id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_5008_0 | /* $Id: minissdpd.c,v 1.37 2014/02/28 18:39:11 nanard Exp $ */
/* MiniUPnP project
* (c) 2007-2014 Thomas Bernard
* website : http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <syslog.h>
#include <ctype.h>
#include <time.h>
#include <sys/queue.h>
/* for chmod : */
#include <sys/stat.h>
/* unix sockets */
#include <sys/un.h>
/* for getpwnam() and getgrnam() */
#include <pwd.h>
#include <grp.h>
#include "upnputils.h"
#include "openssdpsocket.h"
#include "daemonize.h"
#include "codelength.h"
#include "ifacewatch.h"
/* current request management stucture */
struct reqelem {
int socket;
LIST_ENTRY(reqelem) entries;
};
/* divice data structures */
struct header {
const char * p; /* string pointer */
int l; /* string length */
};
#define HEADER_NT 0
#define HEADER_USN 1
#define HEADER_LOCATION 2
struct device {
struct device * next;
time_t t; /* validity time */
struct header headers[3]; /* NT, USN and LOCATION headers */
char data[];
};
#define NTS_SSDP_ALIVE 1
#define NTS_SSDP_BYEBYE 2
#define NTS_SSDP_UPDATE 3
/* discovered device list kept in memory */
struct device * devlist = 0;
/* bootid and configid */
unsigned int upnp_bootid = 1;
unsigned int upnp_configid = 1337;
static const char *
nts_to_str(int nts)
{
switch(nts)
{
case NTS_SSDP_ALIVE:
return "ssdp:alive";
case NTS_SSDP_BYEBYE:
return "ssdp:byebye";
case NTS_SSDP_UPDATE:
return "ssdp:update";
}
return "unknown";
}
/* updateDevice() :
* adds or updates the device to the list.
* return value :
* 0 : the device was updated (or nothing done)
* 1 : the device was new */
static int
updateDevice(const struct header * headers, time_t t)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist; */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
/*printf("found! %d\n", (int)(t - p->t));*/
syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
p->t = t;
/* update Location ! */
if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l)
{
p = realloc(p, sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l );
if(!p) /* allocation error */
{
syslog(LOG_ERR, "updateDevice() : memory allocation error");
return 0;
}
*pp = p;
}
memcpy(p->data + p->headers[0].l + p->headers[1].l,
headers[2].p, headers[2].l);
return 0;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_INFO, "new device discovered : %.*s",
headers[HEADER_USN].l, headers[HEADER_USN].p);
/* add */
{
char * pc;
int i;
p = malloc( sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l );
if(!p) {
syslog(LOG_ERR, "updateDevice(): cannot allocate memory");
return -1;
}
p->next = devlist;
p->t = t;
pc = p->data;
for(i = 0; i < 3; i++)
{
p->headers[i].p = pc;
p->headers[i].l = headers[i].l;
memcpy(pc, headers[i].p, headers[i].l);
pc += headers[i].l;
}
devlist = p;
}
return 1;
}
/* removeDevice() :
* remove a device from the list
* return value :
* 0 : no device removed
* -1 : device removed */
static int
removeDevice(const struct header * headers)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
syslog(LOG_INFO, "remove device : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
*pp = p->next;
free(p);
return -1;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_WARNING, "device not found for removing : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
return 0;
}
/* SendSSDPMSEARCHResponse() :
* build and send response to M-SEARCH SSDP packets. */
static void
SendSSDPMSEARCHResponse(int s, const struct sockaddr * sockname,
const char * st, const char * usn,
const char * server, const char * location)
{
int l, n;
char buf[512];
socklen_t sockname_len;
/*
* follow guideline from document "UPnP Device Architecture 1.0"
* uppercase is recommended.
* DATE: is recommended
* SERVER: OS/ver UPnP/1.0 miniupnpd/1.0
* - check what to put in the 'Cache-Control' header
*
* have a look at the document "UPnP Device Architecture v1.1 */
l = snprintf(buf, sizeof(buf), "HTTP/1.1 200 OK\r\n"
"CACHE-CONTROL: max-age=120\r\n"
/*"DATE: ...\r\n"*/
"ST: %s\r\n"
"USN: %s\r\n"
"EXT:\r\n"
"SERVER: %s\r\n"
"LOCATION: %s\r\n"
"OPT: \"http://schemas.upnp.org/upnp/1/0/\"; ns=01\r\n" /* UDA v1.1 */
"01-NLS: %u\r\n" /* same as BOOTID. UDA v1.1 */
"BOOTID.UPNP.ORG: %u\r\n" /* UDA v1.1 */
"CONFIGID.UPNP.ORG: %u\r\n" /* UDA v1.1 */
"\r\n",
st, usn,
server, location,
upnp_bootid, upnp_bootid, upnp_configid);
#ifdef ENABLE_IPV6
sockname_len = (sockname->sa_family == PF_INET6)
? sizeof(struct sockaddr_in6)
: sizeof(struct sockaddr_in);
#else
sockname_len = sizeof(struct sockaddr_in);
#endif
n = sendto(s, buf, l, 0,
sockname, sockname_len );
if(n < 0) {
/* XXX handle EINTR, EAGAIN, EWOULDBLOCK */
syslog(LOG_ERR, "sendto(udp): %m");
}
}
/* Services stored for answering to M-SEARCH */
struct service {
char * st; /* Service type */
char * usn; /* Unique identifier */
char * server; /* Server string */
char * location; /* URL */
LIST_ENTRY(service) entries;
};
LIST_HEAD(servicehead, service) servicelisthead;
/* Process M-SEARCH requests */
static void
processMSEARCH(int s, const char * st, int st_len,
const struct sockaddr * addr)
{
struct service * serv;
#ifdef ENABLE_IPV6
char buf[64];
#endif
if(!st || st_len==0)
return;
#ifdef ENABLE_IPV6
sockaddr_to_string(addr, buf, sizeof(buf));
syslog(LOG_INFO, "SSDP M-SEARCH from %s ST:%.*s",
buf, st_len, st);
#else
syslog(LOG_INFO, "SSDP M-SEARCH from %s:%d ST: %.*s",
inet_ntoa(((const struct sockaddr_in *)addr)->sin_addr),
ntohs(((const struct sockaddr_in *)addr)->sin_port),
st_len, st);
#endif
if(st_len==8 && (0==memcmp(st, "ssdp:all", 8))) {
/* send a response for all services */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, serv->usn,
serv->server, serv->location);
}
} else if(st_len > 5 && (0==memcmp(st, "uuid:", 5))) {
/* find a matching UUID value */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strncmp(serv->usn, st, st_len)) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, serv->usn,
serv->server, serv->location);
}
}
} else {
/* find matching services */
/* remove version at the end of the ST string */
if(st[st_len-2]==':' && isdigit(st[st_len-1]))
st_len -= 2;
/* answer for each matching service */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strncmp(serv->st, st, st_len)) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, serv->usn,
serv->server, serv->location);
}
}
}
}
/**
* helper function.
* reject any non ASCII or non printable character.
*/
static int
containsForbiddenChars(const unsigned char * p, int len)
{
while(len > 0) {
if(*p < ' ' || *p >= '\x7f')
return 1;
p++;
len--;
}
return 0;
}
#define METHOD_MSEARCH 1
#define METHOD_NOTIFY 2
/* ParseSSDPPacket() :
* parse a received SSDP Packet and call
* updateDevice() or removeDevice() as needed
* return value :
* -1 : a device was removed
* 0 : no device removed nor added
* 1 : a device was added. */
static int
ParseSSDPPacket(int s, const char * p, ssize_t n,
const struct sockaddr * addr)
{
const char * linestart;
const char * lineend;
const char * nameend;
const char * valuestart;
struct header headers[3];
int i, r = 0;
int methodlen;
int nts = -1;
int method = -1;
unsigned int lifetime = 180; /* 3 minutes by default */
const char * st = NULL;
int st_len = 0;
memset(headers, 0, sizeof(headers));
for(methodlen = 0;
methodlen < n && (isalpha(p[methodlen]) || p[methodlen]=='-');
methodlen++);
if(methodlen==8 && 0==memcmp(p, "M-SEARCH", 8))
method = METHOD_MSEARCH;
else if(methodlen==6 && 0==memcmp(p, "NOTIFY", 6))
method = METHOD_NOTIFY;
else if(methodlen==4 && 0==memcmp(p, "HTTP", 4)) {
/* answer to a M-SEARCH => process it as a NOTIFY
* with NTS: ssdp:alive */
method = METHOD_NOTIFY;
nts = NTS_SSDP_ALIVE;
}
linestart = p;
while(linestart < p + n - 2) {
/* start parsing the line : detect line end */
lineend = linestart;
while(lineend < p + n && *lineend != '\n' && *lineend != '\r')
lineend++;
/*printf("line: '%.*s'\n", lineend - linestart, linestart);*/
/* detect name end : ':' character */
nameend = linestart;
while(nameend < lineend && *nameend != ':')
nameend++;
/* detect value */
if(nameend < lineend)
valuestart = nameend + 1;
else
valuestart = nameend;
/* trim spaces */
while(valuestart < lineend && isspace(*valuestart))
valuestart++;
/* suppress leading " if needed */
if(valuestart < lineend && *valuestart=='\"')
valuestart++;
if(nameend > linestart && valuestart < lineend) {
int l = nameend - linestart; /* header name length */
int m = lineend - valuestart; /* header value length */
/* suppress tailing spaces */
while(m>0 && isspace(valuestart[m-1]))
m--;
/* suppress tailing ' if needed */
if(m>0 && valuestart[m-1] == '\"')
m--;
i = -1;
/*printf("--%.*s: (%d)%.*s--\n", l, linestart,
m, m, valuestart);*/
if(l==2 && 0==strncasecmp(linestart, "nt", 2))
i = HEADER_NT;
else if(l==3 && 0==strncasecmp(linestart, "usn", 3))
i = HEADER_USN;
else if(l==3 && 0==strncasecmp(linestart, "nts", 3)) {
if(m==10 && 0==strncasecmp(valuestart, "ssdp:alive", 10))
nts = NTS_SSDP_ALIVE;
else if(m==11 && 0==strncasecmp(valuestart, "ssdp:byebye", 11))
nts = NTS_SSDP_BYEBYE;
else if(m==11 && 0==strncasecmp(valuestart, "ssdp:update", 11))
nts = NTS_SSDP_UPDATE;
}
else if(l==8 && 0==strncasecmp(linestart, "location", 8))
i = HEADER_LOCATION;
else if(l==13 && 0==strncasecmp(linestart, "cache-control", 13)) {
/* parse "name1=value1, name_alone, name2=value2" string */
const char * name = valuestart; /* name */
const char * val; /* value */
int rem = m; /* remaining bytes to process */
while(rem > 0) {
val = name;
while(val < name + rem && *val != '=' && *val != ',')
val++;
if(val >= name + rem)
break;
if(*val == '=') {
while(val < name + rem && (*val == '=' || isspace(*val)))
val++;
if(val >= name + rem)
break;
if(0==strncasecmp(name, "max-age", 7))
lifetime = (unsigned int)strtoul(val, 0, 0);
/* move to the next name=value pair */
while(rem > 0 && *name != ',') {
rem--;
name++;
}
/* skip spaces */
while(rem > 0 && (*name == ',' || isspace(*name))) {
rem--;
name++;
}
} else {
rem -= (val - name);
name = val;
while(rem > 0 && (*name == ',' || isspace(*name))) {
rem--;
name++;
}
}
}
/*syslog(LOG_DEBUG, "**%.*s**%u", m, valuestart, lifetime);*/
} else if(l==2 && 0==strncasecmp(linestart, "st", 2)) {
st = valuestart;
st_len = m;
if(method == METHOD_NOTIFY)
i = HEADER_NT; /* it was a M-SEARCH response */
}
if(i>=0) {
headers[i].p = valuestart;
headers[i].l = m;
}
}
linestart = lineend;
while((*linestart == '\n' || *linestart == '\r') && linestart < p + n)
linestart++;
}
#if 0
printf("NTS=%d\n", nts);
for(i=0; i<3; i++) {
if(headers[i].p)
printf("%d-'%.*s'\n", i, headers[i].l, headers[i].p);
}
#endif
syslog(LOG_DEBUG,"SSDP request: '%.*s' (%d) %s %s=%.*s",
methodlen, p, method, nts_to_str(nts),
(method==METHOD_NOTIFY)?"nt":"st",
(method==METHOD_NOTIFY)?headers[HEADER_NT].l:st_len,
(method==METHOD_NOTIFY)?headers[HEADER_NT].p:st);
switch(method) {
case METHOD_NOTIFY:
if(headers[HEADER_NT].p && headers[HEADER_USN].p && headers[HEADER_LOCATION].p) {
if(nts==NTS_SSDP_ALIVE) {
r = updateDevice(headers, time(NULL) + lifetime);
}
else if(nts==NTS_SSDP_BYEBYE) {
r = removeDevice(headers);
}
}
break;
case METHOD_MSEARCH:
processMSEARCH(s, st, st_len, addr);
break;
default:
syslog(LOG_WARNING, "method %.*s, don't know what to do", methodlen, p);
}
return r;
}
/* OpenUnixSocket()
* open the unix socket and call bind() and listen()
* return -1 in case of error */
static int
OpenUnixSocket(const char * path)
{
struct sockaddr_un addr;
int s;
int rv;
s = socket(AF_UNIX, SOCK_STREAM, 0);
if(s < 0)
{
syslog(LOG_ERR, "socket(AF_UNIX): %m");
return -1;
}
/* unlink the socket pseudo file before binding */
rv = unlink(path);
if(rv < 0 && errno != ENOENT)
{
syslog(LOG_ERR, "unlink(unixsocket, \"%s\"): %m", path);
close(s);
return -1;
}
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path));
if(bind(s, (struct sockaddr *)&addr,
sizeof(struct sockaddr_un)) < 0)
{
syslog(LOG_ERR, "bind(unixsocket, \"%s\"): %m", path);
close(s);
return -1;
}
else if(listen(s, 5) < 0)
{
syslog(LOG_ERR, "listen(unixsocket): %m");
close(s);
return -1;
}
/* Change rights so everyone can communicate with us */
if(chmod(path, 0666) < 0)
{
syslog(LOG_WARNING, "chmod(\"%s\"): %m", path);
}
return s;
}
/* processRequest() :
* process the request coming from a unix socket */
void processRequest(struct reqelem * req)
{
ssize_t n;
unsigned int l, m;
unsigned char buf[2048];
const unsigned char * p;
int type;
struct device * d = devlist;
unsigned char rbuf[4096];
unsigned char * rp = rbuf+1;
unsigned char nrep = 0;
time_t t;
struct service * newserv = NULL;
struct service * serv;
n = read(req->socket, buf, sizeof(buf));
if(n<0) {
if(errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
return; /* try again later */
syslog(LOG_ERR, "(s=%d) processRequest(): read(): %m", req->socket);
goto error;
}
if(n==0) {
syslog(LOG_INFO, "(s=%d) request connection closed", req->socket);
goto error;
}
t = time(NULL);
type = buf[0];
p = buf + 1;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(l == 0 && type != 3) {
syslog(LOG_WARNING, "bad request (length=0)");
goto error;
}
syslog(LOG_INFO, "(s=%d) request type=%d str='%.*s'",
req->socket, type, l, p);
switch(type) {
case 1: /* request by type */
case 2: /* request by USN (unique id) */
case 3: /* everything */
while(d && (nrep < 255)) {
if(d->t < t) {
syslog(LOG_INFO, "outdated device");
} else {
/* test if we can put more responses in the buffer */
if(d->headers[HEADER_LOCATION].l + d->headers[HEADER_NT].l
+ d->headers[HEADER_USN].l + 6
+ (rp - rbuf) >= (int)sizeof(rbuf))
break;
if( (type==1 && 0==memcmp(d->headers[HEADER_NT].p, p, l))
||(type==2 && 0==memcmp(d->headers[HEADER_USN].p, p, l))
||(type==3) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = d->headers[HEADER_LOCATION].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_LOCATION].p, d->headers[HEADER_LOCATION].l);
rp += d->headers[HEADER_LOCATION].l;
m = d->headers[HEADER_NT].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_NT].p, d->headers[HEADER_NT].l);
rp += d->headers[HEADER_NT].l;
m = d->headers[HEADER_USN].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_USN].p, d->headers[HEADER_USN].l);
rp += d->headers[HEADER_USN].l;
nrep++;
}
}
d = d->next;
}
/* Also look in service list */
for(serv = servicelisthead.lh_first;
serv && (nrep < 255);
serv = serv->entries.le_next) {
/* test if we can put more responses in the buffer */
if(strlen(serv->location) + strlen(serv->st)
+ strlen(serv->usn) + 6 + (rp - rbuf) >= sizeof(rbuf))
break;
if( (type==1 && 0==strncmp(serv->st, (const char *)p, l))
||(type==2 && 0==strncmp(serv->usn, (const char *)p, l))
||(type==3) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = strlen(serv->location);
CODELENGTH(m, rp);
memcpy(rp, serv->location, m);
rp += m;
m = strlen(serv->st);
CODELENGTH(m, rp);
memcpy(rp, serv->st, m);
rp += m;
m = strlen(serv->usn);
CODELENGTH(m, rp);
memcpy(rp, serv->usn, m);
rp += m;
nrep++;
}
}
rbuf[0] = nrep;
syslog(LOG_DEBUG, "(s=%d) response : %d device%s",
req->socket, nrep, (nrep > 1) ? "s" : "");
if(write(req->socket, rbuf, rp - rbuf) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
break;
case 4: /* submit service */
newserv = malloc(sizeof(struct service));
if(!newserv) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (st contains forbidden chars)");
goto error;
}
newserv->st = malloc(l + 1);
if(!newserv->st) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->st, p, l);
newserv->st[l] = '\0';
p += l;
if(p >= buf + n) {
syslog(LOG_WARNING, "bad request (missing usn)");
goto error;
}
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (usn contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "usn='%.*s'", l, p);
newserv->usn = malloc(l + 1);
if(!newserv->usn) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->usn, p, l);
newserv->usn[l] = '\0';
p += l;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (server contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "server='%.*s'", l, p);
newserv->server = malloc(l + 1);
if(!newserv->server) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->server, p, l);
newserv->server[l] = '\0';
p += l;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (location contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "location='%.*s'", l, p);
newserv->location = malloc(l + 1);
if(!newserv->location) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->location, p, l);
newserv->location[l] = '\0';
/* look in service list for duplicate */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strcmp(newserv->usn, serv->usn)
&& 0 == strcmp(newserv->st, serv->st)) {
syslog(LOG_INFO, "Service allready in the list. Updating...");
free(newserv->st);
free(newserv->usn);
free(serv->server);
serv->server = newserv->server;
free(serv->location);
serv->location = newserv->location;
free(newserv);
newserv = NULL;
return;
}
}
/* Inserting new service */
LIST_INSERT_HEAD(&servicelisthead, newserv, entries);
newserv = NULL;
/*rbuf[0] = '\0';
if(write(req->socket, rbuf, 1) < 0)
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
*/
break;
default:
syslog(LOG_WARNING, "Unknown request type %d", type);
rbuf[0] = '\0';
if(write(req->socket, rbuf, 1) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
}
return;
error:
if(newserv) {
free(newserv->st);
free(newserv->usn);
free(newserv->server);
free(newserv->location);
free(newserv);
newserv = NULL;
}
close(req->socket);
req->socket = -1;
return;
}
static volatile sig_atomic_t quitting = 0;
/* SIGTERM signal handler */
static void
sigterm(int sig)
{
(void)sig;
/*int save_errno = errno;*/
/*signal(sig, SIG_IGN);*/
#if 0
/* calling syslog() is forbidden in a signal handler according to
* signal(3) */
syslog(LOG_NOTICE, "received signal %d, good-bye", sig);
#endif
quitting = 1;
/*errno = save_errno;*/
}
#define PORT 1900
#define XSTR(s) STR(s)
#define STR(s) #s
#define UPNP_MCAST_ADDR "239.255.255.250"
/* for IPv6 */
#define UPNP_MCAST_LL_ADDR "FF02::C" /* link-local */
#define UPNP_MCAST_SL_ADDR "FF05::C" /* site-local */
/* send the M-SEARCH request for all devices */
void ssdpDiscoverAll(int s, int ipv6)
{
static const char MSearchMsgFmt[] =
"M-SEARCH * HTTP/1.1\r\n"
"HOST: %s:" XSTR(PORT) "\r\n"
"ST: ssdp:all\r\n"
"MAN: \"ssdp:discover\"\r\n"
"MX: %u\r\n"
"\r\n";
char bufr[512];
int n;
int mx = 3;
int linklocal = 1;
struct sockaddr_storage sockudp_w;
{
n = snprintf(bufr, sizeof(bufr),
MSearchMsgFmt,
ipv6 ?
(linklocal ? "[" UPNP_MCAST_LL_ADDR "]" : "[" UPNP_MCAST_SL_ADDR "]")
: UPNP_MCAST_ADDR, mx);
memset(&sockudp_w, 0, sizeof(struct sockaddr_storage));
if(ipv6) {
struct sockaddr_in6 * p = (struct sockaddr_in6 *)&sockudp_w;
p->sin6_family = AF_INET6;
p->sin6_port = htons(PORT);
inet_pton(AF_INET6,
linklocal ? UPNP_MCAST_LL_ADDR : UPNP_MCAST_SL_ADDR,
&(p->sin6_addr));
} else {
struct sockaddr_in * p = (struct sockaddr_in *)&sockudp_w;
p->sin_family = AF_INET;
p->sin_port = htons(PORT);
p->sin_addr.s_addr = inet_addr(UPNP_MCAST_ADDR);
}
n = sendto(s, bufr, n, 0, (const struct sockaddr *)&sockudp_w,
ipv6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
if (n < 0) {
/* XXX : EINTR EWOULDBLOCK EAGAIN */
syslog(LOG_ERR, "sendto: %m");
}
}
}
/* main(): program entry point */
int main(int argc, char * * argv)
{
int ret = 0;
int pid;
struct sigaction sa;
char buf[1500];
ssize_t n;
int s_ssdp = -1; /* udp socket receiving ssdp packets */
#ifdef ENABLE_IPV6
int s_ssdp6 = -1; /* udp socket receiving ssdp packets IPv6*/
#else
#define s_ssdp6 (-1)
#endif
int s_unix = -1; /* unix socket communicating with clients */
int s_ifacewatch = -1; /* socket to receive Route / network interface config changes */
int s;
LIST_HEAD(reqstructhead, reqelem) reqlisthead;
struct reqelem * req;
struct reqelem * reqnext;
fd_set readfds;
const char * if_addr[MAX_IF_ADDR];
int n_if_addr = 0;
int i;
const char * sockpath = "/var/run/minissdpd.sock";
const char * pidfilename = "/var/run/minissdpd.pid";
int debug_flag = 0;
int ipv6 = 0;
int deltadev = 0;
struct sockaddr_in sendername;
socklen_t sendername_len;
#ifdef ENABLE_IPV6
struct sockaddr_in6 sendername6;
socklen_t sendername6_len;
#endif
LIST_INIT(&reqlisthead);
LIST_INIT(&servicelisthead);
/* process command line */
for(i=1; i<argc; i++)
{
if(0==strcmp(argv[i], "-i")) {
if(n_if_addr < MAX_IF_ADDR)
if_addr[n_if_addr++] = argv[++i];
else
syslog(LOG_WARNING, "Max number of interface address set to %d, "
"ignoring %s", MAX_IF_ADDR, argv[++i]);
} else if(0==strcmp(argv[i], "-d"))
debug_flag = 1;
else if(0==strcmp(argv[i], "-s"))
sockpath = argv[++i];
else if(0==strcmp(argv[i], "-p"))
pidfilename = argv[++i];
#ifdef ENABLE_IPV6
else if(0==strcmp(argv[i], "-6"))
ipv6 = 1;
#endif
}
if(n_if_addr < 1)
{
fprintf(stderr,
"Usage: %s [-d] [-6] [-s socket] [-p pidfile] "
"-i <interface> [-i <interface2>] ...\n",
argv[0]);
fprintf(stderr,
"\n <interface> is either an IPv4 address such as 192.168.1.42, or an\ninterface name such as eth0.\n");
fprintf(stderr,
"\n By default, socket will be open as %s\n"
"and pid written to file %s\n",
sockpath, pidfilename);
return 1;
}
/* open log */
openlog("minissdpd",
LOG_CONS|LOG_PID|(debug_flag?LOG_PERROR:0),
LOG_MINISSDPD);
if(!debug_flag) /* speed things up and ignore LOG_INFO and LOG_DEBUG */
setlogmask(LOG_UPTO(LOG_NOTICE));
if(checkforrunning(pidfilename) < 0)
{
syslog(LOG_ERR, "MiniSSDPd is already running. EXITING");
return 1;
}
/* set signal handlers */
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sigterm;
if(sigaction(SIGTERM, &sa, NULL))
{
syslog(LOG_ERR, "Failed to set SIGTERM handler. EXITING");
ret = 1;
goto quit;
}
if(sigaction(SIGINT, &sa, NULL))
{
syslog(LOG_ERR, "Failed to set SIGINT handler. EXITING");
ret = 1;
goto quit;
}
/* open route/interface config changes socket */
s_ifacewatch = OpenAndConfInterfaceWatchSocket();
/* open UDP socket(s) for receiving SSDP packets */
s_ssdp = OpenAndConfSSDPReceiveSocket(n_if_addr, if_addr, 0);
if(s_ssdp < 0)
{
syslog(LOG_ERR, "Cannot open socket for receiving SSDP messages, exiting");
ret = 1;
goto quit;
}
#ifdef ENABLE_IPV6
if(ipv6) {
s_ssdp6 = OpenAndConfSSDPReceiveSocket(n_if_addr, if_addr, 1);
if(s_ssdp6 < 0)
{
syslog(LOG_ERR, "Cannot open socket for receiving SSDP messages (IPv6), exiting");
ret = 1;
goto quit;
}
}
#endif
/* Open Unix socket to communicate with other programs on
* the same machine */
s_unix = OpenUnixSocket(sockpath);
if(s_unix < 0)
{
syslog(LOG_ERR, "Cannot open unix socket for communicating with clients. Exiting");
ret = 1;
goto quit;
}
/* drop privileges */
#if 0
/* if we drop privileges, how to unlink(/var/run/minissdpd.sock) ? */
if(getuid() == 0) {
struct passwd * user;
struct group * group;
user = getpwnam("nobody");
if(!user) {
syslog(LOG_ERR, "getpwnam(\"%s\") : %m", "nobody");
ret = 1;
goto quit;
}
group = getgrnam("nogroup");
if(!group) {
syslog(LOG_ERR, "getgrnam(\"%s\") : %m", "nogroup");
ret = 1;
goto quit;
}
if(setgid(group->gr_gid) < 0) {
syslog(LOG_ERR, "setgit(%d) : %m", group->gr_gid);
ret = 1;
goto quit;
}
if(setuid(user->pw_uid) < 0) {
syslog(LOG_ERR, "setuid(%d) : %m", user->pw_uid);
ret = 1;
goto quit;
}
}
#endif
/* daemonize or in any case get pid ! */
if(debug_flag)
pid = getpid();
else {
#ifdef USE_DAEMON
if(daemon(0, 0) < 0)
perror("daemon()");
pid = getpid();
#else
pid = daemonize();
#endif
}
writepidfile(pidfilename, pid);
/* send M-SEARCH ssdp:all Requests */
ssdpDiscoverAll(s_ssdp, 0);
if(s_ssdp6 >= 0)
ssdpDiscoverAll(s_ssdp6, 1);
/* Main loop */
while(!quitting)
{
/* fill readfds fd_set */
FD_ZERO(&readfds);
if(s_ssdp >= 0) {
FD_SET(s_ssdp, &readfds);
}
#ifdef ENABLE_IPV6
if(s_ssdp6 >= 0) {
FD_SET(s_ssdp6, &readfds);
}
#endif
if(s_ifacewatch >= 0) {
FD_SET(s_ifacewatch, &readfds);
}
FD_SET(s_unix, &readfds);
for(req = reqlisthead.lh_first; req; req = req->entries.le_next)
{
if(req->socket >= 0)
FD_SET(req->socket, &readfds);
}
/* select call */
if(select(FD_SETSIZE, &readfds, 0, 0, 0) < 0)
{
if(errno != EINTR)
{
syslog(LOG_ERR, "select: %m");
break; /* quit */
}
continue; /* try again */
}
#ifdef ENABLE_IPV6
if((s_ssdp6 >= 0) && FD_ISSET(s_ssdp6, &readfds))
{
sendername6_len = sizeof(struct sockaddr_in6);
n = recvfrom(s_ssdp6, buf, sizeof(buf), 0,
(struct sockaddr *)&sendername6, &sendername6_len);
if(n<0)
{
/* EAGAIN, EWOULDBLOCK, EINTR : silently ignore (try again next time)
* other errors : log to LOG_ERR */
if(errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
syslog(LOG_ERR, "recvfrom: %m");
}
else
{
/* Parse and process the packet received */
/*printf("%.*s", n, buf);*/
i = ParseSSDPPacket(s_ssdp6, buf, n,
(struct sockaddr *)&sendername6);
syslog(LOG_DEBUG, "** i=%d deltadev=%d **", i, deltadev);
if(i==0 || (i*deltadev < 0))
{
if(deltadev > 0)
syslog(LOG_NOTICE, "%d new devices added", deltadev);
else if(deltadev < 0)
syslog(LOG_NOTICE, "%d devices removed (good-bye!)", -deltadev);
deltadev = i;
}
else if((i*deltadev) >= 0)
{
deltadev += i;
}
}
}
#endif
if(FD_ISSET(s_ssdp, &readfds))
{
sendername_len = sizeof(struct sockaddr_in);
n = recvfrom(s_ssdp, buf, sizeof(buf), 0,
(struct sockaddr *)&sendername, &sendername_len);
if(n<0)
{
/* EAGAIN, EWOULDBLOCK, EINTR : silently ignore (try again next time)
* other errors : log to LOG_ERR */
if(errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
syslog(LOG_ERR, "recvfrom: %m");
}
else
{
/* Parse and process the packet received */
/*printf("%.*s", n, buf);*/
i = ParseSSDPPacket(s_ssdp, buf, n,
(struct sockaddr *)&sendername);
syslog(LOG_DEBUG, "** i=%d deltadev=%d **", i, deltadev);
if(i==0 || (i*deltadev < 0))
{
if(deltadev > 0)
syslog(LOG_NOTICE, "%d new devices added", deltadev);
else if(deltadev < 0)
syslog(LOG_NOTICE, "%d devices removed (good-bye!)", -deltadev);
deltadev = i;
}
else if((i*deltadev) >= 0)
{
deltadev += i;
}
}
}
/* processing unix socket requests */
for(req = reqlisthead.lh_first; req;)
{
reqnext = req->entries.le_next;
if((req->socket >= 0) && FD_ISSET(req->socket, &readfds))
{
processRequest(req);
}
if(req->socket < 0)
{
LIST_REMOVE(req, entries);
free(req);
}
req = reqnext;
}
/* processing new requests */
if(FD_ISSET(s_unix, &readfds))
{
struct reqelem * tmp;
s = accept(s_unix, NULL, NULL);
if(s<0)
{
syslog(LOG_ERR, "accept(s_unix): %m");
}
else
{
syslog(LOG_INFO, "(s=%d) new request connection", s);
if(!set_non_blocking(s))
syslog(LOG_WARNING, "Failed to set new socket non blocking : %m");
tmp = malloc(sizeof(struct reqelem));
if(!tmp)
{
syslog(LOG_ERR, "cannot allocate memory for request");
close(s);
}
else
{
tmp->socket = s;
LIST_INSERT_HEAD(&reqlisthead, tmp, entries);
}
}
}
/* processing route/network interface config changes */
if((s_ifacewatch >= 0) && FD_ISSET(s_ifacewatch, &readfds)) {
ProcessInterfaceWatch(s_ifacewatch, s_ssdp, s_ssdp6, n_if_addr, if_addr);
}
}
/* closing and cleaning everything */
quit:
if(s_ssdp >= 0) {
close(s_ssdp);
s_ssdp = -1;
}
#ifdef ENABLE_IPV6
if(s_ssdp6 >= 0) {
close(s_ssdp6);
s_ssdp6 = -1;
}
#endif
if(s_unix >= 0) {
close(s_unix);
s_unix = -1;
if(unlink(sockpath) < 0)
syslog(LOG_ERR, "unlink(%s): %m", sockpath);
}
if(s_ifacewatch >= 0) {
close(s_ifacewatch);
s_ifacewatch = -1;
}
if(unlink(pidfilename) < 0)
syslog(LOG_ERR, "unlink(%s): %m", pidfilename);
closelog();
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-388/c/bad_5008_0 |
crossvul-cpp_data_bad_5494_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 "irq.h"
#include "mmu.h"
#include "cpuid.h"
#include "lapic.h"
#include <linux/kvm_host.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/sched.h>
#include <linux/moduleparam.h>
#include <linux/mod_devicetable.h>
#include <linux/trace_events.h>
#include <linux/slab.h>
#include <linux/tboot.h>
#include <linux/hrtimer.h>
#include "kvm_cache_regs.h"
#include "x86.h"
#include <asm/cpu.h>
#include <asm/io.h>
#include <asm/desc.h>
#include <asm/vmx.h>
#include <asm/virtext.h>
#include <asm/mce.h>
#include <asm/fpu/internal.h>
#include <asm/perf_event.h>
#include <asm/debugreg.h>
#include <asm/kexec.h>
#include <asm/apic.h>
#include <asm/irq_remapping.h>
#include "trace.h"
#include "pmu.h"
#define __ex(x) __kvm_handle_fault_on_reboot(x)
#define __ex_clear(x, reg) \
____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
MODULE_AUTHOR("Qumranet");
MODULE_LICENSE("GPL");
static const struct x86_cpu_id vmx_cpu_id[] = {
X86_FEATURE_MATCH(X86_FEATURE_VMX),
{}
};
MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
static bool __read_mostly enable_vpid = 1;
module_param_named(vpid, enable_vpid, bool, 0444);
static bool __read_mostly flexpriority_enabled = 1;
module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
static bool __read_mostly enable_ept = 1;
module_param_named(ept, enable_ept, bool, S_IRUGO);
static bool __read_mostly enable_unrestricted_guest = 1;
module_param_named(unrestricted_guest,
enable_unrestricted_guest, bool, S_IRUGO);
static bool __read_mostly enable_ept_ad_bits = 1;
module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
static bool __read_mostly emulate_invalid_guest_state = true;
module_param(emulate_invalid_guest_state, bool, S_IRUGO);
static bool __read_mostly vmm_exclusive = 1;
module_param(vmm_exclusive, bool, S_IRUGO);
static bool __read_mostly fasteoi = 1;
module_param(fasteoi, bool, S_IRUGO);
static bool __read_mostly enable_apicv = 1;
module_param(enable_apicv, bool, S_IRUGO);
static bool __read_mostly enable_shadow_vmcs = 1;
module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
/*
* If nested=1, nested virtualization is supported, i.e., guests may use
* VMX and be a hypervisor for its own guests. If nested=0, guests may not
* use VMX instructions.
*/
static bool __read_mostly nested = 0;
module_param(nested, bool, S_IRUGO);
static u64 __read_mostly host_xss;
static bool __read_mostly enable_pml = 1;
module_param_named(pml, enable_pml, bool, S_IRUGO);
#define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
/* Guest_tsc -> host_tsc conversion requires 64-bit division. */
static int __read_mostly cpu_preemption_timer_multi;
static bool __read_mostly enable_preemption_timer = 1;
#ifdef CONFIG_X86_64
module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
#endif
#define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
#define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
#define KVM_VM_CR0_ALWAYS_ON \
(KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
#define KVM_CR4_GUEST_OWNED_BITS \
(X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
| X86_CR4_OSXMMEXCPT | X86_CR4_TSD)
#define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
#define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
#define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
#define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
#define VMX_VPID_EXTENT_SUPPORTED_MASK \
(VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
/*
* Hyper-V requires all of these, so mark them as supported even though
* they are just treated the same as all-context.
*/
#define VMX_VPID_EXTENT_SUPPORTED_MASK \
(VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
/*
* These 2 parameters are used to config the controls for Pause-Loop Exiting:
* ple_gap: upper bound on the amount of time between two successive
* executions of PAUSE in a loop. Also indicate if ple enabled.
* According to test, this time is usually smaller than 128 cycles.
* ple_window: upper bound on the amount of time a guest is allowed to execute
* in a PAUSE loop. Tests indicate that most spinlocks are held for
* less than 2^12 cycles
* Time is measured based on a counter that runs at the same rate as the TSC,
* refer SDM volume 3b section 21.6.13 & 22.1.3.
*/
#define KVM_VMX_DEFAULT_PLE_GAP 128
#define KVM_VMX_DEFAULT_PLE_WINDOW 4096
#define KVM_VMX_DEFAULT_PLE_WINDOW_GROW 2
#define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
#define KVM_VMX_DEFAULT_PLE_WINDOW_MAX \
INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
module_param(ple_gap, int, S_IRUGO);
static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
module_param(ple_window, int, S_IRUGO);
/* Default doubles per-vcpu window every exit. */
static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
module_param(ple_window_grow, int, S_IRUGO);
/* Default resets per-vcpu window every exit to ple_window. */
static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
module_param(ple_window_shrink, int, S_IRUGO);
/* Default is to compute the maximum so we can never overflow. */
static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
static int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
module_param(ple_window_max, int, S_IRUGO);
extern const ulong vmx_return;
#define NR_AUTOLOAD_MSRS 8
#define VMCS02_POOL_SIZE 1
struct vmcs {
u32 revision_id;
u32 abort;
char data[0];
};
/*
* Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
* remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
* loaded on this CPU (so we can clear them if the CPU goes down).
*/
struct loaded_vmcs {
struct vmcs *vmcs;
struct vmcs *shadow_vmcs;
int cpu;
int launched;
struct list_head loaded_vmcss_on_cpu_link;
};
struct shared_msr_entry {
unsigned index;
u64 data;
u64 mask;
};
/*
* struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
* single nested guest (L2), hence the name vmcs12. Any VMX implementation has
* a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
* stored in guest memory specified by VMPTRLD, but is opaque to the guest,
* which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
* More than one of these structures may exist, if L1 runs multiple L2 guests.
* nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
* underlying hardware which will be used to run L2.
* This structure is packed to ensure that its layout is identical across
* machines (necessary for live migration).
* If there are changes in this struct, VMCS12_REVISION must be changed.
*/
typedef u64 natural_width;
struct __packed vmcs12 {
/* According to the Intel spec, a VMCS region must start with the
* following two fields. Then follow implementation-specific data.
*/
u32 revision_id;
u32 abort;
u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
u32 padding[7]; /* room for future expansion */
u64 io_bitmap_a;
u64 io_bitmap_b;
u64 msr_bitmap;
u64 vm_exit_msr_store_addr;
u64 vm_exit_msr_load_addr;
u64 vm_entry_msr_load_addr;
u64 tsc_offset;
u64 virtual_apic_page_addr;
u64 apic_access_addr;
u64 posted_intr_desc_addr;
u64 ept_pointer;
u64 eoi_exit_bitmap0;
u64 eoi_exit_bitmap1;
u64 eoi_exit_bitmap2;
u64 eoi_exit_bitmap3;
u64 xss_exit_bitmap;
u64 guest_physical_address;
u64 vmcs_link_pointer;
u64 guest_ia32_debugctl;
u64 guest_ia32_pat;
u64 guest_ia32_efer;
u64 guest_ia32_perf_global_ctrl;
u64 guest_pdptr0;
u64 guest_pdptr1;
u64 guest_pdptr2;
u64 guest_pdptr3;
u64 guest_bndcfgs;
u64 host_ia32_pat;
u64 host_ia32_efer;
u64 host_ia32_perf_global_ctrl;
u64 padding64[8]; /* room for future expansion */
/*
* To allow migration of L1 (complete with its L2 guests) between
* machines of different natural widths (32 or 64 bit), we cannot have
* unsigned long fields with no explict size. We use u64 (aliased
* natural_width) instead. Luckily, x86 is little-endian.
*/
natural_width cr0_guest_host_mask;
natural_width cr4_guest_host_mask;
natural_width cr0_read_shadow;
natural_width cr4_read_shadow;
natural_width cr3_target_value0;
natural_width cr3_target_value1;
natural_width cr3_target_value2;
natural_width cr3_target_value3;
natural_width exit_qualification;
natural_width guest_linear_address;
natural_width guest_cr0;
natural_width guest_cr3;
natural_width guest_cr4;
natural_width guest_es_base;
natural_width guest_cs_base;
natural_width guest_ss_base;
natural_width guest_ds_base;
natural_width guest_fs_base;
natural_width guest_gs_base;
natural_width guest_ldtr_base;
natural_width guest_tr_base;
natural_width guest_gdtr_base;
natural_width guest_idtr_base;
natural_width guest_dr7;
natural_width guest_rsp;
natural_width guest_rip;
natural_width guest_rflags;
natural_width guest_pending_dbg_exceptions;
natural_width guest_sysenter_esp;
natural_width guest_sysenter_eip;
natural_width host_cr0;
natural_width host_cr3;
natural_width host_cr4;
natural_width host_fs_base;
natural_width host_gs_base;
natural_width host_tr_base;
natural_width host_gdtr_base;
natural_width host_idtr_base;
natural_width host_ia32_sysenter_esp;
natural_width host_ia32_sysenter_eip;
natural_width host_rsp;
natural_width host_rip;
natural_width paddingl[8]; /* room for future expansion */
u32 pin_based_vm_exec_control;
u32 cpu_based_vm_exec_control;
u32 exception_bitmap;
u32 page_fault_error_code_mask;
u32 page_fault_error_code_match;
u32 cr3_target_count;
u32 vm_exit_controls;
u32 vm_exit_msr_store_count;
u32 vm_exit_msr_load_count;
u32 vm_entry_controls;
u32 vm_entry_msr_load_count;
u32 vm_entry_intr_info_field;
u32 vm_entry_exception_error_code;
u32 vm_entry_instruction_len;
u32 tpr_threshold;
u32 secondary_vm_exec_control;
u32 vm_instruction_error;
u32 vm_exit_reason;
u32 vm_exit_intr_info;
u32 vm_exit_intr_error_code;
u32 idt_vectoring_info_field;
u32 idt_vectoring_error_code;
u32 vm_exit_instruction_len;
u32 vmx_instruction_info;
u32 guest_es_limit;
u32 guest_cs_limit;
u32 guest_ss_limit;
u32 guest_ds_limit;
u32 guest_fs_limit;
u32 guest_gs_limit;
u32 guest_ldtr_limit;
u32 guest_tr_limit;
u32 guest_gdtr_limit;
u32 guest_idtr_limit;
u32 guest_es_ar_bytes;
u32 guest_cs_ar_bytes;
u32 guest_ss_ar_bytes;
u32 guest_ds_ar_bytes;
u32 guest_fs_ar_bytes;
u32 guest_gs_ar_bytes;
u32 guest_ldtr_ar_bytes;
u32 guest_tr_ar_bytes;
u32 guest_interruptibility_info;
u32 guest_activity_state;
u32 guest_sysenter_cs;
u32 host_ia32_sysenter_cs;
u32 vmx_preemption_timer_value;
u32 padding32[7]; /* room for future expansion */
u16 virtual_processor_id;
u16 posted_intr_nv;
u16 guest_es_selector;
u16 guest_cs_selector;
u16 guest_ss_selector;
u16 guest_ds_selector;
u16 guest_fs_selector;
u16 guest_gs_selector;
u16 guest_ldtr_selector;
u16 guest_tr_selector;
u16 guest_intr_status;
u16 host_es_selector;
u16 host_cs_selector;
u16 host_ss_selector;
u16 host_ds_selector;
u16 host_fs_selector;
u16 host_gs_selector;
u16 host_tr_selector;
};
/*
* VMCS12_REVISION is an arbitrary id that should be changed if the content or
* layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
* VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
*/
#define VMCS12_REVISION 0x11e57ed0
/*
* VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
* and any VMCS region. Although only sizeof(struct vmcs12) are used by the
* current implementation, 4K are reserved to avoid future complications.
*/
#define VMCS12_SIZE 0x1000
/* Used to remember the last vmcs02 used for some recently used vmcs12s */
struct vmcs02_list {
struct list_head list;
gpa_t vmptr;
struct loaded_vmcs vmcs02;
};
/*
* The nested_vmx structure is part of vcpu_vmx, and holds information we need
* for correct emulation of VMX (i.e., nested VMX) on this vcpu.
*/
struct nested_vmx {
/* Has the level1 guest done vmxon? */
bool vmxon;
gpa_t vmxon_ptr;
/* The guest-physical address of the current VMCS L1 keeps for L2 */
gpa_t current_vmptr;
/* The host-usable pointer to the above */
struct page *current_vmcs12_page;
struct vmcs12 *current_vmcs12;
/*
* Cache of the guest's VMCS, existing outside of guest memory.
* Loaded from guest memory during VMPTRLD. Flushed to guest
* memory during VMXOFF, VMCLEAR, VMPTRLD.
*/
struct vmcs12 *cached_vmcs12;
/*
* Indicates if the shadow vmcs must be updated with the
* data hold by vmcs12
*/
bool sync_shadow_vmcs;
/* vmcs02_list cache of VMCSs recently used to run L2 guests */
struct list_head vmcs02_pool;
int vmcs02_num;
bool change_vmcs01_virtual_x2apic_mode;
/* L2 must run next, and mustn't decide to exit to L1. */
bool nested_run_pending;
/*
* Guest pages referred to in vmcs02 with host-physical pointers, so
* we must keep them pinned while L2 runs.
*/
struct page *apic_access_page;
struct page *virtual_apic_page;
struct page *pi_desc_page;
struct pi_desc *pi_desc;
bool pi_pending;
u16 posted_intr_nv;
unsigned long *msr_bitmap;
struct hrtimer preemption_timer;
bool preemption_timer_expired;
/* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
u64 vmcs01_debugctl;
u16 vpid02;
u16 last_vpid;
/*
* We only store the "true" versions of the VMX capability MSRs. We
* generate the "non-true" versions by setting the must-be-1 bits
* according to the SDM.
*/
u32 nested_vmx_procbased_ctls_low;
u32 nested_vmx_procbased_ctls_high;
u32 nested_vmx_secondary_ctls_low;
u32 nested_vmx_secondary_ctls_high;
u32 nested_vmx_pinbased_ctls_low;
u32 nested_vmx_pinbased_ctls_high;
u32 nested_vmx_exit_ctls_low;
u32 nested_vmx_exit_ctls_high;
u32 nested_vmx_entry_ctls_low;
u32 nested_vmx_entry_ctls_high;
u32 nested_vmx_misc_low;
u32 nested_vmx_misc_high;
u32 nested_vmx_ept_caps;
u32 nested_vmx_vpid_caps;
u64 nested_vmx_basic;
u64 nested_vmx_cr0_fixed0;
u64 nested_vmx_cr0_fixed1;
u64 nested_vmx_cr4_fixed0;
u64 nested_vmx_cr4_fixed1;
u64 nested_vmx_vmcs_enum;
};
#define POSTED_INTR_ON 0
#define POSTED_INTR_SN 1
/* Posted-Interrupt Descriptor */
struct pi_desc {
u32 pir[8]; /* Posted interrupt requested */
union {
struct {
/* bit 256 - Outstanding Notification */
u16 on : 1,
/* bit 257 - Suppress Notification */
sn : 1,
/* bit 271:258 - Reserved */
rsvd_1 : 14;
/* bit 279:272 - Notification Vector */
u8 nv;
/* bit 287:280 - Reserved */
u8 rsvd_2;
/* bit 319:288 - Notification Destination */
u32 ndst;
};
u64 control;
};
u32 rsvd[6];
} __aligned(64);
static bool pi_test_and_set_on(struct pi_desc *pi_desc)
{
return test_and_set_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
{
return test_and_clear_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
{
return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
}
static inline void pi_clear_sn(struct pi_desc *pi_desc)
{
return clear_bit(POSTED_INTR_SN,
(unsigned long *)&pi_desc->control);
}
static inline void pi_set_sn(struct pi_desc *pi_desc)
{
return set_bit(POSTED_INTR_SN,
(unsigned long *)&pi_desc->control);
}
static inline void pi_clear_on(struct pi_desc *pi_desc)
{
clear_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static inline int pi_test_on(struct pi_desc *pi_desc)
{
return test_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static inline int pi_test_sn(struct pi_desc *pi_desc)
{
return test_bit(POSTED_INTR_SN,
(unsigned long *)&pi_desc->control);
}
struct vcpu_vmx {
struct kvm_vcpu vcpu;
unsigned long host_rsp;
u8 fail;
bool nmi_known_unmasked;
u32 exit_intr_info;
u32 idt_vectoring_info;
ulong rflags;
struct shared_msr_entry *guest_msrs;
int nmsrs;
int save_nmsrs;
unsigned long host_idt_base;
#ifdef CONFIG_X86_64
u64 msr_host_kernel_gs_base;
u64 msr_guest_kernel_gs_base;
#endif
u32 vm_entry_controls_shadow;
u32 vm_exit_controls_shadow;
/*
* loaded_vmcs points to the VMCS currently used in this vcpu. For a
* non-nested (L1) guest, it always points to vmcs01. For a nested
* guest (L2), it points to a different VMCS.
*/
struct loaded_vmcs vmcs01;
struct loaded_vmcs *loaded_vmcs;
bool __launched; /* temporary, used in vmx_vcpu_run */
struct msr_autoload {
unsigned nr;
struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
} msr_autoload;
struct {
int loaded;
u16 fs_sel, gs_sel, ldt_sel;
#ifdef CONFIG_X86_64
u16 ds_sel, es_sel;
#endif
int gs_ldt_reload_needed;
int fs_reload_needed;
u64 msr_host_bndcfgs;
unsigned long vmcs_host_cr4; /* May not match real cr4 */
} host_state;
struct {
int vm86_active;
ulong save_rflags;
struct kvm_segment segs[8];
} rmode;
struct {
u32 bitmask; /* 4 bits per segment (1 bit per field) */
struct kvm_save_segment {
u16 selector;
unsigned long base;
u32 limit;
u32 ar;
} seg[8];
} segment_cache;
int vpid;
bool emulation_required;
/* Support for vnmi-less CPUs */
int soft_vnmi_blocked;
ktime_t entry_time;
s64 vnmi_blocked_time;
u32 exit_reason;
/* Posted interrupt descriptor */
struct pi_desc pi_desc;
/* Support for a guest hypervisor (nested VMX) */
struct nested_vmx nested;
/* Dynamic PLE window. */
int ple_window;
bool ple_window_dirty;
/* Support for PML */
#define PML_ENTITY_NUM 512
struct page *pml_pg;
/* apic deadline value in host tsc */
u64 hv_deadline_tsc;
u64 current_tsc_ratio;
bool guest_pkru_valid;
u32 guest_pkru;
u32 host_pkru;
/*
* Only bits masked by msr_ia32_feature_control_valid_bits can be set in
* msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
* in msr_ia32_feature_control_valid_bits.
*/
u64 msr_ia32_feature_control;
u64 msr_ia32_feature_control_valid_bits;
};
enum segment_cache_field {
SEG_FIELD_SEL = 0,
SEG_FIELD_BASE = 1,
SEG_FIELD_LIMIT = 2,
SEG_FIELD_AR = 3,
SEG_FIELD_NR = 4
};
static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
{
return container_of(vcpu, struct vcpu_vmx, vcpu);
}
static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
{
return &(to_vmx(vcpu)->pi_desc);
}
#define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
#define FIELD(number, name) [number] = VMCS12_OFFSET(name)
#define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \
[number##_HIGH] = VMCS12_OFFSET(name)+4
static unsigned long shadow_read_only_fields[] = {
/*
* We do NOT shadow fields that are modified when L0
* traps and emulates any vmx instruction (e.g. VMPTRLD,
* VMXON...) executed by L1.
* For example, VM_INSTRUCTION_ERROR is read
* by L1 if a vmx instruction fails (part of the error path).
* Note the code assumes this logic. If for some reason
* we start shadowing these fields then we need to
* force a shadow sync when L0 emulates vmx instructions
* (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
* by nested_vmx_failValid)
*/
VM_EXIT_REASON,
VM_EXIT_INTR_INFO,
VM_EXIT_INSTRUCTION_LEN,
IDT_VECTORING_INFO_FIELD,
IDT_VECTORING_ERROR_CODE,
VM_EXIT_INTR_ERROR_CODE,
EXIT_QUALIFICATION,
GUEST_LINEAR_ADDRESS,
GUEST_PHYSICAL_ADDRESS
};
static int max_shadow_read_only_fields =
ARRAY_SIZE(shadow_read_only_fields);
static unsigned long shadow_read_write_fields[] = {
TPR_THRESHOLD,
GUEST_RIP,
GUEST_RSP,
GUEST_CR0,
GUEST_CR3,
GUEST_CR4,
GUEST_INTERRUPTIBILITY_INFO,
GUEST_RFLAGS,
GUEST_CS_SELECTOR,
GUEST_CS_AR_BYTES,
GUEST_CS_LIMIT,
GUEST_CS_BASE,
GUEST_ES_BASE,
GUEST_BNDCFGS,
CR0_GUEST_HOST_MASK,
CR0_READ_SHADOW,
CR4_READ_SHADOW,
TSC_OFFSET,
EXCEPTION_BITMAP,
CPU_BASED_VM_EXEC_CONTROL,
VM_ENTRY_EXCEPTION_ERROR_CODE,
VM_ENTRY_INTR_INFO_FIELD,
VM_ENTRY_INSTRUCTION_LEN,
VM_ENTRY_EXCEPTION_ERROR_CODE,
HOST_FS_BASE,
HOST_GS_BASE,
HOST_FS_SELECTOR,
HOST_GS_SELECTOR
};
static int max_shadow_read_write_fields =
ARRAY_SIZE(shadow_read_write_fields);
static const unsigned short vmcs_field_to_offset_table[] = {
FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
FIELD(POSTED_INTR_NV, posted_intr_nv),
FIELD(GUEST_ES_SELECTOR, guest_es_selector),
FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
FIELD(GUEST_INTR_STATUS, guest_intr_status),
FIELD(HOST_ES_SELECTOR, host_es_selector),
FIELD(HOST_CS_SELECTOR, host_cs_selector),
FIELD(HOST_SS_SELECTOR, host_ss_selector),
FIELD(HOST_DS_SELECTOR, host_ds_selector),
FIELD(HOST_FS_SELECTOR, host_fs_selector),
FIELD(HOST_GS_SELECTOR, host_gs_selector),
FIELD(HOST_TR_SELECTOR, host_tr_selector),
FIELD64(IO_BITMAP_A, io_bitmap_a),
FIELD64(IO_BITMAP_B, io_bitmap_b),
FIELD64(MSR_BITMAP, msr_bitmap),
FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
FIELD64(TSC_OFFSET, tsc_offset),
FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
FIELD64(EPT_POINTER, ept_pointer),
FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
FIELD64(GUEST_PDPTR0, guest_pdptr0),
FIELD64(GUEST_PDPTR1, guest_pdptr1),
FIELD64(GUEST_PDPTR2, guest_pdptr2),
FIELD64(GUEST_PDPTR3, guest_pdptr3),
FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
FIELD64(HOST_IA32_PAT, host_ia32_pat),
FIELD64(HOST_IA32_EFER, host_ia32_efer),
FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
FIELD(EXCEPTION_BITMAP, exception_bitmap),
FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
FIELD(CR3_TARGET_COUNT, cr3_target_count),
FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
FIELD(TPR_THRESHOLD, tpr_threshold),
FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
FIELD(VM_EXIT_REASON, vm_exit_reason),
FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
FIELD(GUEST_ES_LIMIT, guest_es_limit),
FIELD(GUEST_CS_LIMIT, guest_cs_limit),
FIELD(GUEST_SS_LIMIT, guest_ss_limit),
FIELD(GUEST_DS_LIMIT, guest_ds_limit),
FIELD(GUEST_FS_LIMIT, guest_fs_limit),
FIELD(GUEST_GS_LIMIT, guest_gs_limit),
FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
FIELD(GUEST_TR_LIMIT, guest_tr_limit),
FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
FIELD(CR0_READ_SHADOW, cr0_read_shadow),
FIELD(CR4_READ_SHADOW, cr4_read_shadow),
FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
FIELD(EXIT_QUALIFICATION, exit_qualification),
FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
FIELD(GUEST_CR0, guest_cr0),
FIELD(GUEST_CR3, guest_cr3),
FIELD(GUEST_CR4, guest_cr4),
FIELD(GUEST_ES_BASE, guest_es_base),
FIELD(GUEST_CS_BASE, guest_cs_base),
FIELD(GUEST_SS_BASE, guest_ss_base),
FIELD(GUEST_DS_BASE, guest_ds_base),
FIELD(GUEST_FS_BASE, guest_fs_base),
FIELD(GUEST_GS_BASE, guest_gs_base),
FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
FIELD(GUEST_TR_BASE, guest_tr_base),
FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
FIELD(GUEST_IDTR_BASE, guest_idtr_base),
FIELD(GUEST_DR7, guest_dr7),
FIELD(GUEST_RSP, guest_rsp),
FIELD(GUEST_RIP, guest_rip),
FIELD(GUEST_RFLAGS, guest_rflags),
FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
FIELD(HOST_CR0, host_cr0),
FIELD(HOST_CR3, host_cr3),
FIELD(HOST_CR4, host_cr4),
FIELD(HOST_FS_BASE, host_fs_base),
FIELD(HOST_GS_BASE, host_gs_base),
FIELD(HOST_TR_BASE, host_tr_base),
FIELD(HOST_GDTR_BASE, host_gdtr_base),
FIELD(HOST_IDTR_BASE, host_idtr_base),
FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
FIELD(HOST_RSP, host_rsp),
FIELD(HOST_RIP, host_rip),
};
static inline short vmcs_field_to_offset(unsigned long field)
{
BUILD_BUG_ON(ARRAY_SIZE(vmcs_field_to_offset_table) > SHRT_MAX);
if (field >= ARRAY_SIZE(vmcs_field_to_offset_table) ||
vmcs_field_to_offset_table[field] == 0)
return -ENOENT;
return vmcs_field_to_offset_table[field];
}
static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
{
return to_vmx(vcpu)->nested.cached_vmcs12;
}
static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
{
struct page *page = kvm_vcpu_gfn_to_page(vcpu, addr >> PAGE_SHIFT);
if (is_error_page(page))
return NULL;
return page;
}
static void nested_release_page(struct page *page)
{
kvm_release_page_dirty(page);
}
static void nested_release_page_clean(struct page *page)
{
kvm_release_page_clean(page);
}
static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
static u64 construct_eptp(unsigned long root_hpa);
static void kvm_cpu_vmxon(u64 addr);
static void kvm_cpu_vmxoff(void);
static bool vmx_xsaves_supported(void);
static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
static void vmx_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg);
static void vmx_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg);
static bool guest_state_valid(struct kvm_vcpu *vcpu);
static u32 vmx_segment_access_rights(struct kvm_segment *var);
static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
static int alloc_identity_pagetable(struct kvm *kvm);
static DEFINE_PER_CPU(struct vmcs *, vmxarea);
static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
/*
* We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
* when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
*/
static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
/*
* We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
* can find which vCPU should be waken up.
*/
static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
enum {
VMX_IO_BITMAP_A,
VMX_IO_BITMAP_B,
VMX_MSR_BITMAP_LEGACY,
VMX_MSR_BITMAP_LONGMODE,
VMX_MSR_BITMAP_LEGACY_X2APIC_APICV,
VMX_MSR_BITMAP_LONGMODE_X2APIC_APICV,
VMX_MSR_BITMAP_LEGACY_X2APIC,
VMX_MSR_BITMAP_LONGMODE_X2APIC,
VMX_VMREAD_BITMAP,
VMX_VMWRITE_BITMAP,
VMX_BITMAP_NR
};
static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
#define vmx_io_bitmap_a (vmx_bitmap[VMX_IO_BITMAP_A])
#define vmx_io_bitmap_b (vmx_bitmap[VMX_IO_BITMAP_B])
#define vmx_msr_bitmap_legacy (vmx_bitmap[VMX_MSR_BITMAP_LEGACY])
#define vmx_msr_bitmap_longmode (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE])
#define vmx_msr_bitmap_legacy_x2apic_apicv (vmx_bitmap[VMX_MSR_BITMAP_LEGACY_X2APIC_APICV])
#define vmx_msr_bitmap_longmode_x2apic_apicv (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE_X2APIC_APICV])
#define vmx_msr_bitmap_legacy_x2apic (vmx_bitmap[VMX_MSR_BITMAP_LEGACY_X2APIC])
#define vmx_msr_bitmap_longmode_x2apic (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE_X2APIC])
#define vmx_vmread_bitmap (vmx_bitmap[VMX_VMREAD_BITMAP])
#define vmx_vmwrite_bitmap (vmx_bitmap[VMX_VMWRITE_BITMAP])
static bool cpu_has_load_ia32_efer;
static bool cpu_has_load_perf_global_ctrl;
static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
static DEFINE_SPINLOCK(vmx_vpid_lock);
static struct vmcs_config {
int size;
int order;
u32 basic_cap;
u32 revision_id;
u32 pin_based_exec_ctrl;
u32 cpu_based_exec_ctrl;
u32 cpu_based_2nd_exec_ctrl;
u32 vmexit_ctrl;
u32 vmentry_ctrl;
} vmcs_config;
static struct vmx_capability {
u32 ept;
u32 vpid;
} vmx_capability;
#define VMX_SEGMENT_FIELD(seg) \
[VCPU_SREG_##seg] = { \
.selector = GUEST_##seg##_SELECTOR, \
.base = GUEST_##seg##_BASE, \
.limit = GUEST_##seg##_LIMIT, \
.ar_bytes = GUEST_##seg##_AR_BYTES, \
}
static const struct kvm_vmx_segment_field {
unsigned selector;
unsigned base;
unsigned limit;
unsigned ar_bytes;
} kvm_vmx_segment_fields[] = {
VMX_SEGMENT_FIELD(CS),
VMX_SEGMENT_FIELD(DS),
VMX_SEGMENT_FIELD(ES),
VMX_SEGMENT_FIELD(FS),
VMX_SEGMENT_FIELD(GS),
VMX_SEGMENT_FIELD(SS),
VMX_SEGMENT_FIELD(TR),
VMX_SEGMENT_FIELD(LDTR),
};
static u64 host_efer;
static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
/*
* Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
* away by decrementing the array size.
*/
static const u32 vmx_msr_index[] = {
#ifdef CONFIG_X86_64
MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
#endif
MSR_EFER, MSR_TSC_AUX, MSR_STAR,
};
static inline bool is_exception_n(u32 intr_info, u8 vector)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
INTR_INFO_VALID_MASK)) ==
(INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
}
static inline bool is_debug(u32 intr_info)
{
return is_exception_n(intr_info, DB_VECTOR);
}
static inline bool is_breakpoint(u32 intr_info)
{
return is_exception_n(intr_info, BP_VECTOR);
}
static inline bool is_page_fault(u32 intr_info)
{
return is_exception_n(intr_info, PF_VECTOR);
}
static inline bool is_no_device(u32 intr_info)
{
return is_exception_n(intr_info, NM_VECTOR);
}
static inline bool is_invalid_opcode(u32 intr_info)
{
return is_exception_n(intr_info, UD_VECTOR);
}
static inline bool is_external_interrupt(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
== (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
}
static inline bool is_machine_check(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
INTR_INFO_VALID_MASK)) ==
(INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
}
static inline bool cpu_has_vmx_msr_bitmap(void)
{
return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
}
static inline bool cpu_has_vmx_tpr_shadow(void)
{
return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
}
static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
{
return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
}
static inline bool cpu_has_secondary_exec_ctrls(void)
{
return vmcs_config.cpu_based_exec_ctrl &
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
}
static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
}
static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
}
static inline bool cpu_has_vmx_apic_register_virt(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_APIC_REGISTER_VIRT;
}
static inline bool cpu_has_vmx_virtual_intr_delivery(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
}
/*
* Comment's format: document - errata name - stepping - processor name.
* Refer from
* https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
*/
static u32 vmx_preemption_cpu_tfms[] = {
/* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
0x000206E6,
/* 323056.pdf - AAX65 - C2 - Xeon L3406 */
/* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
/* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
0x00020652,
/* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
0x00020655,
/* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
/* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
/*
* 320767.pdf - AAP86 - B1 -
* i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
*/
0x000106E5,
/* 321333.pdf - AAM126 - C0 - Xeon 3500 */
0x000106A0,
/* 321333.pdf - AAM126 - C1 - Xeon 3500 */
0x000106A1,
/* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
0x000106A4,
/* 321333.pdf - AAM126 - D0 - Xeon 3500 */
/* 321324.pdf - AAK139 - D0 - Xeon 5500 */
/* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
0x000106A5,
};
static inline bool cpu_has_broken_vmx_preemption_timer(void)
{
u32 eax = cpuid_eax(0x00000001), i;
/* Clear the reserved bits */
eax &= ~(0x3U << 14 | 0xfU << 28);
for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
if (eax == vmx_preemption_cpu_tfms[i])
return true;
return false;
}
static inline bool cpu_has_vmx_preemption_timer(void)
{
return vmcs_config.pin_based_exec_ctrl &
PIN_BASED_VMX_PREEMPTION_TIMER;
}
static inline bool cpu_has_vmx_posted_intr(void)
{
return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
}
static inline bool cpu_has_vmx_apicv(void)
{
return cpu_has_vmx_apic_register_virt() &&
cpu_has_vmx_virtual_intr_delivery() &&
cpu_has_vmx_posted_intr();
}
static inline bool cpu_has_vmx_flexpriority(void)
{
return cpu_has_vmx_tpr_shadow() &&
cpu_has_vmx_virtualize_apic_accesses();
}
static inline bool cpu_has_vmx_ept_execute_only(void)
{
return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
}
static inline bool cpu_has_vmx_ept_2m_page(void)
{
return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
}
static inline bool cpu_has_vmx_ept_1g_page(void)
{
return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
}
static inline bool cpu_has_vmx_ept_4levels(void)
{
return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
}
static inline bool cpu_has_vmx_ept_ad_bits(void)
{
return vmx_capability.ept & VMX_EPT_AD_BIT;
}
static inline bool cpu_has_vmx_invept_context(void)
{
return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
}
static inline bool cpu_has_vmx_invept_global(void)
{
return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
}
static inline bool cpu_has_vmx_invvpid_single(void)
{
return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
}
static inline bool cpu_has_vmx_invvpid_global(void)
{
return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
}
static inline bool cpu_has_vmx_ept(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_ENABLE_EPT;
}
static inline bool cpu_has_vmx_unrestricted_guest(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_UNRESTRICTED_GUEST;
}
static inline bool cpu_has_vmx_ple(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_PAUSE_LOOP_EXITING;
}
static inline bool cpu_has_vmx_basic_inout(void)
{
return (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
}
static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
{
return flexpriority_enabled && lapic_in_kernel(vcpu);
}
static inline bool cpu_has_vmx_vpid(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_ENABLE_VPID;
}
static inline bool cpu_has_vmx_rdtscp(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_RDTSCP;
}
static inline bool cpu_has_vmx_invpcid(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_ENABLE_INVPCID;
}
static inline bool cpu_has_virtual_nmis(void)
{
return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
}
static inline bool cpu_has_vmx_wbinvd_exit(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_WBINVD_EXITING;
}
static inline bool cpu_has_vmx_shadow_vmcs(void)
{
u64 vmx_msr;
rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
/* check if the cpu supports writing r/o exit information fields */
if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
return false;
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_SHADOW_VMCS;
}
static inline bool cpu_has_vmx_pml(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
}
static inline bool cpu_has_vmx_tsc_scaling(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_TSC_SCALING;
}
static inline bool report_flexpriority(void)
{
return flexpriority_enabled;
}
static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
{
return vmcs12->cpu_based_vm_exec_control & bit;
}
static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
{
return (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
(vmcs12->secondary_vm_exec_control & bit);
}
static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
{
return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
}
static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
{
return vmcs12->pin_based_vm_exec_control &
PIN_BASED_VMX_PREEMPTION_TIMER;
}
static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
}
static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES) &&
vmx_xsaves_supported();
}
static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
}
static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
}
static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
}
static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
}
static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
{
return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
}
static inline bool is_exception(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
== (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
}
static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
u32 exit_intr_info,
unsigned long exit_qualification);
static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12,
u32 reason, unsigned long qualification);
static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
{
int i;
for (i = 0; i < vmx->nmsrs; ++i)
if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
return i;
return -1;
}
static inline void __invvpid(int ext, u16 vpid, gva_t gva)
{
struct {
u64 vpid : 16;
u64 rsvd : 48;
u64 gva;
} operand = { vpid, 0, gva };
asm volatile (__ex(ASM_VMX_INVVPID)
/* CF==1 or ZF==1 --> rc = -1 */
"; ja 1f ; ud2 ; 1:"
: : "a"(&operand), "c"(ext) : "cc", "memory");
}
static inline void __invept(int ext, u64 eptp, gpa_t gpa)
{
struct {
u64 eptp, gpa;
} operand = {eptp, gpa};
asm volatile (__ex(ASM_VMX_INVEPT)
/* CF==1 or ZF==1 --> rc = -1 */
"; ja 1f ; ud2 ; 1:\n"
: : "a" (&operand), "c" (ext) : "cc", "memory");
}
static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
{
int i;
i = __find_msr_index(vmx, msr);
if (i >= 0)
return &vmx->guest_msrs[i];
return NULL;
}
static void vmcs_clear(struct vmcs *vmcs)
{
u64 phys_addr = __pa(vmcs);
u8 error;
asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
: "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
: "cc", "memory");
if (error)
printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
vmcs, phys_addr);
}
static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
{
vmcs_clear(loaded_vmcs->vmcs);
if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
vmcs_clear(loaded_vmcs->shadow_vmcs);
loaded_vmcs->cpu = -1;
loaded_vmcs->launched = 0;
}
static void vmcs_load(struct vmcs *vmcs)
{
u64 phys_addr = __pa(vmcs);
u8 error;
asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
: "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
: "cc", "memory");
if (error)
printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
vmcs, phys_addr);
}
#ifdef CONFIG_KEXEC_CORE
/*
* This bitmap is used to indicate whether the vmclear
* operation is enabled on all cpus. All disabled by
* default.
*/
static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
static inline void crash_enable_local_vmclear(int cpu)
{
cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
}
static inline void crash_disable_local_vmclear(int cpu)
{
cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
}
static inline int crash_local_vmclear_enabled(int cpu)
{
return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
}
static void crash_vmclear_local_loaded_vmcss(void)
{
int cpu = raw_smp_processor_id();
struct loaded_vmcs *v;
if (!crash_local_vmclear_enabled(cpu))
return;
list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
loaded_vmcss_on_cpu_link)
vmcs_clear(v->vmcs);
}
#else
static inline void crash_enable_local_vmclear(int cpu) { }
static inline void crash_disable_local_vmclear(int cpu) { }
#endif /* CONFIG_KEXEC_CORE */
static void __loaded_vmcs_clear(void *arg)
{
struct loaded_vmcs *loaded_vmcs = arg;
int cpu = raw_smp_processor_id();
if (loaded_vmcs->cpu != cpu)
return; /* vcpu migration can race with cpu offline */
if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
per_cpu(current_vmcs, cpu) = NULL;
crash_disable_local_vmclear(cpu);
list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
/*
* we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
* is before setting loaded_vmcs->vcpu to -1 which is done in
* loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
* then adds the vmcs into percpu list before it is deleted.
*/
smp_wmb();
loaded_vmcs_init(loaded_vmcs);
crash_enable_local_vmclear(cpu);
}
static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
{
int cpu = loaded_vmcs->cpu;
if (cpu != -1)
smp_call_function_single(cpu,
__loaded_vmcs_clear, loaded_vmcs, 1);
}
static inline void vpid_sync_vcpu_single(int vpid)
{
if (vpid == 0)
return;
if (cpu_has_vmx_invvpid_single())
__invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
}
static inline void vpid_sync_vcpu_global(void)
{
if (cpu_has_vmx_invvpid_global())
__invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
}
static inline void vpid_sync_context(int vpid)
{
if (cpu_has_vmx_invvpid_single())
vpid_sync_vcpu_single(vpid);
else
vpid_sync_vcpu_global();
}
static inline void ept_sync_global(void)
{
if (cpu_has_vmx_invept_global())
__invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
}
static inline void ept_sync_context(u64 eptp)
{
if (enable_ept) {
if (cpu_has_vmx_invept_context())
__invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
else
ept_sync_global();
}
}
static __always_inline void vmcs_check16(unsigned long field)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
"16-bit accessor invalid for 64-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
"16-bit accessor invalid for 64-bit high field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
"16-bit accessor invalid for 32-bit high field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
"16-bit accessor invalid for natural width field");
}
static __always_inline void vmcs_check32(unsigned long field)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
"32-bit accessor invalid for 16-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
"32-bit accessor invalid for natural width field");
}
static __always_inline void vmcs_check64(unsigned long field)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
"64-bit accessor invalid for 16-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
"64-bit accessor invalid for 64-bit high field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
"64-bit accessor invalid for 32-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
"64-bit accessor invalid for natural width field");
}
static __always_inline void vmcs_checkl(unsigned long field)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
"Natural width accessor invalid for 16-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
"Natural width accessor invalid for 64-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
"Natural width accessor invalid for 64-bit high field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
"Natural width accessor invalid for 32-bit field");
}
static __always_inline unsigned long __vmcs_readl(unsigned long field)
{
unsigned long value;
asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
: "=a"(value) : "d"(field) : "cc");
return value;
}
static __always_inline u16 vmcs_read16(unsigned long field)
{
vmcs_check16(field);
return __vmcs_readl(field);
}
static __always_inline u32 vmcs_read32(unsigned long field)
{
vmcs_check32(field);
return __vmcs_readl(field);
}
static __always_inline u64 vmcs_read64(unsigned long field)
{
vmcs_check64(field);
#ifdef CONFIG_X86_64
return __vmcs_readl(field);
#else
return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
#endif
}
static __always_inline unsigned long vmcs_readl(unsigned long field)
{
vmcs_checkl(field);
return __vmcs_readl(field);
}
static noinline void vmwrite_error(unsigned long field, unsigned long value)
{
printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
dump_stack();
}
static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
{
u8 error;
asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
: "=q"(error) : "a"(value), "d"(field) : "cc");
if (unlikely(error))
vmwrite_error(field, value);
}
static __always_inline void vmcs_write16(unsigned long field, u16 value)
{
vmcs_check16(field);
__vmcs_writel(field, value);
}
static __always_inline void vmcs_write32(unsigned long field, u32 value)
{
vmcs_check32(field);
__vmcs_writel(field, value);
}
static __always_inline void vmcs_write64(unsigned long field, u64 value)
{
vmcs_check64(field);
__vmcs_writel(field, value);
#ifndef CONFIG_X86_64
asm volatile ("");
__vmcs_writel(field+1, value >> 32);
#endif
}
static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
{
vmcs_checkl(field);
__vmcs_writel(field, value);
}
static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
"vmcs_clear_bits does not support 64-bit fields");
__vmcs_writel(field, __vmcs_readl(field) & ~mask);
}
static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
"vmcs_set_bits does not support 64-bit fields");
__vmcs_writel(field, __vmcs_readl(field) | mask);
}
static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
{
vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
}
static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
{
vmcs_write32(VM_ENTRY_CONTROLS, val);
vmx->vm_entry_controls_shadow = val;
}
static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
{
if (vmx->vm_entry_controls_shadow != val)
vm_entry_controls_init(vmx, val);
}
static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
{
return vmx->vm_entry_controls_shadow;
}
static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
{
vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
}
static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
{
vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
}
static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
{
vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
}
static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
{
vmcs_write32(VM_EXIT_CONTROLS, val);
vmx->vm_exit_controls_shadow = val;
}
static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
{
if (vmx->vm_exit_controls_shadow != val)
vm_exit_controls_init(vmx, val);
}
static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
{
return vmx->vm_exit_controls_shadow;
}
static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
{
vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
}
static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
{
vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
}
static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
{
vmx->segment_cache.bitmask = 0;
}
static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
unsigned field)
{
bool ret;
u32 mask = 1 << (seg * SEG_FIELD_NR + field);
if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
vmx->segment_cache.bitmask = 0;
}
ret = vmx->segment_cache.bitmask & mask;
vmx->segment_cache.bitmask |= mask;
return ret;
}
static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
{
u16 *p = &vmx->segment_cache.seg[seg].selector;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
*p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
return *p;
}
static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
{
ulong *p = &vmx->segment_cache.seg[seg].base;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
*p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
return *p;
}
static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
{
u32 *p = &vmx->segment_cache.seg[seg].limit;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
*p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
return *p;
}
static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
{
u32 *p = &vmx->segment_cache.seg[seg].ar;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
*p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
return *p;
}
static void update_exception_bitmap(struct kvm_vcpu *vcpu)
{
u32 eb;
eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
(1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR);
if ((vcpu->guest_debug &
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
eb |= 1u << BP_VECTOR;
if (to_vmx(vcpu)->rmode.vm86_active)
eb = ~0;
if (enable_ept)
eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
if (vcpu->fpu_active)
eb &= ~(1u << NM_VECTOR);
/* When we are running a nested L2 guest and L1 specified for it a
* certain exception bitmap, we must trap the same exceptions and pass
* them to L1. When running L2, we will only handle the exceptions
* specified above if L1 did not want them.
*/
if (is_guest_mode(vcpu))
eb |= get_vmcs12(vcpu)->exception_bitmap;
vmcs_write32(EXCEPTION_BITMAP, eb);
}
static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
unsigned long entry, unsigned long exit)
{
vm_entry_controls_clearbit(vmx, entry);
vm_exit_controls_clearbit(vmx, exit);
}
static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
{
unsigned i;
struct msr_autoload *m = &vmx->msr_autoload;
switch (msr) {
case MSR_EFER:
if (cpu_has_load_ia32_efer) {
clear_atomic_switch_msr_special(vmx,
VM_ENTRY_LOAD_IA32_EFER,
VM_EXIT_LOAD_IA32_EFER);
return;
}
break;
case MSR_CORE_PERF_GLOBAL_CTRL:
if (cpu_has_load_perf_global_ctrl) {
clear_atomic_switch_msr_special(vmx,
VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
return;
}
break;
}
for (i = 0; i < m->nr; ++i)
if (m->guest[i].index == msr)
break;
if (i == m->nr)
return;
--m->nr;
m->guest[i] = m->guest[m->nr];
m->host[i] = m->host[m->nr];
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
}
static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
unsigned long entry, unsigned long exit,
unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
u64 guest_val, u64 host_val)
{
vmcs_write64(guest_val_vmcs, guest_val);
vmcs_write64(host_val_vmcs, host_val);
vm_entry_controls_setbit(vmx, entry);
vm_exit_controls_setbit(vmx, exit);
}
static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
u64 guest_val, u64 host_val)
{
unsigned i;
struct msr_autoload *m = &vmx->msr_autoload;
switch (msr) {
case MSR_EFER:
if (cpu_has_load_ia32_efer) {
add_atomic_switch_msr_special(vmx,
VM_ENTRY_LOAD_IA32_EFER,
VM_EXIT_LOAD_IA32_EFER,
GUEST_IA32_EFER,
HOST_IA32_EFER,
guest_val, host_val);
return;
}
break;
case MSR_CORE_PERF_GLOBAL_CTRL:
if (cpu_has_load_perf_global_ctrl) {
add_atomic_switch_msr_special(vmx,
VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
GUEST_IA32_PERF_GLOBAL_CTRL,
HOST_IA32_PERF_GLOBAL_CTRL,
guest_val, host_val);
return;
}
break;
case MSR_IA32_PEBS_ENABLE:
/* PEBS needs a quiescent period after being disabled (to write
* a record). Disabling PEBS through VMX MSR swapping doesn't
* provide that period, so a CPU could write host's record into
* guest's memory.
*/
wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
}
for (i = 0; i < m->nr; ++i)
if (m->guest[i].index == msr)
break;
if (i == NR_AUTOLOAD_MSRS) {
printk_once(KERN_WARNING "Not enough msr switch entries. "
"Can't add msr %x\n", msr);
return;
} else if (i == m->nr) {
++m->nr;
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
}
m->guest[i].index = msr;
m->guest[i].value = guest_val;
m->host[i].index = msr;
m->host[i].value = host_val;
}
static void reload_tss(void)
{
/*
* VT restores TR but not its size. Useless.
*/
struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
struct desc_struct *descs;
descs = (void *)gdt->address;
descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
load_TR_desc();
}
static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
{
u64 guest_efer = vmx->vcpu.arch.efer;
u64 ignore_bits = 0;
if (!enable_ept) {
/*
* NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
* host CPUID is more efficient than testing guest CPUID
* or CR4. Host SMEP is anyway a requirement for guest SMEP.
*/
if (boot_cpu_has(X86_FEATURE_SMEP))
guest_efer |= EFER_NX;
else if (!(guest_efer & EFER_NX))
ignore_bits |= EFER_NX;
}
/*
* LMA and LME handled by hardware; SCE meaningless outside long mode.
*/
ignore_bits |= EFER_SCE;
#ifdef CONFIG_X86_64
ignore_bits |= EFER_LMA | EFER_LME;
/* SCE is meaningful only in long mode on Intel */
if (guest_efer & EFER_LMA)
ignore_bits &= ~(u64)EFER_SCE;
#endif
clear_atomic_switch_msr(vmx, MSR_EFER);
/*
* On EPT, we can't emulate NX, so we must switch EFER atomically.
* On CPUs that support "load IA32_EFER", always switch EFER
* atomically, since it's faster than switching it manually.
*/
if (cpu_has_load_ia32_efer ||
(enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
if (!(guest_efer & EFER_LMA))
guest_efer &= ~EFER_LME;
if (guest_efer != host_efer)
add_atomic_switch_msr(vmx, MSR_EFER,
guest_efer, host_efer);
return false;
} else {
guest_efer &= ~ignore_bits;
guest_efer |= host_efer & ignore_bits;
vmx->guest_msrs[efer_offset].data = guest_efer;
vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
return true;
}
}
static unsigned long segment_base(u16 selector)
{
struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
struct desc_struct *d;
unsigned long table_base;
unsigned long v;
if (!(selector & ~3))
return 0;
table_base = gdt->address;
if (selector & 4) { /* from ldt */
u16 ldt_selector = kvm_read_ldt();
if (!(ldt_selector & ~3))
return 0;
table_base = segment_base(ldt_selector);
}
d = (struct desc_struct *)(table_base + (selector & ~7));
v = get_desc_base(d);
#ifdef CONFIG_X86_64
if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
#endif
return v;
}
static inline unsigned long kvm_read_tr_base(void)
{
u16 tr;
asm("str %0" : "=g"(tr));
return segment_base(tr);
}
static void vmx_save_host_state(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int i;
if (vmx->host_state.loaded)
return;
vmx->host_state.loaded = 1;
/*
* Set host fs and gs selectors. Unfortunately, 22.2.3 does not
* allow segment selectors with cpl > 0 or ti == 1.
*/
vmx->host_state.ldt_sel = kvm_read_ldt();
vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
savesegment(fs, vmx->host_state.fs_sel);
if (!(vmx->host_state.fs_sel & 7)) {
vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
vmx->host_state.fs_reload_needed = 0;
} else {
vmcs_write16(HOST_FS_SELECTOR, 0);
vmx->host_state.fs_reload_needed = 1;
}
savesegment(gs, vmx->host_state.gs_sel);
if (!(vmx->host_state.gs_sel & 7))
vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
else {
vmcs_write16(HOST_GS_SELECTOR, 0);
vmx->host_state.gs_ldt_reload_needed = 1;
}
#ifdef CONFIG_X86_64
savesegment(ds, vmx->host_state.ds_sel);
savesegment(es, vmx->host_state.es_sel);
#endif
#ifdef CONFIG_X86_64
vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
#else
vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
#endif
#ifdef CONFIG_X86_64
rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
if (is_long_mode(&vmx->vcpu))
wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
#endif
if (boot_cpu_has(X86_FEATURE_MPX))
rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
for (i = 0; i < vmx->save_nmsrs; ++i)
kvm_set_shared_msr(vmx->guest_msrs[i].index,
vmx->guest_msrs[i].data,
vmx->guest_msrs[i].mask);
}
static void __vmx_load_host_state(struct vcpu_vmx *vmx)
{
if (!vmx->host_state.loaded)
return;
++vmx->vcpu.stat.host_state_reload;
vmx->host_state.loaded = 0;
#ifdef CONFIG_X86_64
if (is_long_mode(&vmx->vcpu))
rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
#endif
if (vmx->host_state.gs_ldt_reload_needed) {
kvm_load_ldt(vmx->host_state.ldt_sel);
#ifdef CONFIG_X86_64
load_gs_index(vmx->host_state.gs_sel);
#else
loadsegment(gs, vmx->host_state.gs_sel);
#endif
}
if (vmx->host_state.fs_reload_needed)
loadsegment(fs, vmx->host_state.fs_sel);
#ifdef CONFIG_X86_64
if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
loadsegment(ds, vmx->host_state.ds_sel);
loadsegment(es, vmx->host_state.es_sel);
}
#endif
reload_tss();
#ifdef CONFIG_X86_64
wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
#endif
if (vmx->host_state.msr_host_bndcfgs)
wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
load_gdt(this_cpu_ptr(&host_gdt));
}
static void vmx_load_host_state(struct vcpu_vmx *vmx)
{
preempt_disable();
__vmx_load_host_state(vmx);
preempt_enable();
}
static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
{
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
struct pi_desc old, new;
unsigned int dest;
if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(vcpu))
return;
do {
old.control = new.control = pi_desc->control;
/*
* If 'nv' field is POSTED_INTR_WAKEUP_VECTOR, there
* are two possible cases:
* 1. After running 'pre_block', context switch
* happened. For this case, 'sn' was set in
* vmx_vcpu_put(), so we need to clear it here.
* 2. After running 'pre_block', we were blocked,
* and woken up by some other guy. For this case,
* we don't need to do anything, 'pi_post_block'
* will do everything for us. However, we cannot
* check whether it is case #1 or case #2 here
* (maybe, not needed), so we also clear sn here,
* I think it is not a big deal.
*/
if (pi_desc->nv != POSTED_INTR_WAKEUP_VECTOR) {
if (vcpu->cpu != cpu) {
dest = cpu_physical_id(cpu);
if (x2apic_enabled())
new.ndst = dest;
else
new.ndst = (dest << 8) & 0xFF00;
}
/* set 'NV' to 'notification vector' */
new.nv = POSTED_INTR_VECTOR;
}
/* Allow posting non-urgent interrupts */
new.sn = 0;
} while (cmpxchg(&pi_desc->control, old.control,
new.control) != old.control);
}
static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
{
vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
}
/*
* Switches to specified vcpu, until a matching vcpu_put(), but assumes
* vcpu mutex is already taken.
*/
static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
if (!vmm_exclusive)
kvm_cpu_vmxon(phys_addr);
else if (!already_loaded)
loaded_vmcs_clear(vmx->loaded_vmcs);
if (!already_loaded) {
local_irq_disable();
crash_disable_local_vmclear(cpu);
/*
* Read loaded_vmcs->cpu should be before fetching
* loaded_vmcs->loaded_vmcss_on_cpu_link.
* See the comments in __loaded_vmcs_clear().
*/
smp_rmb();
list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
&per_cpu(loaded_vmcss_on_cpu, cpu));
crash_enable_local_vmclear(cpu);
local_irq_enable();
}
if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
vmcs_load(vmx->loaded_vmcs->vmcs);
}
if (!already_loaded) {
struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
unsigned long sysenter_esp;
kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
/*
* Linux uses per-cpu TSS and GDT, so set these when switching
* processors.
*/
vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
vmcs_writel(HOST_GDTR_BASE, gdt->address); /* 22.2.4 */
rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
vmx->loaded_vmcs->cpu = cpu;
}
/* Setup TSC multiplier */
if (kvm_has_tsc_control &&
vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
decache_tsc_multiplier(vmx);
vmx_vcpu_pi_load(vcpu, cpu);
vmx->host_pkru = read_pkru();
}
static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
{
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(vcpu))
return;
/* Set SN when the vCPU is preempted */
if (vcpu->preempted)
pi_set_sn(pi_desc);
}
static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
{
vmx_vcpu_pi_put(vcpu);
__vmx_load_host_state(to_vmx(vcpu));
if (!vmm_exclusive) {
__loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
vcpu->cpu = -1;
kvm_cpu_vmxoff();
}
}
static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
{
ulong cr0;
if (vcpu->fpu_active)
return;
vcpu->fpu_active = 1;
cr0 = vmcs_readl(GUEST_CR0);
cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
vmcs_writel(GUEST_CR0, cr0);
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
if (is_guest_mode(vcpu))
vcpu->arch.cr0_guest_owned_bits &=
~get_vmcs12(vcpu)->cr0_guest_host_mask;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
}
static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
/*
* Return the cr0 value that a nested guest would read. This is a combination
* of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
* its hypervisor (cr0_read_shadow).
*/
static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
{
return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
(fields->cr0_read_shadow & fields->cr0_guest_host_mask);
}
static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
{
return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
(fields->cr4_read_shadow & fields->cr4_guest_host_mask);
}
static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
{
/* Note that there is no vcpu->fpu_active = 0 here. The caller must
* set this *before* calling this function.
*/
vmx_decache_cr0_guest_bits(vcpu);
vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits = 0;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
if (is_guest_mode(vcpu)) {
/*
* L1's specified read shadow might not contain the TS bit,
* so now that we turned on shadowing of this bit, we need to
* set this bit of the shadow. Like in nested_vmx_run we need
* nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
* up-to-date here because we just decached cr0.TS (and we'll
* only update vmcs12->guest_cr0 on nested exit).
*/
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
(vcpu->arch.cr0 & X86_CR0_TS);
vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
} else
vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
}
static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
{
unsigned long rflags, save_rflags;
if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
rflags = vmcs_readl(GUEST_RFLAGS);
if (to_vmx(vcpu)->rmode.vm86_active) {
rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
save_rflags = to_vmx(vcpu)->rmode.save_rflags;
rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
}
to_vmx(vcpu)->rflags = rflags;
}
return to_vmx(vcpu)->rflags;
}
static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
{
__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
to_vmx(vcpu)->rflags = rflags;
if (to_vmx(vcpu)->rmode.vm86_active) {
to_vmx(vcpu)->rmode.save_rflags = rflags;
rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
}
vmcs_writel(GUEST_RFLAGS, rflags);
}
static u32 vmx_get_pkru(struct kvm_vcpu *vcpu)
{
return to_vmx(vcpu)->guest_pkru;
}
static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
{
u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
int ret = 0;
if (interruptibility & GUEST_INTR_STATE_STI)
ret |= KVM_X86_SHADOW_INT_STI;
if (interruptibility & GUEST_INTR_STATE_MOV_SS)
ret |= KVM_X86_SHADOW_INT_MOV_SS;
return ret;
}
static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
{
u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
u32 interruptibility = interruptibility_old;
interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
if (mask & KVM_X86_SHADOW_INT_MOV_SS)
interruptibility |= GUEST_INTR_STATE_MOV_SS;
else if (mask & KVM_X86_SHADOW_INT_STI)
interruptibility |= GUEST_INTR_STATE_STI;
if ((interruptibility != interruptibility_old))
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
}
static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
{
unsigned long rip;
rip = kvm_rip_read(vcpu);
rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_rip_write(vcpu, rip);
/* skipping an emulated instruction also counts */
vmx_set_interrupt_shadow(vcpu, 0);
}
/*
* KVM wants to inject page-faults which it got to the guest. This function
* checks whether in a nested guest, we need to inject them to L1 or L2.
*/
static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned nr)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
if (!(vmcs12->exception_bitmap & (1u << nr)))
return 0;
nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
vmcs_read32(VM_EXIT_INTR_INFO),
vmcs_readl(EXIT_QUALIFICATION));
return 1;
}
static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
bool has_error_code, u32 error_code,
bool reinject)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 intr_info = nr | INTR_INFO_VALID_MASK;
if (!reinject && is_guest_mode(vcpu) &&
nested_vmx_check_exception(vcpu, nr))
return;
if (has_error_code) {
vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
intr_info |= INTR_INFO_DELIVER_CODE_MASK;
}
if (vmx->rmode.vm86_active) {
int inc_eip = 0;
if (kvm_exception_is_soft(nr))
inc_eip = vcpu->arch.event_exit_inst_len;
if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
if (kvm_exception_is_soft(nr)) {
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmx->vcpu.arch.event_exit_inst_len);
intr_info |= INTR_TYPE_SOFT_EXCEPTION;
} else
intr_info |= INTR_TYPE_HARD_EXCEPTION;
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
}
static bool vmx_rdtscp_supported(void)
{
return cpu_has_vmx_rdtscp();
}
static bool vmx_invpcid_supported(void)
{
return cpu_has_vmx_invpcid() && enable_ept;
}
/*
* Swap MSR entry in host/guest MSR entry array.
*/
static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
{
struct shared_msr_entry tmp;
tmp = vmx->guest_msrs[to];
vmx->guest_msrs[to] = vmx->guest_msrs[from];
vmx->guest_msrs[from] = tmp;
}
static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
{
unsigned long *msr_bitmap;
if (is_guest_mode(vcpu))
msr_bitmap = to_vmx(vcpu)->nested.msr_bitmap;
else if (cpu_has_secondary_exec_ctrls() &&
(vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
if (enable_apicv && kvm_vcpu_apicv_active(vcpu)) {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode_x2apic_apicv;
else
msr_bitmap = vmx_msr_bitmap_legacy_x2apic_apicv;
} else {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
else
msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
}
} else {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode;
else
msr_bitmap = vmx_msr_bitmap_legacy;
}
vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
}
/*
* Set up the vmcs to automatically save and restore system
* msrs. Don't touch the 64-bit msrs if the guest is in legacy
* mode, as fiddling with msrs is very expensive.
*/
static void setup_msrs(struct vcpu_vmx *vmx)
{
int save_nmsrs, index;
save_nmsrs = 0;
#ifdef CONFIG_X86_64
if (is_long_mode(&vmx->vcpu)) {
index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
if (index >= 0)
move_msr_up(vmx, index, save_nmsrs++);
index = __find_msr_index(vmx, MSR_LSTAR);
if (index >= 0)
move_msr_up(vmx, index, save_nmsrs++);
index = __find_msr_index(vmx, MSR_CSTAR);
if (index >= 0)
move_msr_up(vmx, index, save_nmsrs++);
index = __find_msr_index(vmx, MSR_TSC_AUX);
if (index >= 0 && guest_cpuid_has_rdtscp(&vmx->vcpu))
move_msr_up(vmx, index, save_nmsrs++);
/*
* MSR_STAR is only needed on long mode guests, and only
* if efer.sce is enabled.
*/
index = __find_msr_index(vmx, MSR_STAR);
if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
move_msr_up(vmx, index, save_nmsrs++);
}
#endif
index = __find_msr_index(vmx, MSR_EFER);
if (index >= 0 && update_transition_efer(vmx, index))
move_msr_up(vmx, index, save_nmsrs++);
vmx->save_nmsrs = save_nmsrs;
if (cpu_has_vmx_msr_bitmap())
vmx_set_msr_bitmap(&vmx->vcpu);
}
/*
* reads and returns guest's timestamp counter "register"
* guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
* -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
*/
static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
{
u64 host_tsc, tsc_offset;
host_tsc = rdtsc();
tsc_offset = vmcs_read64(TSC_OFFSET);
return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
}
/*
* writes 'offset' into guest's timestamp counter offset register
*/
static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
{
if (is_guest_mode(vcpu)) {
/*
* We're here if L1 chose not to trap WRMSR to TSC. According
* to the spec, this should set L1's TSC; The offset that L1
* set for L2 remains unchanged, and still needs to be added
* to the newly set TSC to get L2's TSC.
*/
struct vmcs12 *vmcs12;
/* recalculate vmcs02.TSC_OFFSET: */
vmcs12 = get_vmcs12(vcpu);
vmcs_write64(TSC_OFFSET, offset +
(nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
vmcs12->tsc_offset : 0));
} else {
trace_kvm_write_tsc_offset(vcpu->vcpu_id,
vmcs_read64(TSC_OFFSET), offset);
vmcs_write64(TSC_OFFSET, offset);
}
}
static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
{
struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
}
/*
* nested_vmx_allowed() checks whether a guest should be allowed to use VMX
* instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
* all guests if the "nested" module option is off, and can also be disabled
* for a single guest by disabling its VMX cpuid bit.
*/
static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
{
return nested && guest_cpuid_has_vmx(vcpu);
}
/*
* nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
* returned for the various VMX controls MSRs when nested VMX is enabled.
* The same values should also be used to verify that vmcs12 control fields are
* valid during nested entry from L1 to L2.
* Each of these control msrs has a low and high 32-bit half: A low bit is on
* if the corresponding bit in the (32-bit) control field *must* be on, and a
* bit in the high half is on if the corresponding bit in the control field
* may be on. See also vmx_control_verify().
*/
static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
{
/*
* Note that as a general rule, the high half of the MSRs (bits in
* the control fields which may be 1) should be initialized by the
* intersection of the underlying hardware's MSR (i.e., features which
* can be supported) and the list of features we want to expose -
* because they are known to be properly supported in our code.
* Also, usually, the low half of the MSRs (bits which must be 1) can
* be set to 0, meaning that L1 may turn off any of these bits. The
* reason is that if one of these bits is necessary, it will appear
* in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
* fields of vmcs01 and vmcs02, will turn these bits off - and
* nested_vmx_exit_handled() will not pass related exits to L1.
* These rules have exceptions below.
*/
/* pin-based controls */
rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
vmx->nested.nested_vmx_pinbased_ctls_low,
vmx->nested.nested_vmx_pinbased_ctls_high);
vmx->nested.nested_vmx_pinbased_ctls_low |=
PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
vmx->nested.nested_vmx_pinbased_ctls_high &=
PIN_BASED_EXT_INTR_MASK |
PIN_BASED_NMI_EXITING |
PIN_BASED_VIRTUAL_NMIS;
vmx->nested.nested_vmx_pinbased_ctls_high |=
PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
PIN_BASED_VMX_PREEMPTION_TIMER;
if (kvm_vcpu_apicv_active(&vmx->vcpu))
vmx->nested.nested_vmx_pinbased_ctls_high |=
PIN_BASED_POSTED_INTR;
/* exit controls */
rdmsr(MSR_IA32_VMX_EXIT_CTLS,
vmx->nested.nested_vmx_exit_ctls_low,
vmx->nested.nested_vmx_exit_ctls_high);
vmx->nested.nested_vmx_exit_ctls_low =
VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
vmx->nested.nested_vmx_exit_ctls_high &=
#ifdef CONFIG_X86_64
VM_EXIT_HOST_ADDR_SPACE_SIZE |
#endif
VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
vmx->nested.nested_vmx_exit_ctls_high |=
VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
if (kvm_mpx_supported())
vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
/* We support free control of debug control saving. */
vmx->nested.nested_vmx_exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
/* entry controls */
rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
vmx->nested.nested_vmx_entry_ctls_low,
vmx->nested.nested_vmx_entry_ctls_high);
vmx->nested.nested_vmx_entry_ctls_low =
VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
vmx->nested.nested_vmx_entry_ctls_high &=
#ifdef CONFIG_X86_64
VM_ENTRY_IA32E_MODE |
#endif
VM_ENTRY_LOAD_IA32_PAT;
vmx->nested.nested_vmx_entry_ctls_high |=
(VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
if (kvm_mpx_supported())
vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
/* We support free control of debug control loading. */
vmx->nested.nested_vmx_entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
/* cpu-based controls */
rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
vmx->nested.nested_vmx_procbased_ctls_low,
vmx->nested.nested_vmx_procbased_ctls_high);
vmx->nested.nested_vmx_procbased_ctls_low =
CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
vmx->nested.nested_vmx_procbased_ctls_high &=
CPU_BASED_VIRTUAL_INTR_PENDING |
CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING |
#ifdef CONFIG_X86_64
CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
#endif
CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
/*
* We can allow some features even when not supported by the
* hardware. For example, L1 can specify an MSR bitmap - and we
* can use it to avoid exits to L1 - even when L0 runs L2
* without MSR bitmaps.
*/
vmx->nested.nested_vmx_procbased_ctls_high |=
CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
CPU_BASED_USE_MSR_BITMAPS;
/* We support free control of CR3 access interception. */
vmx->nested.nested_vmx_procbased_ctls_low &=
~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
/* secondary cpu-based controls */
rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
vmx->nested.nested_vmx_secondary_ctls_low,
vmx->nested.nested_vmx_secondary_ctls_high);
vmx->nested.nested_vmx_secondary_ctls_low = 0;
vmx->nested.nested_vmx_secondary_ctls_high &=
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
SECONDARY_EXEC_RDTSCP |
SECONDARY_EXEC_DESC |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_ENABLE_VPID |
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
SECONDARY_EXEC_WBINVD_EXITING |
SECONDARY_EXEC_XSAVES;
if (enable_ept) {
/* nested EPT: emulate EPT also to L1 */
vmx->nested.nested_vmx_secondary_ctls_high |=
SECONDARY_EXEC_ENABLE_EPT;
vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
VMX_EPTP_WB_BIT | VMX_EPT_2MB_PAGE_BIT |
VMX_EPT_INVEPT_BIT;
if (cpu_has_vmx_ept_execute_only())
vmx->nested.nested_vmx_ept_caps |=
VMX_EPT_EXECUTE_ONLY_BIT;
vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
VMX_EPT_EXTENT_CONTEXT_BIT;
} else
vmx->nested.nested_vmx_ept_caps = 0;
/*
* Old versions of KVM use the single-context version without
* checking for support, so declare that it is supported even
* though it is treated as global context. The alternative is
* not failing the single-context invvpid, and it is worse.
*/
if (enable_vpid)
vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
VMX_VPID_EXTENT_SUPPORTED_MASK;
else
vmx->nested.nested_vmx_vpid_caps = 0;
if (enable_unrestricted_guest)
vmx->nested.nested_vmx_secondary_ctls_high |=
SECONDARY_EXEC_UNRESTRICTED_GUEST;
/* miscellaneous data */
rdmsr(MSR_IA32_VMX_MISC,
vmx->nested.nested_vmx_misc_low,
vmx->nested.nested_vmx_misc_high);
vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
vmx->nested.nested_vmx_misc_low |=
VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
VMX_MISC_ACTIVITY_HLT;
vmx->nested.nested_vmx_misc_high = 0;
/*
* This MSR reports some information about VMX support. We
* should return information about the VMX we emulate for the
* guest, and the VMCS structure we give it - not about the
* VMX support of the underlying hardware.
*/
vmx->nested.nested_vmx_basic =
VMCS12_REVISION |
VMX_BASIC_TRUE_CTLS |
((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
(VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
if (cpu_has_vmx_basic_inout())
vmx->nested.nested_vmx_basic |= VMX_BASIC_INOUT;
/*
* These MSRs specify bits which the guest must keep fixed on
* while L1 is in VMXON mode (in L1's root mode, or running an L2).
* We picked the standard core2 setting.
*/
#define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
#define VMXON_CR4_ALWAYSON X86_CR4_VMXE
vmx->nested.nested_vmx_cr0_fixed0 = VMXON_CR0_ALWAYSON;
vmx->nested.nested_vmx_cr4_fixed0 = VMXON_CR4_ALWAYSON;
/* These MSRs specify bits which the guest must keep fixed off. */
rdmsrl(MSR_IA32_VMX_CR0_FIXED1, vmx->nested.nested_vmx_cr0_fixed1);
rdmsrl(MSR_IA32_VMX_CR4_FIXED1, vmx->nested.nested_vmx_cr4_fixed1);
/* highest index: VMX_PREEMPTION_TIMER_VALUE */
vmx->nested.nested_vmx_vmcs_enum = 0x2e;
}
/*
* if fixed0[i] == 1: val[i] must be 1
* if fixed1[i] == 0: val[i] must be 0
*/
static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
{
return ((val & fixed1) | fixed0) == val;
}
static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
{
return fixed_bits_valid(control, low, high);
}
static inline u64 vmx_control_msr(u32 low, u32 high)
{
return low | ((u64)high << 32);
}
static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
{
superset &= mask;
subset &= mask;
return (superset | subset) == superset;
}
static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
{
const u64 feature_and_reserved =
/* feature (except bit 48; see below) */
BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
/* reserved */
BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
u64 vmx_basic = vmx->nested.nested_vmx_basic;
if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
return -EINVAL;
/*
* KVM does not emulate a version of VMX that constrains physical
* addresses of VMX structures (e.g. VMCS) to 32-bits.
*/
if (data & BIT_ULL(48))
return -EINVAL;
if (vmx_basic_vmcs_revision_id(vmx_basic) !=
vmx_basic_vmcs_revision_id(data))
return -EINVAL;
if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
return -EINVAL;
vmx->nested.nested_vmx_basic = data;
return 0;
}
static int
vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
{
u64 supported;
u32 *lowp, *highp;
switch (msr_index) {
case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
lowp = &vmx->nested.nested_vmx_pinbased_ctls_low;
highp = &vmx->nested.nested_vmx_pinbased_ctls_high;
break;
case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
lowp = &vmx->nested.nested_vmx_procbased_ctls_low;
highp = &vmx->nested.nested_vmx_procbased_ctls_high;
break;
case MSR_IA32_VMX_TRUE_EXIT_CTLS:
lowp = &vmx->nested.nested_vmx_exit_ctls_low;
highp = &vmx->nested.nested_vmx_exit_ctls_high;
break;
case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
lowp = &vmx->nested.nested_vmx_entry_ctls_low;
highp = &vmx->nested.nested_vmx_entry_ctls_high;
break;
case MSR_IA32_VMX_PROCBASED_CTLS2:
lowp = &vmx->nested.nested_vmx_secondary_ctls_low;
highp = &vmx->nested.nested_vmx_secondary_ctls_high;
break;
default:
BUG();
}
supported = vmx_control_msr(*lowp, *highp);
/* Check must-be-1 bits are still 1. */
if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
return -EINVAL;
/* Check must-be-0 bits are still 0. */
if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
return -EINVAL;
*lowp = data;
*highp = data >> 32;
return 0;
}
static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
{
const u64 feature_and_reserved_bits =
/* feature */
BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
/* reserved */
GENMASK_ULL(13, 9) | BIT_ULL(31);
u64 vmx_misc;
vmx_misc = vmx_control_msr(vmx->nested.nested_vmx_misc_low,
vmx->nested.nested_vmx_misc_high);
if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
return -EINVAL;
if ((vmx->nested.nested_vmx_pinbased_ctls_high &
PIN_BASED_VMX_PREEMPTION_TIMER) &&
vmx_misc_preemption_timer_rate(data) !=
vmx_misc_preemption_timer_rate(vmx_misc))
return -EINVAL;
if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
return -EINVAL;
if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
return -EINVAL;
if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
return -EINVAL;
vmx->nested.nested_vmx_misc_low = data;
vmx->nested.nested_vmx_misc_high = data >> 32;
return 0;
}
static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
{
u64 vmx_ept_vpid_cap;
vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.nested_vmx_ept_caps,
vmx->nested.nested_vmx_vpid_caps);
/* Every bit is either reserved or a feature bit. */
if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
return -EINVAL;
vmx->nested.nested_vmx_ept_caps = data;
vmx->nested.nested_vmx_vpid_caps = data >> 32;
return 0;
}
static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
{
u64 *msr;
switch (msr_index) {
case MSR_IA32_VMX_CR0_FIXED0:
msr = &vmx->nested.nested_vmx_cr0_fixed0;
break;
case MSR_IA32_VMX_CR4_FIXED0:
msr = &vmx->nested.nested_vmx_cr4_fixed0;
break;
default:
BUG();
}
/*
* 1 bits (which indicates bits which "must-be-1" during VMX operation)
* must be 1 in the restored value.
*/
if (!is_bitwise_subset(data, *msr, -1ULL))
return -EINVAL;
*msr = data;
return 0;
}
/*
* Called when userspace is restoring VMX MSRs.
*
* Returns 0 on success, non-0 otherwise.
*/
static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
switch (msr_index) {
case MSR_IA32_VMX_BASIC:
return vmx_restore_vmx_basic(vmx, data);
case MSR_IA32_VMX_PINBASED_CTLS:
case MSR_IA32_VMX_PROCBASED_CTLS:
case MSR_IA32_VMX_EXIT_CTLS:
case MSR_IA32_VMX_ENTRY_CTLS:
/*
* The "non-true" VMX capability MSRs are generated from the
* "true" MSRs, so we do not support restoring them directly.
*
* If userspace wants to emulate VMX_BASIC[55]=0, userspace
* should restore the "true" MSRs with the must-be-1 bits
* set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
* DEFAULT SETTINGS".
*/
return -EINVAL;
case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
case MSR_IA32_VMX_TRUE_EXIT_CTLS:
case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
case MSR_IA32_VMX_PROCBASED_CTLS2:
return vmx_restore_control_msr(vmx, msr_index, data);
case MSR_IA32_VMX_MISC:
return vmx_restore_vmx_misc(vmx, data);
case MSR_IA32_VMX_CR0_FIXED0:
case MSR_IA32_VMX_CR4_FIXED0:
return vmx_restore_fixed0_msr(vmx, msr_index, data);
case MSR_IA32_VMX_CR0_FIXED1:
case MSR_IA32_VMX_CR4_FIXED1:
/*
* These MSRs are generated based on the vCPU's CPUID, so we
* do not support restoring them directly.
*/
return -EINVAL;
case MSR_IA32_VMX_EPT_VPID_CAP:
return vmx_restore_vmx_ept_vpid_cap(vmx, data);
case MSR_IA32_VMX_VMCS_ENUM:
vmx->nested.nested_vmx_vmcs_enum = data;
return 0;
default:
/*
* The rest of the VMX capability MSRs do not support restore.
*/
return -EINVAL;
}
}
/* Returns 0 on success, non-0 otherwise. */
static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
switch (msr_index) {
case MSR_IA32_VMX_BASIC:
*pdata = vmx->nested.nested_vmx_basic;
break;
case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
case MSR_IA32_VMX_PINBASED_CTLS:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_pinbased_ctls_low,
vmx->nested.nested_vmx_pinbased_ctls_high);
if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
*pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
break;
case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
case MSR_IA32_VMX_PROCBASED_CTLS:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_procbased_ctls_low,
vmx->nested.nested_vmx_procbased_ctls_high);
if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
*pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
break;
case MSR_IA32_VMX_TRUE_EXIT_CTLS:
case MSR_IA32_VMX_EXIT_CTLS:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_exit_ctls_low,
vmx->nested.nested_vmx_exit_ctls_high);
if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
*pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
break;
case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
case MSR_IA32_VMX_ENTRY_CTLS:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_entry_ctls_low,
vmx->nested.nested_vmx_entry_ctls_high);
if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
*pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
break;
case MSR_IA32_VMX_MISC:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_misc_low,
vmx->nested.nested_vmx_misc_high);
break;
case MSR_IA32_VMX_CR0_FIXED0:
*pdata = vmx->nested.nested_vmx_cr0_fixed0;
break;
case MSR_IA32_VMX_CR0_FIXED1:
*pdata = vmx->nested.nested_vmx_cr0_fixed1;
break;
case MSR_IA32_VMX_CR4_FIXED0:
*pdata = vmx->nested.nested_vmx_cr4_fixed0;
break;
case MSR_IA32_VMX_CR4_FIXED1:
*pdata = vmx->nested.nested_vmx_cr4_fixed1;
break;
case MSR_IA32_VMX_VMCS_ENUM:
*pdata = vmx->nested.nested_vmx_vmcs_enum;
break;
case MSR_IA32_VMX_PROCBASED_CTLS2:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_secondary_ctls_low,
vmx->nested.nested_vmx_secondary_ctls_high);
break;
case MSR_IA32_VMX_EPT_VPID_CAP:
*pdata = vmx->nested.nested_vmx_ept_caps |
((u64)vmx->nested.nested_vmx_vpid_caps << 32);
break;
default:
return 1;
}
return 0;
}
static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
uint64_t val)
{
uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
return !(val & ~valid_bits);
}
/*
* Reads an msr value (of 'msr_index') into 'pdata'.
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
struct shared_msr_entry *msr;
switch (msr_info->index) {
#ifdef CONFIG_X86_64
case MSR_FS_BASE:
msr_info->data = vmcs_readl(GUEST_FS_BASE);
break;
case MSR_GS_BASE:
msr_info->data = vmcs_readl(GUEST_GS_BASE);
break;
case MSR_KERNEL_GS_BASE:
vmx_load_host_state(to_vmx(vcpu));
msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
break;
#endif
case MSR_EFER:
return kvm_get_msr_common(vcpu, msr_info);
case MSR_IA32_TSC:
msr_info->data = guest_read_tsc(vcpu);
break;
case MSR_IA32_SYSENTER_CS:
msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
break;
case MSR_IA32_SYSENTER_EIP:
msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
break;
case MSR_IA32_SYSENTER_ESP:
msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
break;
case MSR_IA32_BNDCFGS:
if (!kvm_mpx_supported())
return 1;
msr_info->data = vmcs_read64(GUEST_BNDCFGS);
break;
case MSR_IA32_MCG_EXT_CTL:
if (!msr_info->host_initiated &&
!(to_vmx(vcpu)->msr_ia32_feature_control &
FEATURE_CONTROL_LMCE))
return 1;
msr_info->data = vcpu->arch.mcg_ext_ctl;
break;
case MSR_IA32_FEATURE_CONTROL:
msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
break;
case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
if (!nested_vmx_allowed(vcpu))
return 1;
return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
case MSR_IA32_XSS:
if (!vmx_xsaves_supported())
return 1;
msr_info->data = vcpu->arch.ia32_xss;
break;
case MSR_TSC_AUX:
if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
return 1;
/* Otherwise falls through */
default:
msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
if (msr) {
msr_info->data = msr->data;
break;
}
return kvm_get_msr_common(vcpu, msr_info);
}
return 0;
}
static void vmx_leave_nested(struct kvm_vcpu *vcpu);
/*
* Writes msr value into into the appropriate "register".
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct shared_msr_entry *msr;
int ret = 0;
u32 msr_index = msr_info->index;
u64 data = msr_info->data;
switch (msr_index) {
case MSR_EFER:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
#ifdef CONFIG_X86_64
case MSR_FS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_FS_BASE, data);
break;
case MSR_GS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_GS_BASE, data);
break;
case MSR_KERNEL_GS_BASE:
vmx_load_host_state(vmx);
vmx->msr_guest_kernel_gs_base = data;
break;
#endif
case MSR_IA32_SYSENTER_CS:
vmcs_write32(GUEST_SYSENTER_CS, data);
break;
case MSR_IA32_SYSENTER_EIP:
vmcs_writel(GUEST_SYSENTER_EIP, data);
break;
case MSR_IA32_SYSENTER_ESP:
vmcs_writel(GUEST_SYSENTER_ESP, data);
break;
case MSR_IA32_BNDCFGS:
if (!kvm_mpx_supported())
return 1;
vmcs_write64(GUEST_BNDCFGS, data);
break;
case MSR_IA32_TSC:
kvm_write_tsc(vcpu, msr_info);
break;
case MSR_IA32_CR_PAT:
if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
return 1;
vmcs_write64(GUEST_IA32_PAT, data);
vcpu->arch.pat = data;
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_IA32_TSC_ADJUST:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_IA32_MCG_EXT_CTL:
if ((!msr_info->host_initiated &&
!(to_vmx(vcpu)->msr_ia32_feature_control &
FEATURE_CONTROL_LMCE)) ||
(data & ~MCG_EXT_CTL_LMCE_EN))
return 1;
vcpu->arch.mcg_ext_ctl = data;
break;
case MSR_IA32_FEATURE_CONTROL:
if (!vmx_feature_control_msr_valid(vcpu, data) ||
(to_vmx(vcpu)->msr_ia32_feature_control &
FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
return 1;
vmx->msr_ia32_feature_control = data;
if (msr_info->host_initiated && data == 0)
vmx_leave_nested(vcpu);
break;
case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
if (!msr_info->host_initiated)
return 1; /* they are read-only */
if (!nested_vmx_allowed(vcpu))
return 1;
return vmx_set_vmx_msr(vcpu, msr_index, data);
case MSR_IA32_XSS:
if (!vmx_xsaves_supported())
return 1;
/*
* The only supported bit as of Skylake is bit 8, but
* it is not supported on KVM.
*/
if (data != 0)
return 1;
vcpu->arch.ia32_xss = data;
if (vcpu->arch.ia32_xss != host_xss)
add_atomic_switch_msr(vmx, MSR_IA32_XSS,
vcpu->arch.ia32_xss, host_xss);
else
clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
break;
case MSR_TSC_AUX:
if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
return 1;
/* Check reserved bit, higher 32 bits should be zero */
if ((data >> 32) != 0)
return 1;
/* Otherwise falls through */
default:
msr = find_msr_entry(vmx, msr_index);
if (msr) {
u64 old_msr_data = msr->data;
msr->data = data;
if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
preempt_disable();
ret = kvm_set_shared_msr(msr->index, msr->data,
msr->mask);
preempt_enable();
if (ret)
msr->data = old_msr_data;
}
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
}
return ret;
}
static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
{
__set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
switch (reg) {
case VCPU_REGS_RSP:
vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
break;
case VCPU_REGS_RIP:
vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
break;
case VCPU_EXREG_PDPTR:
if (enable_ept)
ept_save_pdptrs(vcpu);
break;
default:
break;
}
}
static __init int cpu_has_kvm_support(void)
{
return cpu_has_vmx();
}
static __init int vmx_disabled_by_bios(void)
{
u64 msr;
rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
if (msr & FEATURE_CONTROL_LOCKED) {
/* launched w/ TXT and VMX disabled */
if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
&& tboot_enabled())
return 1;
/* launched w/o TXT and VMX only enabled w/ TXT */
if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
&& (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
&& !tboot_enabled()) {
printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
"activate TXT before enabling KVM\n");
return 1;
}
/* launched w/o TXT and VMX disabled */
if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
&& !tboot_enabled())
return 1;
}
return 0;
}
static void kvm_cpu_vmxon(u64 addr)
{
intel_pt_handle_vmx(1);
asm volatile (ASM_VMX_VMXON_RAX
: : "a"(&addr), "m"(addr)
: "memory", "cc");
}
static int hardware_enable(void)
{
int cpu = raw_smp_processor_id();
u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
u64 old, test_bits;
if (cr4_read_shadow() & X86_CR4_VMXE)
return -EBUSY;
INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
/*
* Now we can enable the vmclear operation in kdump
* since the loaded_vmcss_on_cpu list on this cpu
* has been initialized.
*
* Though the cpu is not in VMX operation now, there
* is no problem to enable the vmclear operation
* for the loaded_vmcss_on_cpu list is empty!
*/
crash_enable_local_vmclear(cpu);
rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
test_bits = FEATURE_CONTROL_LOCKED;
test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
if (tboot_enabled())
test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
if ((old & test_bits) != test_bits) {
/* enable and lock */
wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
}
cr4_set_bits(X86_CR4_VMXE);
if (vmm_exclusive) {
kvm_cpu_vmxon(phys_addr);
ept_sync_global();
}
native_store_gdt(this_cpu_ptr(&host_gdt));
return 0;
}
static void vmclear_local_loaded_vmcss(void)
{
int cpu = raw_smp_processor_id();
struct loaded_vmcs *v, *n;
list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
loaded_vmcss_on_cpu_link)
__loaded_vmcs_clear(v);
}
/* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
* tricks.
*/
static void kvm_cpu_vmxoff(void)
{
asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
intel_pt_handle_vmx(0);
}
static void hardware_disable(void)
{
if (vmm_exclusive) {
vmclear_local_loaded_vmcss();
kvm_cpu_vmxoff();
}
cr4_clear_bits(X86_CR4_VMXE);
}
static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
u32 msr, u32 *result)
{
u32 vmx_msr_low, vmx_msr_high;
u32 ctl = ctl_min | ctl_opt;
rdmsr(msr, vmx_msr_low, vmx_msr_high);
ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
/* Ensure minimum (required) set of control bits are supported. */
if (ctl_min & ~ctl)
return -EIO;
*result = ctl;
return 0;
}
static __init bool allow_1_setting(u32 msr, u32 ctl)
{
u32 vmx_msr_low, vmx_msr_high;
rdmsr(msr, vmx_msr_low, vmx_msr_high);
return vmx_msr_high & ctl;
}
static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
{
u32 vmx_msr_low, vmx_msr_high;
u32 min, opt, min2, opt2;
u32 _pin_based_exec_control = 0;
u32 _cpu_based_exec_control = 0;
u32 _cpu_based_2nd_exec_control = 0;
u32 _vmexit_control = 0;
u32 _vmentry_control = 0;
min = CPU_BASED_HLT_EXITING |
#ifdef CONFIG_X86_64
CPU_BASED_CR8_LOAD_EXITING |
CPU_BASED_CR8_STORE_EXITING |
#endif
CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING |
CPU_BASED_USE_IO_BITMAPS |
CPU_BASED_MOV_DR_EXITING |
CPU_BASED_USE_TSC_OFFSETING |
CPU_BASED_MWAIT_EXITING |
CPU_BASED_MONITOR_EXITING |
CPU_BASED_INVLPG_EXITING |
CPU_BASED_RDPMC_EXITING;
opt = CPU_BASED_TPR_SHADOW |
CPU_BASED_USE_MSR_BITMAPS |
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
&_cpu_based_exec_control) < 0)
return -EIO;
#ifdef CONFIG_X86_64
if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
_cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
~CPU_BASED_CR8_STORE_EXITING;
#endif
if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
min2 = 0;
opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_WBINVD_EXITING |
SECONDARY_EXEC_ENABLE_VPID |
SECONDARY_EXEC_ENABLE_EPT |
SECONDARY_EXEC_UNRESTRICTED_GUEST |
SECONDARY_EXEC_PAUSE_LOOP_EXITING |
SECONDARY_EXEC_RDTSCP |
SECONDARY_EXEC_ENABLE_INVPCID |
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
SECONDARY_EXEC_SHADOW_VMCS |
SECONDARY_EXEC_XSAVES |
SECONDARY_EXEC_ENABLE_PML |
SECONDARY_EXEC_TSC_SCALING;
if (adjust_vmx_controls(min2, opt2,
MSR_IA32_VMX_PROCBASED_CTLS2,
&_cpu_based_2nd_exec_control) < 0)
return -EIO;
}
#ifndef CONFIG_X86_64
if (!(_cpu_based_2nd_exec_control &
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
_cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
#endif
if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
_cpu_based_2nd_exec_control &= ~(
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
/* CR3 accesses and invlpg don't need to cause VM Exits when EPT
enabled */
_cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING |
CPU_BASED_INVLPG_EXITING);
rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
vmx_capability.ept, vmx_capability.vpid);
}
min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
#ifdef CONFIG_X86_64
min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
#endif
opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
VM_EXIT_CLEAR_BNDCFGS;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
&_vmexit_control) < 0)
return -EIO;
min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
PIN_BASED_VMX_PREEMPTION_TIMER;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
&_pin_based_exec_control) < 0)
return -EIO;
if (cpu_has_broken_vmx_preemption_timer())
_pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
if (!(_cpu_based_2nd_exec_control &
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
_pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
&_vmentry_control) < 0)
return -EIO;
rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
/* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
return -EIO;
#ifdef CONFIG_X86_64
/* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
if (vmx_msr_high & (1u<<16))
return -EIO;
#endif
/* Require Write-Back (WB) memory type for VMCS accesses. */
if (((vmx_msr_high >> 18) & 15) != 6)
return -EIO;
vmcs_conf->size = vmx_msr_high & 0x1fff;
vmcs_conf->order = get_order(vmcs_conf->size);
vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
vmcs_conf->revision_id = vmx_msr_low;
vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
vmcs_conf->vmexit_ctrl = _vmexit_control;
vmcs_conf->vmentry_ctrl = _vmentry_control;
cpu_has_load_ia32_efer =
allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
VM_ENTRY_LOAD_IA32_EFER)
&& allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
VM_EXIT_LOAD_IA32_EFER);
cpu_has_load_perf_global_ctrl =
allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
&& allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
/*
* Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
* but due to errata below it can't be used. Workaround is to use
* msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
*
* VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
*
* AAK155 (model 26)
* AAP115 (model 30)
* AAT100 (model 37)
* BC86,AAY89,BD102 (model 44)
* BA97 (model 46)
*
*/
if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
switch (boot_cpu_data.x86_model) {
case 26:
case 30:
case 37:
case 44:
case 46:
cpu_has_load_perf_global_ctrl = false;
printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
"does not work properly. Using workaround\n");
break;
default:
break;
}
}
if (boot_cpu_has(X86_FEATURE_XSAVES))
rdmsrl(MSR_IA32_XSS, host_xss);
return 0;
}
static struct vmcs *alloc_vmcs_cpu(int cpu)
{
int node = cpu_to_node(cpu);
struct page *pages;
struct vmcs *vmcs;
pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
if (!pages)
return NULL;
vmcs = page_address(pages);
memset(vmcs, 0, vmcs_config.size);
vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
return vmcs;
}
static struct vmcs *alloc_vmcs(void)
{
return alloc_vmcs_cpu(raw_smp_processor_id());
}
static void free_vmcs(struct vmcs *vmcs)
{
free_pages((unsigned long)vmcs, vmcs_config.order);
}
/*
* Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
*/
static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
{
if (!loaded_vmcs->vmcs)
return;
loaded_vmcs_clear(loaded_vmcs);
free_vmcs(loaded_vmcs->vmcs);
loaded_vmcs->vmcs = NULL;
WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
}
static void free_kvm_area(void)
{
int cpu;
for_each_possible_cpu(cpu) {
free_vmcs(per_cpu(vmxarea, cpu));
per_cpu(vmxarea, cpu) = NULL;
}
}
static void init_vmcs_shadow_fields(void)
{
int i, j;
/* No checks for read only fields yet */
for (i = j = 0; i < max_shadow_read_write_fields; i++) {
switch (shadow_read_write_fields[i]) {
case GUEST_BNDCFGS:
if (!kvm_mpx_supported())
continue;
break;
default:
break;
}
if (j < i)
shadow_read_write_fields[j] =
shadow_read_write_fields[i];
j++;
}
max_shadow_read_write_fields = j;
/* shadowed fields guest access without vmexit */
for (i = 0; i < max_shadow_read_write_fields; i++) {
clear_bit(shadow_read_write_fields[i],
vmx_vmwrite_bitmap);
clear_bit(shadow_read_write_fields[i],
vmx_vmread_bitmap);
}
for (i = 0; i < max_shadow_read_only_fields; i++)
clear_bit(shadow_read_only_fields[i],
vmx_vmread_bitmap);
}
static __init int alloc_kvm_area(void)
{
int cpu;
for_each_possible_cpu(cpu) {
struct vmcs *vmcs;
vmcs = alloc_vmcs_cpu(cpu);
if (!vmcs) {
free_kvm_area();
return -ENOMEM;
}
per_cpu(vmxarea, cpu) = vmcs;
}
return 0;
}
static bool emulation_required(struct kvm_vcpu *vcpu)
{
return emulate_invalid_guest_state && !guest_state_valid(vcpu);
}
static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
struct kvm_segment *save)
{
if (!emulate_invalid_guest_state) {
/*
* CS and SS RPL should be equal during guest entry according
* to VMX spec, but in reality it is not always so. Since vcpu
* is in the middle of the transition from real mode to
* protected mode it is safe to assume that RPL 0 is a good
* default value.
*/
if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
save->selector &= ~SEGMENT_RPL_MASK;
save->dpl = save->selector & SEGMENT_RPL_MASK;
save->s = 1;
}
vmx_set_segment(vcpu, save, seg);
}
static void enter_pmode(struct kvm_vcpu *vcpu)
{
unsigned long flags;
struct vcpu_vmx *vmx = to_vmx(vcpu);
/*
* Update real mode segment cache. It may be not up-to-date if sement
* register was written while vcpu was in a guest mode.
*/
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
vmx->rmode.vm86_active = 0;
vmx_segment_cache_clear(vmx);
vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
flags = vmcs_readl(GUEST_RFLAGS);
flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
vmcs_writel(GUEST_RFLAGS, flags);
vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
(vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
update_exception_bitmap(vcpu);
fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
}
static void fix_rmode_seg(int seg, struct kvm_segment *save)
{
const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
struct kvm_segment var = *save;
var.dpl = 0x3;
if (seg == VCPU_SREG_CS)
var.type = 0x3;
if (!emulate_invalid_guest_state) {
var.selector = var.base >> 4;
var.base = var.base & 0xffff0;
var.limit = 0xffff;
var.g = 0;
var.db = 0;
var.present = 1;
var.s = 1;
var.l = 0;
var.unusable = 0;
var.type = 0x3;
var.avl = 0;
if (save->base & 0xf)
printk_once(KERN_WARNING "kvm: segment base is not "
"paragraph aligned when entering "
"protected mode (seg=%d)", seg);
}
vmcs_write16(sf->selector, var.selector);
vmcs_write32(sf->base, var.base);
vmcs_write32(sf->limit, var.limit);
vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
}
static void enter_rmode(struct kvm_vcpu *vcpu)
{
unsigned long flags;
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
vmx->rmode.vm86_active = 1;
/*
* Very old userspace does not call KVM_SET_TSS_ADDR before entering
* vcpu. Warn the user that an update is overdue.
*/
if (!vcpu->kvm->arch.tss_addr)
printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
"called before entering vcpu\n");
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
flags = vmcs_readl(GUEST_RFLAGS);
vmx->rmode.save_rflags = flags;
flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
vmcs_writel(GUEST_RFLAGS, flags);
vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
update_exception_bitmap(vcpu);
fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
kvm_mmu_reset_context(vcpu);
}
static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
if (!msr)
return;
/*
* Force kernel_gs_base reloading before EFER changes, as control
* of this msr depends on is_long_mode().
*/
vmx_load_host_state(to_vmx(vcpu));
vcpu->arch.efer = efer;
if (efer & EFER_LMA) {
vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
msr->data = efer;
} else {
vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
msr->data = efer & ~EFER_LME;
}
setup_msrs(vmx);
}
#ifdef CONFIG_X86_64
static void enter_lmode(struct kvm_vcpu *vcpu)
{
u32 guest_tr_ar;
vmx_segment_cache_clear(to_vmx(vcpu));
guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
pr_debug_ratelimited("%s: tss fixup for long mode. \n",
__func__);
vmcs_write32(GUEST_TR_AR_BYTES,
(guest_tr_ar & ~VMX_AR_TYPE_MASK)
| VMX_AR_TYPE_BUSY_64_TSS);
}
vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
}
static void exit_lmode(struct kvm_vcpu *vcpu)
{
vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
}
#endif
static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid)
{
vpid_sync_context(vpid);
if (enable_ept) {
if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
return;
ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
}
}
static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
{
__vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid);
}
static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
{
ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
}
static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
{
if (enable_ept && is_paging(vcpu))
vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
}
static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
{
ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
}
static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
{
struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
if (!test_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_dirty))
return;
if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
}
}
static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
{
struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
}
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_avail);
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_dirty);
}
static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
{
u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
SECONDARY_EXEC_UNRESTRICTED_GUEST &&
nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
return fixed_bits_valid(val, fixed0, fixed1);
}
static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
{
u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
return fixed_bits_valid(val, fixed0, fixed1);
}
static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
{
u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed0;
u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed1;
return fixed_bits_valid(val, fixed0, fixed1);
}
/* No difference in the restrictions on guest and host CR4 in VMX operation. */
#define nested_guest_cr4_valid nested_cr4_valid
#define nested_host_cr4_valid nested_cr4_valid
static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
unsigned long cr0,
struct kvm_vcpu *vcpu)
{
if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
vmx_decache_cr3(vcpu);
if (!(cr0 & X86_CR0_PG)) {
/* From paging/starting to nonpaging */
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
(CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING));
vcpu->arch.cr0 = cr0;
vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
} else if (!is_paging(vcpu)) {
/* From nonpaging to paging */
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
~(CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING));
vcpu->arch.cr0 = cr0;
vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
}
if (!(cr0 & X86_CR0_WP))
*hw_cr0 &= ~X86_CR0_WP;
}
static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long hw_cr0;
hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
if (enable_unrestricted_guest)
hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
else {
hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
enter_pmode(vcpu);
if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
enter_rmode(vcpu);
}
#ifdef CONFIG_X86_64
if (vcpu->arch.efer & EFER_LME) {
if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
enter_lmode(vcpu);
if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
exit_lmode(vcpu);
}
#endif
if (enable_ept)
ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
if (!vcpu->fpu_active)
hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
vmcs_writel(CR0_READ_SHADOW, cr0);
vmcs_writel(GUEST_CR0, hw_cr0);
vcpu->arch.cr0 = cr0;
/* depends on vcpu->arch.cr0 to be set to a new value */
vmx->emulation_required = emulation_required(vcpu);
}
static u64 construct_eptp(unsigned long root_hpa)
{
u64 eptp;
/* TODO write the value reading from MSR */
eptp = VMX_EPT_DEFAULT_MT |
VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
if (enable_ept_ad_bits)
eptp |= VMX_EPT_AD_ENABLE_BIT;
eptp |= (root_hpa & PAGE_MASK);
return eptp;
}
static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
{
unsigned long guest_cr3;
u64 eptp;
guest_cr3 = cr3;
if (enable_ept) {
eptp = construct_eptp(cr3);
vmcs_write64(EPT_POINTER, eptp);
if (is_paging(vcpu) || is_guest_mode(vcpu))
guest_cr3 = kvm_read_cr3(vcpu);
else
guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
ept_load_pdptrs(vcpu);
}
vmx_flush_tlb(vcpu);
vmcs_writel(GUEST_CR3, guest_cr3);
}
static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
{
/*
* Pass through host's Machine Check Enable value to hw_cr4, which
* is in force while we are in guest mode. Do not let guests control
* this bit, even if host CR4.MCE == 0.
*/
unsigned long hw_cr4 =
(cr4_read_shadow() & X86_CR4_MCE) |
(cr4 & ~X86_CR4_MCE) |
(to_vmx(vcpu)->rmode.vm86_active ?
KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
if (cr4 & X86_CR4_VMXE) {
/*
* To use VMXON (and later other VMX instructions), a guest
* must first be able to turn on cr4.VMXE (see handle_vmon()).
* So basically the check on whether to allow nested VMX
* is here.
*/
if (!nested_vmx_allowed(vcpu))
return 1;
}
if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
return 1;
vcpu->arch.cr4 = cr4;
if (enable_ept) {
if (!is_paging(vcpu)) {
hw_cr4 &= ~X86_CR4_PAE;
hw_cr4 |= X86_CR4_PSE;
} else if (!(cr4 & X86_CR4_PAE)) {
hw_cr4 &= ~X86_CR4_PAE;
}
}
if (!enable_unrestricted_guest && !is_paging(vcpu))
/*
* SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
* hardware. To emulate this behavior, SMEP/SMAP/PKU needs
* to be manually disabled when guest switches to non-paging
* mode.
*
* If !enable_unrestricted_guest, the CPU is always running
* with CR0.PG=1 and CR4 needs to be modified.
* If enable_unrestricted_guest, the CPU automatically
* disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
*/
hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
vmcs_writel(CR4_READ_SHADOW, cr4);
vmcs_writel(GUEST_CR4, hw_cr4);
return 0;
}
static void vmx_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 ar;
if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
*var = vmx->rmode.segs[seg];
if (seg == VCPU_SREG_TR
|| var->selector == vmx_read_guest_seg_selector(vmx, seg))
return;
var->base = vmx_read_guest_seg_base(vmx, seg);
var->selector = vmx_read_guest_seg_selector(vmx, seg);
return;
}
var->base = vmx_read_guest_seg_base(vmx, seg);
var->limit = vmx_read_guest_seg_limit(vmx, seg);
var->selector = vmx_read_guest_seg_selector(vmx, seg);
ar = vmx_read_guest_seg_ar(vmx, seg);
var->unusable = (ar >> 16) & 1;
var->type = ar & 15;
var->s = (ar >> 4) & 1;
var->dpl = (ar >> 5) & 3;
/*
* Some userspaces do not preserve unusable property. Since usable
* segment has to be present according to VMX spec we can use present
* property to amend userspace bug by making unusable segment always
* nonpresent. vmx_segment_access_rights() already marks nonpresent
* segment as unusable.
*/
var->present = !var->unusable;
var->avl = (ar >> 12) & 1;
var->l = (ar >> 13) & 1;
var->db = (ar >> 14) & 1;
var->g = (ar >> 15) & 1;
}
static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
{
struct kvm_segment s;
if (to_vmx(vcpu)->rmode.vm86_active) {
vmx_get_segment(vcpu, &s, seg);
return s.base;
}
return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
}
static int vmx_get_cpl(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (unlikely(vmx->rmode.vm86_active))
return 0;
else {
int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
return VMX_AR_DPL(ar);
}
}
static u32 vmx_segment_access_rights(struct kvm_segment *var)
{
u32 ar;
if (var->unusable || !var->present)
ar = 1 << 16;
else {
ar = var->type & 15;
ar |= (var->s & 1) << 4;
ar |= (var->dpl & 3) << 5;
ar |= (var->present & 1) << 7;
ar |= (var->avl & 1) << 12;
ar |= (var->l & 1) << 13;
ar |= (var->db & 1) << 14;
ar |= (var->g & 1) << 15;
}
return ar;
}
static void vmx_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
vmx_segment_cache_clear(vmx);
if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
vmx->rmode.segs[seg] = *var;
if (seg == VCPU_SREG_TR)
vmcs_write16(sf->selector, var->selector);
else if (var->s)
fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
goto out;
}
vmcs_writel(sf->base, var->base);
vmcs_write32(sf->limit, var->limit);
vmcs_write16(sf->selector, var->selector);
/*
* Fix the "Accessed" bit in AR field of segment registers for older
* qemu binaries.
* IA32 arch specifies that at the time of processor reset the
* "Accessed" bit in the AR field of segment registers is 1. And qemu
* is setting it to 0 in the userland code. This causes invalid guest
* state vmexit when "unrestricted guest" mode is turned on.
* Fix for this setup issue in cpu_reset is being pushed in the qemu
* tree. Newer qemu binaries with that qemu fix would not need this
* kvm hack.
*/
if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
var->type |= 0x1; /* Accessed */
vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
out:
vmx->emulation_required = emulation_required(vcpu);
}
static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
{
u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
*db = (ar >> 14) & 1;
*l = (ar >> 13) & 1;
}
static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
dt->address = vmcs_readl(GUEST_IDTR_BASE);
}
static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
vmcs_writel(GUEST_IDTR_BASE, dt->address);
}
static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
dt->address = vmcs_readl(GUEST_GDTR_BASE);
}
static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
vmcs_writel(GUEST_GDTR_BASE, dt->address);
}
static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
{
struct kvm_segment var;
u32 ar;
vmx_get_segment(vcpu, &var, seg);
var.dpl = 0x3;
if (seg == VCPU_SREG_CS)
var.type = 0x3;
ar = vmx_segment_access_rights(&var);
if (var.base != (var.selector << 4))
return false;
if (var.limit != 0xffff)
return false;
if (ar != 0xf3)
return false;
return true;
}
static bool code_segment_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs;
unsigned int cs_rpl;
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
cs_rpl = cs.selector & SEGMENT_RPL_MASK;
if (cs.unusable)
return false;
if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
return false;
if (!cs.s)
return false;
if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
if (cs.dpl > cs_rpl)
return false;
} else {
if (cs.dpl != cs_rpl)
return false;
}
if (!cs.present)
return false;
/* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
return true;
}
static bool stack_segment_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment ss;
unsigned int ss_rpl;
vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
ss_rpl = ss.selector & SEGMENT_RPL_MASK;
if (ss.unusable)
return true;
if (ss.type != 3 && ss.type != 7)
return false;
if (!ss.s)
return false;
if (ss.dpl != ss_rpl) /* DPL != RPL */
return false;
if (!ss.present)
return false;
return true;
}
static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
{
struct kvm_segment var;
unsigned int rpl;
vmx_get_segment(vcpu, &var, seg);
rpl = var.selector & SEGMENT_RPL_MASK;
if (var.unusable)
return true;
if (!var.s)
return false;
if (!var.present)
return false;
if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
if (var.dpl < rpl) /* DPL < RPL */
return false;
}
/* TODO: Add other members to kvm_segment_field to allow checking for other access
* rights flags
*/
return true;
}
static bool tr_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment tr;
vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
if (tr.unusable)
return false;
if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
return false;
if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
return false;
if (!tr.present)
return false;
return true;
}
static bool ldtr_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment ldtr;
vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
if (ldtr.unusable)
return true;
if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
return false;
if (ldtr.type != 2)
return false;
if (!ldtr.present)
return false;
return true;
}
static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs, ss;
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
return ((cs.selector & SEGMENT_RPL_MASK) ==
(ss.selector & SEGMENT_RPL_MASK));
}
/*
* Check if guest state is valid. Returns true if valid, false if
* not.
* We assume that registers are always usable
*/
static bool guest_state_valid(struct kvm_vcpu *vcpu)
{
if (enable_unrestricted_guest)
return true;
/* real mode guest state checks */
if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
return false;
} else {
/* protected mode guest state checks */
if (!cs_ss_rpl_check(vcpu))
return false;
if (!code_segment_valid(vcpu))
return false;
if (!stack_segment_valid(vcpu))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_DS))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_ES))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_FS))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_GS))
return false;
if (!tr_valid(vcpu))
return false;
if (!ldtr_valid(vcpu))
return false;
}
/* TODO:
* - Add checks on RIP
* - Add checks on RFLAGS
*/
return true;
}
static int init_rmode_tss(struct kvm *kvm)
{
gfn_t fn;
u16 data = 0;
int idx, r;
idx = srcu_read_lock(&kvm->srcu);
fn = kvm->arch.tss_addr >> PAGE_SHIFT;
r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
if (r < 0)
goto out;
data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
r = kvm_write_guest_page(kvm, fn++, &data,
TSS_IOPB_BASE_OFFSET, sizeof(u16));
if (r < 0)
goto out;
r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
if (r < 0)
goto out;
r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
if (r < 0)
goto out;
data = ~0;
r = kvm_write_guest_page(kvm, fn, &data,
RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
sizeof(u8));
out:
srcu_read_unlock(&kvm->srcu, idx);
return r;
}
static int init_rmode_identity_map(struct kvm *kvm)
{
int i, idx, r = 0;
kvm_pfn_t identity_map_pfn;
u32 tmp;
if (!enable_ept)
return 0;
/* Protect kvm->arch.ept_identity_pagetable_done. */
mutex_lock(&kvm->slots_lock);
if (likely(kvm->arch.ept_identity_pagetable_done))
goto out2;
identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
r = alloc_identity_pagetable(kvm);
if (r < 0)
goto out2;
idx = srcu_read_lock(&kvm->srcu);
r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
if (r < 0)
goto out;
/* Set up identity-mapping pagetable for EPT in real mode */
for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
_PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
r = kvm_write_guest_page(kvm, identity_map_pfn,
&tmp, i * sizeof(tmp), sizeof(tmp));
if (r < 0)
goto out;
}
kvm->arch.ept_identity_pagetable_done = true;
out:
srcu_read_unlock(&kvm->srcu, idx);
out2:
mutex_unlock(&kvm->slots_lock);
return r;
}
static void seg_setup(int seg)
{
const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
unsigned int ar;
vmcs_write16(sf->selector, 0);
vmcs_writel(sf->base, 0);
vmcs_write32(sf->limit, 0xffff);
ar = 0x93;
if (seg == VCPU_SREG_CS)
ar |= 0x08; /* code segment */
vmcs_write32(sf->ar_bytes, ar);
}
static int alloc_apic_access_page(struct kvm *kvm)
{
struct page *page;
int r = 0;
mutex_lock(&kvm->slots_lock);
if (kvm->arch.apic_access_page_done)
goto out;
r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
if (r)
goto out;
page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
if (is_error_page(page)) {
r = -EFAULT;
goto out;
}
/*
* Do not pin the page in memory, so that memory hot-unplug
* is able to migrate it.
*/
put_page(page);
kvm->arch.apic_access_page_done = true;
out:
mutex_unlock(&kvm->slots_lock);
return r;
}
static int alloc_identity_pagetable(struct kvm *kvm)
{
/* Called with kvm->slots_lock held. */
int r = 0;
BUG_ON(kvm->arch.ept_identity_pagetable_done);
r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
kvm->arch.ept_identity_map_addr, PAGE_SIZE);
return r;
}
static int allocate_vpid(void)
{
int vpid;
if (!enable_vpid)
return 0;
spin_lock(&vmx_vpid_lock);
vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
if (vpid < VMX_NR_VPIDS)
__set_bit(vpid, vmx_vpid_bitmap);
else
vpid = 0;
spin_unlock(&vmx_vpid_lock);
return vpid;
}
static void free_vpid(int vpid)
{
if (!enable_vpid || vpid == 0)
return;
spin_lock(&vmx_vpid_lock);
__clear_bit(vpid, vmx_vpid_bitmap);
spin_unlock(&vmx_vpid_lock);
}
#define MSR_TYPE_R 1
#define MSR_TYPE_W 2
static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
u32 msr, int type)
{
int f = sizeof(unsigned long);
if (!cpu_has_vmx_msr_bitmap())
return;
/*
* See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
* have the write-low and read-high bitmap offsets the wrong way round.
* We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
*/
if (msr <= 0x1fff) {
if (type & MSR_TYPE_R)
/* read-low */
__clear_bit(msr, msr_bitmap + 0x000 / f);
if (type & MSR_TYPE_W)
/* write-low */
__clear_bit(msr, msr_bitmap + 0x800 / f);
} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
msr &= 0x1fff;
if (type & MSR_TYPE_R)
/* read-high */
__clear_bit(msr, msr_bitmap + 0x400 / f);
if (type & MSR_TYPE_W)
/* write-high */
__clear_bit(msr, msr_bitmap + 0xc00 / f);
}
}
/*
* If a msr is allowed by L0, we should check whether it is allowed by L1.
* The corresponding bit will be cleared unless both of L0 and L1 allow it.
*/
static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
unsigned long *msr_bitmap_nested,
u32 msr, int type)
{
int f = sizeof(unsigned long);
if (!cpu_has_vmx_msr_bitmap()) {
WARN_ON(1);
return;
}
/*
* See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
* have the write-low and read-high bitmap offsets the wrong way round.
* We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
*/
if (msr <= 0x1fff) {
if (type & MSR_TYPE_R &&
!test_bit(msr, msr_bitmap_l1 + 0x000 / f))
/* read-low */
__clear_bit(msr, msr_bitmap_nested + 0x000 / f);
if (type & MSR_TYPE_W &&
!test_bit(msr, msr_bitmap_l1 + 0x800 / f))
/* write-low */
__clear_bit(msr, msr_bitmap_nested + 0x800 / f);
} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
msr &= 0x1fff;
if (type & MSR_TYPE_R &&
!test_bit(msr, msr_bitmap_l1 + 0x400 / f))
/* read-high */
__clear_bit(msr, msr_bitmap_nested + 0x400 / f);
if (type & MSR_TYPE_W &&
!test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
/* write-high */
__clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
}
}
static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
{
if (!longmode_only)
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
msr, MSR_TYPE_R | MSR_TYPE_W);
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
msr, MSR_TYPE_R | MSR_TYPE_W);
}
static void vmx_disable_intercept_msr_x2apic(u32 msr, int type, bool apicv_active)
{
if (apicv_active) {
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic_apicv,
msr, type);
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic_apicv,
msr, type);
} else {
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
msr, type);
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
msr, type);
}
}
static bool vmx_get_enable_apicv(void)
{
return enable_apicv;
}
static int vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int max_irr;
void *vapic_page;
u16 status;
if (vmx->nested.pi_desc &&
vmx->nested.pi_pending) {
vmx->nested.pi_pending = false;
if (!pi_test_and_clear_on(vmx->nested.pi_desc))
return 0;
max_irr = find_last_bit(
(unsigned long *)vmx->nested.pi_desc->pir, 256);
if (max_irr == 256)
return 0;
vapic_page = kmap(vmx->nested.virtual_apic_page);
if (!vapic_page) {
WARN_ON(1);
return -ENOMEM;
}
__kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
kunmap(vmx->nested.virtual_apic_page);
status = vmcs_read16(GUEST_INTR_STATUS);
if ((u8)max_irr > ((u8)status & 0xff)) {
status &= ~0xff;
status |= (u8)max_irr;
vmcs_write16(GUEST_INTR_STATUS, status);
}
}
return 0;
}
static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu)
{
#ifdef CONFIG_SMP
if (vcpu->mode == IN_GUEST_MODE) {
struct vcpu_vmx *vmx = to_vmx(vcpu);
/*
* Currently, we don't support urgent interrupt,
* all interrupts are recognized as non-urgent
* interrupt, so we cannot post interrupts when
* 'SN' is set.
*
* If the vcpu is in guest mode, it means it is
* running instead of being scheduled out and
* waiting in the run queue, and that's the only
* case when 'SN' is set currently, warning if
* 'SN' is set.
*/
WARN_ON_ONCE(pi_test_sn(&vmx->pi_desc));
apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
POSTED_INTR_VECTOR);
return true;
}
#endif
return false;
}
static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
int vector)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (is_guest_mode(vcpu) &&
vector == vmx->nested.posted_intr_nv) {
/* the PIR and ON have been set by L1. */
kvm_vcpu_trigger_posted_interrupt(vcpu);
/*
* If a posted intr is not recognized by hardware,
* we will accomplish it in the next vmentry.
*/
vmx->nested.pi_pending = true;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
return -1;
}
/*
* Send interrupt to vcpu via posted interrupt way.
* 1. If target vcpu is running(non-root mode), send posted interrupt
* notification to vcpu and hardware will sync PIR to vIRR atomically.
* 2. If target vcpu isn't running(root mode), kick it to pick up the
* interrupt from PIR in next vmentry.
*/
static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int r;
r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
if (!r)
return;
if (pi_test_and_set_pir(vector, &vmx->pi_desc))
return;
r = pi_test_and_set_on(&vmx->pi_desc);
kvm_make_request(KVM_REQ_EVENT, vcpu);
if (r || !kvm_vcpu_trigger_posted_interrupt(vcpu))
kvm_vcpu_kick(vcpu);
}
static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!pi_test_on(&vmx->pi_desc))
return;
pi_clear_on(&vmx->pi_desc);
/*
* IOMMU can write to PIR.ON, so the barrier matters even on UP.
* But on x86 this is just a compiler barrier anyway.
*/
smp_mb__after_atomic();
kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
}
/*
* Set up the vmcs's constant host-state fields, i.e., host-state fields that
* will not change in the lifetime of the guest.
* Note that host-state that does change is set elsewhere. E.g., host-state
* that is set differently for each CPU is set in vmx_vcpu_load(), not here.
*/
static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
{
u32 low32, high32;
unsigned long tmpl;
struct desc_ptr dt;
unsigned long cr0, cr4;
cr0 = read_cr0();
WARN_ON(cr0 & X86_CR0_TS);
vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
/* Save the most likely value for this task's CR4 in the VMCS. */
cr4 = cr4_read_shadow();
vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
vmx->host_state.vmcs_host_cr4 = cr4;
vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
#ifdef CONFIG_X86_64
/*
* Load null selectors, so we can avoid reloading them in
* __vmx_load_host_state(), in case userspace uses the null selectors
* too (the expected case).
*/
vmcs_write16(HOST_DS_SELECTOR, 0);
vmcs_write16(HOST_ES_SELECTOR, 0);
#else
vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
#endif
vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
native_store_idt(&dt);
vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
vmx->host_idt_base = dt.address;
vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
rdmsr(MSR_IA32_CR_PAT, low32, high32);
vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
}
}
static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
{
vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
if (enable_ept)
vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
if (is_guest_mode(&vmx->vcpu))
vmx->vcpu.arch.cr4_guest_owned_bits &=
~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
}
static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
{
u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
if (!kvm_vcpu_apicv_active(&vmx->vcpu))
pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
/* Enable the preemption timer dynamically */
pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
return pin_based_exec_ctrl;
}
static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
if (cpu_has_secondary_exec_ctrls()) {
if (kvm_vcpu_apicv_active(vcpu))
vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
else
vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
}
if (cpu_has_vmx_msr_bitmap())
vmx_set_msr_bitmap(vcpu);
}
static u32 vmx_exec_control(struct vcpu_vmx *vmx)
{
u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
exec_control &= ~CPU_BASED_MOV_DR_EXITING;
if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
exec_control &= ~CPU_BASED_TPR_SHADOW;
#ifdef CONFIG_X86_64
exec_control |= CPU_BASED_CR8_STORE_EXITING |
CPU_BASED_CR8_LOAD_EXITING;
#endif
}
if (!enable_ept)
exec_control |= CPU_BASED_CR3_STORE_EXITING |
CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_INVLPG_EXITING;
return exec_control;
}
static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
{
u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
if (!cpu_need_virtualize_apic_accesses(&vmx->vcpu))
exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
if (vmx->vpid == 0)
exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
if (!enable_ept) {
exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
enable_unrestricted_guest = 0;
/* Enable INVPCID for non-ept guests may cause performance regression. */
exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
}
if (!enable_unrestricted_guest)
exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
if (!ple_gap)
exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
if (!kvm_vcpu_apicv_active(&vmx->vcpu))
exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
/* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
(handle_vmptrld).
We can NOT enable shadow_vmcs here because we don't have yet
a current VMCS12
*/
exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
if (!enable_pml)
exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
return exec_control;
}
static void ept_set_mmio_spte_mask(void)
{
/*
* EPT Misconfigurations can be generated if the value of bits 2:0
* of an EPT paging-structure entry is 110b (write/execute).
* Also, magic bits (0x3ull << 62) is set to quickly identify mmio
* spte.
*/
kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull);
}
#define VMX_XSS_EXIT_BITMAP 0
/*
* Sets up the vmcs for emulated real mode.
*/
static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
{
#ifdef CONFIG_X86_64
unsigned long a;
#endif
int i;
/* I/O */
vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
if (enable_shadow_vmcs) {
vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
}
if (cpu_has_vmx_msr_bitmap())
vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
/* Control */
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
vmx->hv_deadline_tsc = -1;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
if (cpu_has_secondary_exec_ctrls()) {
vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
vmx_secondary_exec_control(vmx));
}
if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
vmcs_write64(EOI_EXIT_BITMAP0, 0);
vmcs_write64(EOI_EXIT_BITMAP1, 0);
vmcs_write64(EOI_EXIT_BITMAP2, 0);
vmcs_write64(EOI_EXIT_BITMAP3, 0);
vmcs_write16(GUEST_INTR_STATUS, 0);
vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
}
if (ple_gap) {
vmcs_write32(PLE_GAP, ple_gap);
vmx->ple_window = ple_window;
vmx->ple_window_dirty = true;
}
vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
vmx_set_constant_host_state(vmx);
#ifdef CONFIG_X86_64
rdmsrl(MSR_FS_BASE, a);
vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
rdmsrl(MSR_GS_BASE, a);
vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
#else
vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
#endif
vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
u32 index = vmx_msr_index[i];
u32 data_low, data_high;
int j = vmx->nmsrs;
if (rdmsr_safe(index, &data_low, &data_high) < 0)
continue;
if (wrmsr_safe(index, data_low, data_high) < 0)
continue;
vmx->guest_msrs[j].index = i;
vmx->guest_msrs[j].data = 0;
vmx->guest_msrs[j].mask = -1ull;
++vmx->nmsrs;
}
vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
/* 22.2.1, 20.8.1 */
vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
set_cr4_guest_host_mask(vmx);
if (vmx_xsaves_supported())
vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
if (enable_pml) {
ASSERT(vmx->pml_pg);
vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
}
return 0;
}
static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct msr_data apic_base_msr;
u64 cr0;
vmx->rmode.vm86_active = 0;
vmx->soft_vnmi_blocked = 0;
vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
kvm_set_cr8(vcpu, 0);
if (!init_event) {
apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
MSR_IA32_APICBASE_ENABLE;
if (kvm_vcpu_is_reset_bsp(vcpu))
apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
apic_base_msr.host_initiated = true;
kvm_set_apic_base(vcpu, &apic_base_msr);
}
vmx_segment_cache_clear(vmx);
seg_setup(VCPU_SREG_CS);
vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
seg_setup(VCPU_SREG_DS);
seg_setup(VCPU_SREG_ES);
seg_setup(VCPU_SREG_FS);
seg_setup(VCPU_SREG_GS);
seg_setup(VCPU_SREG_SS);
vmcs_write16(GUEST_TR_SELECTOR, 0);
vmcs_writel(GUEST_TR_BASE, 0);
vmcs_write32(GUEST_TR_LIMIT, 0xffff);
vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
vmcs_write16(GUEST_LDTR_SELECTOR, 0);
vmcs_writel(GUEST_LDTR_BASE, 0);
vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
if (!init_event) {
vmcs_write32(GUEST_SYSENTER_CS, 0);
vmcs_writel(GUEST_SYSENTER_ESP, 0);
vmcs_writel(GUEST_SYSENTER_EIP, 0);
vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
}
vmcs_writel(GUEST_RFLAGS, 0x02);
kvm_rip_write(vcpu, 0xfff0);
vmcs_writel(GUEST_GDTR_BASE, 0);
vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
vmcs_writel(GUEST_IDTR_BASE, 0);
vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
setup_msrs(vmx);
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
if (cpu_has_vmx_tpr_shadow() && !init_event) {
vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
if (cpu_need_tpr_shadow(vcpu))
vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
__pa(vcpu->arch.apic->regs));
vmcs_write32(TPR_THRESHOLD, 0);
}
kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
if (kvm_vcpu_apicv_active(vcpu))
memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
if (vmx->vpid != 0)
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
vmx->vcpu.arch.cr0 = cr0;
vmx_set_cr0(vcpu, cr0); /* enter rmode */
vmx_set_cr4(vcpu, 0);
vmx_set_efer(vcpu, 0);
vmx_fpu_activate(vcpu);
update_exception_bitmap(vcpu);
vpid_sync_context(vmx->vpid);
}
/*
* In nested virtualization, check if L1 asked to exit on external interrupts.
* For most existing hypervisors, this will always return true.
*/
static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
{
return get_vmcs12(vcpu)->pin_based_vm_exec_control &
PIN_BASED_EXT_INTR_MASK;
}
/*
* In nested virtualization, check if L1 has set
* VM_EXIT_ACK_INTR_ON_EXIT
*/
static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
{
return get_vmcs12(vcpu)->vm_exit_controls &
VM_EXIT_ACK_INTR_ON_EXIT;
}
static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
{
return get_vmcs12(vcpu)->pin_based_vm_exec_control &
PIN_BASED_NMI_EXITING;
}
static void enable_irq_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
}
static void enable_nmi_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
if (!cpu_has_virtual_nmis() ||
vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
enable_irq_window(vcpu);
return;
}
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
}
static void vmx_inject_irq(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
uint32_t intr;
int irq = vcpu->arch.interrupt.nr;
trace_kvm_inj_virq(irq);
++vcpu->stat.irq_injections;
if (vmx->rmode.vm86_active) {
int inc_eip = 0;
if (vcpu->arch.interrupt.soft)
inc_eip = vcpu->arch.event_exit_inst_len;
if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
intr = irq | INTR_INFO_VALID_MASK;
if (vcpu->arch.interrupt.soft) {
intr |= INTR_TYPE_SOFT_INTR;
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmx->vcpu.arch.event_exit_inst_len);
} else
intr |= INTR_TYPE_EXT_INTR;
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
}
static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!is_guest_mode(vcpu)) {
if (!cpu_has_virtual_nmis()) {
/*
* Tracking the NMI-blocked state in software is built upon
* finding the next open IRQ window. This, in turn, depends on
* well-behaving guests: They have to keep IRQs disabled at
* least as long as the NMI handler runs. Otherwise we may
* cause NMI nesting, maybe breaking the guest. But as this is
* highly unlikely, we can live with the residual risk.
*/
vmx->soft_vnmi_blocked = 1;
vmx->vnmi_blocked_time = 0;
}
++vcpu->stat.nmi_injections;
vmx->nmi_known_unmasked = false;
}
if (vmx->rmode.vm86_active) {
if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
}
static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
{
if (!cpu_has_virtual_nmis())
return to_vmx(vcpu)->soft_vnmi_blocked;
if (to_vmx(vcpu)->nmi_known_unmasked)
return false;
return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
}
static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!cpu_has_virtual_nmis()) {
if (vmx->soft_vnmi_blocked != masked) {
vmx->soft_vnmi_blocked = masked;
vmx->vnmi_blocked_time = 0;
}
} else {
vmx->nmi_known_unmasked = !masked;
if (masked)
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
else
vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
}
}
static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
{
if (to_vmx(vcpu)->nested.nested_run_pending)
return 0;
if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
return 0;
return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
(GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
| GUEST_INTR_STATE_NMI));
}
static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
{
return (!to_vmx(vcpu)->nested.nested_run_pending &&
vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
}
static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
{
int ret;
ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
PAGE_SIZE * 3);
if (ret)
return ret;
kvm->arch.tss_addr = addr;
return init_rmode_tss(kvm);
}
static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
{
switch (vec) {
case BP_VECTOR:
/*
* Update instruction length as we may reinject the exception
* from user space while in guest debugging mode.
*/
to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
return false;
/* fall through */
case DB_VECTOR:
if (vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
return false;
/* fall through */
case DE_VECTOR:
case OF_VECTOR:
case BR_VECTOR:
case UD_VECTOR:
case DF_VECTOR:
case SS_VECTOR:
case GP_VECTOR:
case MF_VECTOR:
return true;
break;
}
return false;
}
static int handle_rmode_exception(struct kvm_vcpu *vcpu,
int vec, u32 err_code)
{
/*
* Instruction with address size override prefix opcode 0x67
* Cause the #SS fault with 0 error code in VM86 mode.
*/
if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
if (vcpu->arch.halt_request) {
vcpu->arch.halt_request = 0;
return kvm_vcpu_halt(vcpu);
}
return 1;
}
return 0;
}
/*
* Forward all other exceptions that are valid in real mode.
* FIXME: Breaks guest debugging in real mode, needs to be fixed with
* the required debugging infrastructure rework.
*/
kvm_queue_exception(vcpu, vec);
return 1;
}
/*
* Trigger machine check on the host. We assume all the MSRs are already set up
* by the CPU and that we still run on the same CPU as the MCE occurred on.
* We pass a fake environment to the machine check handler because we want
* the guest to be always treated like user space, no matter what context
* it used internally.
*/
static void kvm_machine_check(void)
{
#if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
struct pt_regs regs = {
.cs = 3, /* Fake ring 3 no matter what the guest ran on */
.flags = X86_EFLAGS_IF,
};
do_machine_check(®s, 0);
#endif
}
static int handle_machine_check(struct kvm_vcpu *vcpu)
{
/* already handled by vcpu_run */
return 1;
}
static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case AC_VECTOR:
kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
return 1;
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
static int handle_external_interrupt(struct kvm_vcpu *vcpu)
{
++vcpu->stat.irq_exits;
return 1;
}
static int handle_triple_fault(struct kvm_vcpu *vcpu)
{
vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
return 0;
}
static int handle_io(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
int size, in, string, ret;
unsigned port;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
string = (exit_qualification & 16) != 0;
in = (exit_qualification & 8) != 0;
++vcpu->stat.io_exits;
if (string || in)
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
port = exit_qualification >> 16;
size = (exit_qualification & 7) + 1;
ret = kvm_skip_emulated_instruction(vcpu);
/*
* TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
* KVM_EXIT_DEBUG here.
*/
return kvm_fast_pio_out(vcpu, size, port) && ret;
}
static void
vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
{
/*
* Patch in the VMCALL instruction:
*/
hypercall[0] = 0x0f;
hypercall[1] = 0x01;
hypercall[2] = 0xc1;
}
/* called to set cr0 as appropriate for a mov-to-cr0 exit. */
static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
{
if (is_guest_mode(vcpu)) {
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
unsigned long orig_val = val;
/*
* We get here when L2 changed cr0 in a way that did not change
* any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
* but did change L0 shadowed bits. So we first calculate the
* effective cr0 value that L1 would like to write into the
* hardware. It consists of the L2-owned bits from the new
* value combined with the L1-owned bits from L1's guest_cr0.
*/
val = (val & ~vmcs12->cr0_guest_host_mask) |
(vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
if (!nested_guest_cr0_valid(vcpu, val))
return 1;
if (kvm_set_cr0(vcpu, val))
return 1;
vmcs_writel(CR0_READ_SHADOW, orig_val);
return 0;
} else {
if (to_vmx(vcpu)->nested.vmxon &&
!nested_host_cr0_valid(vcpu, val))
return 1;
return kvm_set_cr0(vcpu, val);
}
}
static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
{
if (is_guest_mode(vcpu)) {
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
unsigned long orig_val = val;
/* analogously to handle_set_cr0 */
val = (val & ~vmcs12->cr4_guest_host_mask) |
(vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
if (kvm_set_cr4(vcpu, val))
return 1;
vmcs_writel(CR4_READ_SHADOW, orig_val);
return 0;
} else
return kvm_set_cr4(vcpu, val);
}
/* called to set cr0 as appropriate for clts instruction exit. */
static void handle_clts(struct kvm_vcpu *vcpu)
{
if (is_guest_mode(vcpu)) {
/*
* We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
* but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
* just pretend it's off (also in arch.cr0 for fpu_activate).
*/
vmcs_writel(CR0_READ_SHADOW,
vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
vcpu->arch.cr0 &= ~X86_CR0_TS;
} else
vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
}
static int handle_cr(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification, val;
int cr;
int reg;
int err;
int ret;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
cr = exit_qualification & 15;
reg = (exit_qualification >> 8) & 15;
switch ((exit_qualification >> 4) & 3) {
case 0: /* mov to cr */
val = kvm_register_readl(vcpu, reg);
trace_kvm_cr_write(cr, val);
switch (cr) {
case 0:
err = handle_set_cr0(vcpu, val);
return kvm_complete_insn_gp(vcpu, err);
case 3:
err = kvm_set_cr3(vcpu, val);
return kvm_complete_insn_gp(vcpu, err);
case 4:
err = handle_set_cr4(vcpu, val);
return kvm_complete_insn_gp(vcpu, err);
case 8: {
u8 cr8_prev = kvm_get_cr8(vcpu);
u8 cr8 = (u8)val;
err = kvm_set_cr8(vcpu, cr8);
ret = kvm_complete_insn_gp(vcpu, err);
if (lapic_in_kernel(vcpu))
return ret;
if (cr8_prev <= cr8)
return ret;
/*
* TODO: we might be squashing a
* KVM_GUESTDBG_SINGLESTEP-triggered
* KVM_EXIT_DEBUG here.
*/
vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
return 0;
}
}
break;
case 2: /* clts */
handle_clts(vcpu);
trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
vmx_fpu_activate(vcpu);
return kvm_skip_emulated_instruction(vcpu);
case 1: /*mov from cr*/
switch (cr) {
case 3:
val = kvm_read_cr3(vcpu);
kvm_register_write(vcpu, reg, val);
trace_kvm_cr_read(cr, val);
return kvm_skip_emulated_instruction(vcpu);
case 8:
val = kvm_get_cr8(vcpu);
kvm_register_write(vcpu, reg, val);
trace_kvm_cr_read(cr, val);
return kvm_skip_emulated_instruction(vcpu);
}
break;
case 3: /* lmsw */
val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
kvm_lmsw(vcpu, val);
return kvm_skip_emulated_instruction(vcpu);
default:
break;
}
vcpu->run->exit_reason = 0;
vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
(int)(exit_qualification >> 4) & 3, cr);
return 0;
}
static int handle_dr(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
int dr, dr7, reg;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
/* First, if DR does not exist, trigger UD */
if (!kvm_require_dr(vcpu, dr))
return 1;
/* Do not handle if the CPL > 0, will trigger GP on re-entry */
if (!kvm_require_cpl(vcpu, 0))
return 1;
dr7 = vmcs_readl(GUEST_DR7);
if (dr7 & DR7_GD) {
/*
* As the vm-exit takes precedence over the debug trap, we
* need to emulate the latter, either for the host or the
* guest debugging itself.
*/
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
vcpu->run->debug.arch.dr7 = dr7;
vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
vcpu->run->debug.arch.exception = DB_VECTOR;
vcpu->run->exit_reason = KVM_EXIT_DEBUG;
return 0;
} else {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
}
if (vcpu->guest_debug == 0) {
vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
CPU_BASED_MOV_DR_EXITING);
/*
* No more DR vmexits; force a reload of the debug registers
* and reenter on this instruction. The next vmexit will
* retrieve the full state of the debug registers.
*/
vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
return 1;
}
reg = DEBUG_REG_ACCESS_REG(exit_qualification);
if (exit_qualification & TYPE_MOV_FROM_DR) {
unsigned long val;
if (kvm_get_dr(vcpu, dr, &val))
return 1;
kvm_register_write(vcpu, reg, val);
} else
if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
return 1;
return kvm_skip_emulated_instruction(vcpu);
}
static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
{
return vcpu->arch.dr6;
}
static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
{
}
static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
{
get_debugreg(vcpu->arch.db[0], 0);
get_debugreg(vcpu->arch.db[1], 1);
get_debugreg(vcpu->arch.db[2], 2);
get_debugreg(vcpu->arch.db[3], 3);
get_debugreg(vcpu->arch.dr6, 6);
vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
}
static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
{
vmcs_writel(GUEST_DR7, val);
}
static int handle_cpuid(struct kvm_vcpu *vcpu)
{
return kvm_emulate_cpuid(vcpu);
}
static int handle_rdmsr(struct kvm_vcpu *vcpu)
{
u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
struct msr_data msr_info;
msr_info.index = ecx;
msr_info.host_initiated = false;
if (vmx_get_msr(vcpu, &msr_info)) {
trace_kvm_msr_read_ex(ecx);
kvm_inject_gp(vcpu, 0);
return 1;
}
trace_kvm_msr_read(ecx, msr_info.data);
/* FIXME: handling of bits 32:63 of rax, rdx */
vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_wrmsr(struct kvm_vcpu *vcpu)
{
struct msr_data msr;
u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
msr.data = data;
msr.index = ecx;
msr.host_initiated = false;
if (kvm_set_msr(vcpu, &msr) != 0) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(vcpu, 0);
return 1;
}
trace_kvm_msr_write(ecx, data);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
{
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 1;
}
static int handle_interrupt_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
/* clear pending irq */
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
kvm_make_request(KVM_REQ_EVENT, vcpu);
++vcpu->stat.irq_window_exits;
return 1;
}
static int handle_halt(struct kvm_vcpu *vcpu)
{
return kvm_emulate_halt(vcpu);
}
static int handle_vmcall(struct kvm_vcpu *vcpu)
{
return kvm_emulate_hypercall(vcpu);
}
static int handle_invd(struct kvm_vcpu *vcpu)
{
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
}
static int handle_invlpg(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
kvm_mmu_invlpg(vcpu, exit_qualification);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_rdpmc(struct kvm_vcpu *vcpu)
{
int err;
err = kvm_rdpmc(vcpu);
return kvm_complete_insn_gp(vcpu, err);
}
static int handle_wbinvd(struct kvm_vcpu *vcpu)
{
return kvm_emulate_wbinvd(vcpu);
}
static int handle_xsetbv(struct kvm_vcpu *vcpu)
{
u64 new_bv = kvm_read_edx_eax(vcpu);
u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
if (kvm_set_xcr(vcpu, index, new_bv) == 0)
return kvm_skip_emulated_instruction(vcpu);
return 1;
}
static int handle_xsaves(struct kvm_vcpu *vcpu)
{
kvm_skip_emulated_instruction(vcpu);
WARN(1, "this should never happen\n");
return 1;
}
static int handle_xrstors(struct kvm_vcpu *vcpu)
{
kvm_skip_emulated_instruction(vcpu);
WARN(1, "this should never happen\n");
return 1;
}
static int handle_apic_access(struct kvm_vcpu *vcpu)
{
if (likely(fasteoi)) {
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
int access_type, offset;
access_type = exit_qualification & APIC_ACCESS_TYPE;
offset = exit_qualification & APIC_ACCESS_OFFSET;
/*
* Sane guest uses MOV to write EOI, with written value
* not cared. So make a short-circuit here by avoiding
* heavy instruction emulation.
*/
if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
(offset == APIC_EOI)) {
kvm_lapic_set_eoi(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
}
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
}
static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
int vector = exit_qualification & 0xff;
/* EOI-induced VM exit is trap-like and thus no need to adjust IP */
kvm_apic_set_eoi_accelerated(vcpu, vector);
return 1;
}
static int handle_apic_write(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 offset = exit_qualification & 0xfff;
/* APIC-write VM exit is trap-like and thus no need to adjust IP */
kvm_apic_write_nodecode(vcpu, offset);
return 1;
}
static int handle_task_switch(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long exit_qualification;
bool has_error_code = false;
u32 error_code = 0;
u16 tss_selector;
int reason, type, idt_v, idt_index;
idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
reason = (u32)exit_qualification >> 30;
if (reason == TASK_SWITCH_GATE && idt_v) {
switch (type) {
case INTR_TYPE_NMI_INTR:
vcpu->arch.nmi_injected = false;
vmx_set_nmi_mask(vcpu, true);
break;
case INTR_TYPE_EXT_INTR:
case INTR_TYPE_SOFT_INTR:
kvm_clear_interrupt_queue(vcpu);
break;
case INTR_TYPE_HARD_EXCEPTION:
if (vmx->idt_vectoring_info &
VECTORING_INFO_DELIVER_CODE_MASK) {
has_error_code = true;
error_code =
vmcs_read32(IDT_VECTORING_ERROR_CODE);
}
/* fall through */
case INTR_TYPE_SOFT_EXCEPTION:
kvm_clear_exception_queue(vcpu);
break;
default:
break;
}
}
tss_selector = exit_qualification;
if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
type != INTR_TYPE_EXT_INTR &&
type != INTR_TYPE_NMI_INTR))
skip_emulated_instruction(vcpu);
if (kvm_task_switch(vcpu, tss_selector,
type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
has_error_code, error_code) == EMULATE_FAIL) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
return 0;
}
/*
* TODO: What about debug traps on tss switch?
* Are we supposed to inject them and update dr6?
*/
return 1;
}
static int handle_ept_violation(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
gpa_t gpa;
u32 error_code;
int gla_validity;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
gla_validity = (exit_qualification >> 7) & 0x3;
if (gla_validity == 0x2) {
printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
(long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
vmcs_readl(GUEST_LINEAR_ADDRESS));
printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
(long unsigned int)exit_qualification);
vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
return 0;
}
/*
* EPT violation happened while executing iret from NMI,
* "blocked by NMI" bit has to be set before next VM entry.
* There are errata that may cause this bit to not be set:
* AAK134, BY25.
*/
if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
cpu_has_virtual_nmis() &&
(exit_qualification & INTR_INFO_UNBLOCK_NMI))
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
trace_kvm_page_fault(gpa, exit_qualification);
/* it is a read fault? */
error_code = (exit_qualification << 2) & PFERR_USER_MASK;
/* it is a write fault? */
error_code |= exit_qualification & PFERR_WRITE_MASK;
/* It is a fetch fault? */
error_code |= (exit_qualification << 2) & PFERR_FETCH_MASK;
/* ept page table is present? */
error_code |= (exit_qualification & 0x38) != 0;
vcpu->arch.exit_qualification = exit_qualification;
return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
}
static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
{
int ret;
gpa_t gpa;
gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
if (!kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
trace_kvm_fast_mmio(gpa);
return kvm_skip_emulated_instruction(vcpu);
}
ret = handle_mmio_page_fault(vcpu, gpa, true);
if (likely(ret == RET_MMIO_PF_EMULATE))
return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
EMULATE_DONE;
if (unlikely(ret == RET_MMIO_PF_INVALID))
return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0);
if (unlikely(ret == RET_MMIO_PF_RETRY))
return 1;
/* It is the real ept misconfig */
WARN_ON(1);
vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
return 0;
}
static int handle_nmi_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
/* clear pending NMI */
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
++vcpu->stat.nmi_window_exits;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 1;
}
static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
enum emulation_result err = EMULATE_DONE;
int ret = 1;
u32 cpu_exec_ctrl;
bool intr_window_requested;
unsigned count = 130;
cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
while (vmx->emulation_required && count-- != 0) {
if (intr_window_requested && vmx_interrupt_allowed(vcpu))
return handle_interrupt_window(&vmx->vcpu);
if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
return 1;
err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE);
if (err == EMULATE_USER_EXIT) {
++vcpu->stat.mmio_exits;
ret = 0;
goto out;
}
if (err != EMULATE_DONE) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
return 0;
}
if (vcpu->arch.halt_request) {
vcpu->arch.halt_request = 0;
ret = kvm_vcpu_halt(vcpu);
goto out;
}
if (signal_pending(current))
goto out;
if (need_resched())
schedule();
}
out:
return ret;
}
static int __grow_ple_window(int val)
{
if (ple_window_grow < 1)
return ple_window;
val = min(val, ple_window_actual_max);
if (ple_window_grow < ple_window)
val *= ple_window_grow;
else
val += ple_window_grow;
return val;
}
static int __shrink_ple_window(int val, int modifier, int minimum)
{
if (modifier < 1)
return ple_window;
if (modifier < ple_window)
val /= modifier;
else
val -= modifier;
return max(val, minimum);
}
static void grow_ple_window(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int old = vmx->ple_window;
vmx->ple_window = __grow_ple_window(old);
if (vmx->ple_window != old)
vmx->ple_window_dirty = true;
trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
}
static void shrink_ple_window(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int old = vmx->ple_window;
vmx->ple_window = __shrink_ple_window(old,
ple_window_shrink, ple_window);
if (vmx->ple_window != old)
vmx->ple_window_dirty = true;
trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
}
/*
* ple_window_actual_max is computed to be one grow_ple_window() below
* ple_window_max. (See __grow_ple_window for the reason.)
* This prevents overflows, because ple_window_max is int.
* ple_window_max effectively rounded down to a multiple of ple_window_grow in
* this process.
* ple_window_max is also prevented from setting vmx->ple_window < ple_window.
*/
static void update_ple_window_actual_max(void)
{
ple_window_actual_max =
__shrink_ple_window(max(ple_window_max, ple_window),
ple_window_grow, INT_MIN);
}
/*
* Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
*/
static void wakeup_handler(void)
{
struct kvm_vcpu *vcpu;
int cpu = smp_processor_id();
spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
blocked_vcpu_list) {
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
if (pi_test_on(pi_desc) == 1)
kvm_vcpu_kick(vcpu);
}
spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
}
static __init int hardware_setup(void)
{
int r = -ENOMEM, i, msr;
rdmsrl_safe(MSR_EFER, &host_efer);
for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
kvm_define_shared_msr(i, vmx_msr_index[i]);
for (i = 0; i < VMX_BITMAP_NR; i++) {
vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_bitmap[i])
goto out;
}
vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
/*
* Allow direct access to the PC debug port (it is often used for I/O
* delays, but the vmexits simply slow things down).
*/
memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
clear_bit(0x80, vmx_io_bitmap_a);
memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
if (setup_vmcs_config(&vmcs_config) < 0) {
r = -EIO;
goto out;
}
if (boot_cpu_has(X86_FEATURE_NX))
kvm_enable_efer_bits(EFER_NX);
if (!cpu_has_vmx_vpid())
enable_vpid = 0;
if (!cpu_has_vmx_shadow_vmcs())
enable_shadow_vmcs = 0;
if (enable_shadow_vmcs)
init_vmcs_shadow_fields();
if (!cpu_has_vmx_ept() ||
!cpu_has_vmx_ept_4levels()) {
enable_ept = 0;
enable_unrestricted_guest = 0;
enable_ept_ad_bits = 0;
}
if (!cpu_has_vmx_ept_ad_bits())
enable_ept_ad_bits = 0;
if (!cpu_has_vmx_unrestricted_guest())
enable_unrestricted_guest = 0;
if (!cpu_has_vmx_flexpriority())
flexpriority_enabled = 0;
/*
* set_apic_access_page_addr() is used to reload apic access
* page upon invalidation. No need to do anything if not
* using the APIC_ACCESS_ADDR VMCS field.
*/
if (!flexpriority_enabled)
kvm_x86_ops->set_apic_access_page_addr = NULL;
if (!cpu_has_vmx_tpr_shadow())
kvm_x86_ops->update_cr8_intercept = NULL;
if (enable_ept && !cpu_has_vmx_ept_2m_page())
kvm_disable_largepages();
if (!cpu_has_vmx_ple())
ple_gap = 0;
if (!cpu_has_vmx_apicv())
enable_apicv = 0;
if (cpu_has_vmx_tsc_scaling()) {
kvm_has_tsc_control = true;
kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
kvm_tsc_scaling_ratio_frac_bits = 48;
}
vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
vmx_disable_intercept_for_msr(MSR_IA32_BNDCFGS, true);
memcpy(vmx_msr_bitmap_legacy_x2apic_apicv,
vmx_msr_bitmap_legacy, PAGE_SIZE);
memcpy(vmx_msr_bitmap_longmode_x2apic_apicv,
vmx_msr_bitmap_longmode, PAGE_SIZE);
memcpy(vmx_msr_bitmap_legacy_x2apic,
vmx_msr_bitmap_legacy, PAGE_SIZE);
memcpy(vmx_msr_bitmap_longmode_x2apic,
vmx_msr_bitmap_longmode, PAGE_SIZE);
set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
for (msr = 0x800; msr <= 0x8ff; msr++) {
if (msr == 0x839 /* TMCCT */)
continue;
vmx_disable_intercept_msr_x2apic(msr, MSR_TYPE_R, true);
}
/*
* TPR reads and writes can be virtualized even if virtual interrupt
* delivery is not in use.
*/
vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_W, true);
vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_R | MSR_TYPE_W, false);
/* EOI */
vmx_disable_intercept_msr_x2apic(0x80b, MSR_TYPE_W, true);
/* SELF-IPI */
vmx_disable_intercept_msr_x2apic(0x83f, MSR_TYPE_W, true);
if (enable_ept) {
kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
(enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
(enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
0ull, VMX_EPT_EXECUTABLE_MASK,
cpu_has_vmx_ept_execute_only() ?
0ull : VMX_EPT_READABLE_MASK);
ept_set_mmio_spte_mask();
kvm_enable_tdp();
} else
kvm_disable_tdp();
update_ple_window_actual_max();
/*
* Only enable PML when hardware supports PML feature, and both EPT
* and EPT A/D bit features are enabled -- PML depends on them to work.
*/
if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
enable_pml = 0;
if (!enable_pml) {
kvm_x86_ops->slot_enable_log_dirty = NULL;
kvm_x86_ops->slot_disable_log_dirty = NULL;
kvm_x86_ops->flush_log_dirty = NULL;
kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
}
if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
u64 vmx_msr;
rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
cpu_preemption_timer_multi =
vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
} else {
kvm_x86_ops->set_hv_timer = NULL;
kvm_x86_ops->cancel_hv_timer = NULL;
}
kvm_set_posted_intr_wakeup_handler(wakeup_handler);
kvm_mce_cap_supported |= MCG_LMCE_P;
return alloc_kvm_area();
out:
for (i = 0; i < VMX_BITMAP_NR; i++)
free_page((unsigned long)vmx_bitmap[i]);
return r;
}
static __exit void hardware_unsetup(void)
{
int i;
for (i = 0; i < VMX_BITMAP_NR; i++)
free_page((unsigned long)vmx_bitmap[i]);
free_kvm_area();
}
/*
* Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
* exiting, so only get here on cpu with PAUSE-Loop-Exiting.
*/
static int handle_pause(struct kvm_vcpu *vcpu)
{
if (ple_gap)
grow_ple_window(vcpu);
kvm_vcpu_on_spin(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_nop(struct kvm_vcpu *vcpu)
{
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_mwait(struct kvm_vcpu *vcpu)
{
printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
return handle_nop(vcpu);
}
static int handle_monitor_trap(struct kvm_vcpu *vcpu)
{
return 1;
}
static int handle_monitor(struct kvm_vcpu *vcpu)
{
printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
return handle_nop(vcpu);
}
/*
* To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
* We could reuse a single VMCS for all the L2 guests, but we also want the
* option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
* allows keeping them loaded on the processor, and in the future will allow
* optimizations where prepare_vmcs02 doesn't need to set all the fields on
* every entry if they never change.
* So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
* (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
*
* The following functions allocate and free a vmcs02 in this pool.
*/
/* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
{
struct vmcs02_list *item;
list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
if (item->vmptr == vmx->nested.current_vmptr) {
list_move(&item->list, &vmx->nested.vmcs02_pool);
return &item->vmcs02;
}
if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
/* Recycle the least recently used VMCS. */
item = list_last_entry(&vmx->nested.vmcs02_pool,
struct vmcs02_list, list);
item->vmptr = vmx->nested.current_vmptr;
list_move(&item->list, &vmx->nested.vmcs02_pool);
return &item->vmcs02;
}
/* Create a new VMCS */
item = kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
if (!item)
return NULL;
item->vmcs02.vmcs = alloc_vmcs();
item->vmcs02.shadow_vmcs = NULL;
if (!item->vmcs02.vmcs) {
kfree(item);
return NULL;
}
loaded_vmcs_init(&item->vmcs02);
item->vmptr = vmx->nested.current_vmptr;
list_add(&(item->list), &(vmx->nested.vmcs02_pool));
vmx->nested.vmcs02_num++;
return &item->vmcs02;
}
/* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
{
struct vmcs02_list *item;
list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
if (item->vmptr == vmptr) {
free_loaded_vmcs(&item->vmcs02);
list_del(&item->list);
kfree(item);
vmx->nested.vmcs02_num--;
return;
}
}
/*
* Free all VMCSs saved for this vcpu, except the one pointed by
* vmx->loaded_vmcs. We must be running L1, so vmx->loaded_vmcs
* must be &vmx->vmcs01.
*/
static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
{
struct vmcs02_list *item, *n;
WARN_ON(vmx->loaded_vmcs != &vmx->vmcs01);
list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
/*
* Something will leak if the above WARN triggers. Better than
* a use-after-free.
*/
if (vmx->loaded_vmcs == &item->vmcs02)
continue;
free_loaded_vmcs(&item->vmcs02);
list_del(&item->list);
kfree(item);
vmx->nested.vmcs02_num--;
}
}
/*
* The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
* set the success or error code of an emulated VMX instruction, as specified
* by Vol 2B, VMX Instruction Reference, "Conventions".
*/
static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
{
vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
}
static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
{
vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
& ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
X86_EFLAGS_SF | X86_EFLAGS_OF))
| X86_EFLAGS_CF);
}
static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
u32 vm_instruction_error)
{
if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
/*
* failValid writes the error number to the current VMCS, which
* can't be done there isn't a current VMCS.
*/
nested_vmx_failInvalid(vcpu);
return;
}
vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_SF | X86_EFLAGS_OF))
| X86_EFLAGS_ZF);
get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
/*
* We don't need to force a shadow sync because
* VM_INSTRUCTION_ERROR is not shadowed
*/
}
static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
{
/* TODO: not to reset guest simply here. */
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
}
static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
{
struct vcpu_vmx *vmx =
container_of(timer, struct vcpu_vmx, nested.preemption_timer);
vmx->nested.preemption_timer_expired = true;
kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
kvm_vcpu_kick(&vmx->vcpu);
return HRTIMER_NORESTART;
}
/*
* Decode the memory-address operand of a vmx instruction, as recorded on an
* exit caused by such an instruction (run by a guest hypervisor).
* On success, returns 0. When the operand is invalid, returns 1 and throws
* #UD or #GP.
*/
static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
unsigned long exit_qualification,
u32 vmx_instruction_info, bool wr, gva_t *ret)
{
gva_t off;
bool exn;
struct kvm_segment s;
/*
* According to Vol. 3B, "Information for VM Exits Due to Instruction
* Execution", on an exit, vmx_instruction_info holds most of the
* addressing components of the operand. Only the displacement part
* is put in exit_qualification (see 3B, "Basic VM-Exit Information").
* For how an actual address is calculated from all these components,
* refer to Vol. 1, "Operand Addressing".
*/
int scaling = vmx_instruction_info & 3;
int addr_size = (vmx_instruction_info >> 7) & 7;
bool is_reg = vmx_instruction_info & (1u << 10);
int seg_reg = (vmx_instruction_info >> 15) & 7;
int index_reg = (vmx_instruction_info >> 18) & 0xf;
bool index_is_valid = !(vmx_instruction_info & (1u << 22));
int base_reg = (vmx_instruction_info >> 23) & 0xf;
bool base_is_valid = !(vmx_instruction_info & (1u << 27));
if (is_reg) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
/* Addr = segment_base + offset */
/* offset = base + [index * scale] + displacement */
off = exit_qualification; /* holds the displacement */
if (base_is_valid)
off += kvm_register_read(vcpu, base_reg);
if (index_is_valid)
off += kvm_register_read(vcpu, index_reg)<<scaling;
vmx_get_segment(vcpu, &s, seg_reg);
*ret = s.base + off;
if (addr_size == 1) /* 32 bit */
*ret &= 0xffffffff;
/* Checks for #GP/#SS exceptions. */
exn = false;
if (is_long_mode(vcpu)) {
/* Long mode: #GP(0)/#SS(0) if the memory address is in a
* non-canonical form. This is the only check on the memory
* destination for long mode!
*/
exn = is_noncanonical_address(*ret);
} else if (is_protmode(vcpu)) {
/* Protected mode: apply checks for segment validity in the
* following order:
* - segment type check (#GP(0) may be thrown)
* - usability check (#GP(0)/#SS(0))
* - limit check (#GP(0)/#SS(0))
*/
if (wr)
/* #GP(0) if the destination operand is located in a
* read-only data segment or any code segment.
*/
exn = ((s.type & 0xa) == 0 || (s.type & 8));
else
/* #GP(0) if the source operand is located in an
* execute-only code segment
*/
exn = ((s.type & 0xa) == 8);
if (exn) {
kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
return 1;
}
/* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
*/
exn = (s.unusable != 0);
/* Protected mode: #GP(0)/#SS(0) if the memory
* operand is outside the segment limit.
*/
exn = exn || (off + sizeof(u64) > s.limit);
}
if (exn) {
kvm_queue_exception_e(vcpu,
seg_reg == VCPU_SREG_SS ?
SS_VECTOR : GP_VECTOR,
0);
return 1;
}
return 0;
}
/*
* This function performs the various checks including
* - if it's 4KB aligned
* - No bits beyond the physical address width are set
* - Returns 0 on success or else 1
* (Intel SDM Section 30.3)
*/
static int nested_vmx_check_vmptr(struct kvm_vcpu *vcpu, int exit_reason,
gpa_t *vmpointer)
{
gva_t gva;
gpa_t vmptr;
struct x86_exception e;
struct page *page;
struct vcpu_vmx *vmx = to_vmx(vcpu);
int maxphyaddr = cpuid_maxphyaddr(vcpu);
if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
sizeof(vmptr), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
switch (exit_reason) {
case EXIT_REASON_VMON:
/*
* SDM 3: 24.11.5
* The first 4 bytes of VMXON region contain the supported
* VMCS revision identifier
*
* Note - IA32_VMX_BASIC[48] will never be 1
* for the nested case;
* which replaces physical address width with 32
*
*/
if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
nested_vmx_failInvalid(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
page = nested_get_page(vcpu, vmptr);
if (page == NULL ||
*(u32 *)kmap(page) != VMCS12_REVISION) {
nested_vmx_failInvalid(vcpu);
kunmap(page);
return kvm_skip_emulated_instruction(vcpu);
}
kunmap(page);
vmx->nested.vmxon_ptr = vmptr;
break;
case EXIT_REASON_VMCLEAR:
if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
nested_vmx_failValid(vcpu,
VMXERR_VMCLEAR_INVALID_ADDRESS);
return kvm_skip_emulated_instruction(vcpu);
}
if (vmptr == vmx->nested.vmxon_ptr) {
nested_vmx_failValid(vcpu,
VMXERR_VMCLEAR_VMXON_POINTER);
return kvm_skip_emulated_instruction(vcpu);
}
break;
case EXIT_REASON_VMPTRLD:
if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
nested_vmx_failValid(vcpu,
VMXERR_VMPTRLD_INVALID_ADDRESS);
return kvm_skip_emulated_instruction(vcpu);
}
if (vmptr == vmx->nested.vmxon_ptr) {
nested_vmx_failValid(vcpu,
VMXERR_VMPTRLD_VMXON_POINTER);
return kvm_skip_emulated_instruction(vcpu);
}
break;
default:
return 1; /* shouldn't happen */
}
if (vmpointer)
*vmpointer = vmptr;
return 0;
}
/*
* Emulate the VMXON instruction.
* Currently, we just remember that VMX is active, and do not save or even
* inspect the argument to VMXON (the so-called "VMXON pointer") because we
* do not currently need to store anything in that guest-allocated memory
* region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
* argument is different from the VMXON pointer (which the spec says they do).
*/
static int handle_vmon(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs;
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs *shadow_vmcs;
const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
| FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
/* The Intel VMX Instruction Reference lists a bunch of bits that
* are prerequisite to running VMXON, most notably cr4.VMXE must be
* set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
* Otherwise, we should fail with #UD. We test these now:
*/
if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
!kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
(vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
if (is_long_mode(vcpu) && !cs.l) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
if (vmx_get_cpl(vcpu)) {
kvm_inject_gp(vcpu, 0);
return 1;
}
if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMON, NULL))
return 1;
if (vmx->nested.vmxon) {
nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
return kvm_skip_emulated_instruction(vcpu);
}
if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
!= VMXON_NEEDED_FEATURES) {
kvm_inject_gp(vcpu, 0);
return 1;
}
if (cpu_has_vmx_msr_bitmap()) {
vmx->nested.msr_bitmap =
(unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx->nested.msr_bitmap)
goto out_msr_bitmap;
}
vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
if (!vmx->nested.cached_vmcs12)
goto out_cached_vmcs12;
if (enable_shadow_vmcs) {
shadow_vmcs = alloc_vmcs();
if (!shadow_vmcs)
goto out_shadow_vmcs;
/* mark vmcs as shadow */
shadow_vmcs->revision_id |= (1u << 31);
/* init shadow vmcs */
vmcs_clear(shadow_vmcs);
vmx->vmcs01.shadow_vmcs = shadow_vmcs;
}
INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
vmx->nested.vmcs02_num = 0;
hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
HRTIMER_MODE_REL_PINNED);
vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
vmx->nested.vmxon = true;
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
out_shadow_vmcs:
kfree(vmx->nested.cached_vmcs12);
out_cached_vmcs12:
free_page((unsigned long)vmx->nested.msr_bitmap);
out_msr_bitmap:
return -ENOMEM;
}
/*
* Intel's VMX Instruction Reference specifies a common set of prerequisites
* for running VMX instructions (except VMXON, whose prerequisites are
* slightly different). It also specifies what exception to inject otherwise.
*/
static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs;
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!vmx->nested.vmxon) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
(is_long_mode(vcpu) && !cs.l)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
if (vmx_get_cpl(vcpu)) {
kvm_inject_gp(vcpu, 0);
return 0;
}
return 1;
}
static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
{
if (vmx->nested.current_vmptr == -1ull)
return;
/* current_vmptr and current_vmcs12 are always set/reset together */
if (WARN_ON(vmx->nested.current_vmcs12 == NULL))
return;
if (enable_shadow_vmcs) {
/* copy to memory all shadowed fields in case
they were modified */
copy_shadow_to_vmcs12(vmx);
vmx->nested.sync_shadow_vmcs = false;
vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_SHADOW_VMCS);
vmcs_write64(VMCS_LINK_POINTER, -1ull);
}
vmx->nested.posted_intr_nv = -1;
/* Flush VMCS12 to guest memory */
memcpy(vmx->nested.current_vmcs12, vmx->nested.cached_vmcs12,
VMCS12_SIZE);
kunmap(vmx->nested.current_vmcs12_page);
nested_release_page(vmx->nested.current_vmcs12_page);
vmx->nested.current_vmptr = -1ull;
vmx->nested.current_vmcs12 = NULL;
}
/*
* Free whatever needs to be freed from vmx->nested when L1 goes down, or
* just stops using VMX.
*/
static void free_nested(struct vcpu_vmx *vmx)
{
if (!vmx->nested.vmxon)
return;
vmx->nested.vmxon = false;
free_vpid(vmx->nested.vpid02);
nested_release_vmcs12(vmx);
if (vmx->nested.msr_bitmap) {
free_page((unsigned long)vmx->nested.msr_bitmap);
vmx->nested.msr_bitmap = NULL;
}
if (enable_shadow_vmcs) {
vmcs_clear(vmx->vmcs01.shadow_vmcs);
free_vmcs(vmx->vmcs01.shadow_vmcs);
vmx->vmcs01.shadow_vmcs = NULL;
}
kfree(vmx->nested.cached_vmcs12);
/* Unpin physical memory we referred to in current vmcs02 */
if (vmx->nested.apic_access_page) {
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page = NULL;
}
if (vmx->nested.virtual_apic_page) {
nested_release_page(vmx->nested.virtual_apic_page);
vmx->nested.virtual_apic_page = NULL;
}
if (vmx->nested.pi_desc_page) {
kunmap(vmx->nested.pi_desc_page);
nested_release_page(vmx->nested.pi_desc_page);
vmx->nested.pi_desc_page = NULL;
vmx->nested.pi_desc = NULL;
}
nested_free_all_saved_vmcss(vmx);
}
/* Emulate the VMXOFF instruction */
static int handle_vmoff(struct kvm_vcpu *vcpu)
{
if (!nested_vmx_check_permission(vcpu))
return 1;
free_nested(to_vmx(vcpu));
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
/* Emulate the VMCLEAR instruction */
static int handle_vmclear(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
gpa_t vmptr;
struct vmcs12 *vmcs12;
struct page *page;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMCLEAR, &vmptr))
return 1;
if (vmptr == vmx->nested.current_vmptr)
nested_release_vmcs12(vmx);
page = nested_get_page(vcpu, vmptr);
if (page == NULL) {
/*
* For accurate processor emulation, VMCLEAR beyond available
* physical memory should do nothing at all. However, it is
* possible that a nested vmx bug, not a guest hypervisor bug,
* resulted in this case, so let's shut down before doing any
* more damage:
*/
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return 1;
}
vmcs12 = kmap(page);
vmcs12->launch_state = 0;
kunmap(page);
nested_release_page(page);
nested_free_vmcs02(vmx, vmptr);
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
/* Emulate the VMLAUNCH instruction */
static int handle_vmlaunch(struct kvm_vcpu *vcpu)
{
return nested_vmx_run(vcpu, true);
}
/* Emulate the VMRESUME instruction */
static int handle_vmresume(struct kvm_vcpu *vcpu)
{
return nested_vmx_run(vcpu, false);
}
enum vmcs_field_type {
VMCS_FIELD_TYPE_U16 = 0,
VMCS_FIELD_TYPE_U64 = 1,
VMCS_FIELD_TYPE_U32 = 2,
VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
};
static inline int vmcs_field_type(unsigned long field)
{
if (0x1 & field) /* the *_HIGH fields are all 32 bit */
return VMCS_FIELD_TYPE_U32;
return (field >> 13) & 0x3 ;
}
static inline int vmcs_field_readonly(unsigned long field)
{
return (((field >> 10) & 0x3) == 1);
}
/*
* Read a vmcs12 field. Since these can have varying lengths and we return
* one type, we chose the biggest type (u64) and zero-extend the return value
* to that size. Note that the caller, handle_vmread, might need to use only
* some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
* 64-bit fields are to be returned).
*/
static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
unsigned long field, u64 *ret)
{
short offset = vmcs_field_to_offset(field);
char *p;
if (offset < 0)
return offset;
p = ((char *)(get_vmcs12(vcpu))) + offset;
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
*ret = *((natural_width *)p);
return 0;
case VMCS_FIELD_TYPE_U16:
*ret = *((u16 *)p);
return 0;
case VMCS_FIELD_TYPE_U32:
*ret = *((u32 *)p);
return 0;
case VMCS_FIELD_TYPE_U64:
*ret = *((u64 *)p);
return 0;
default:
WARN_ON(1);
return -ENOENT;
}
}
static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
unsigned long field, u64 field_value){
short offset = vmcs_field_to_offset(field);
char *p = ((char *) get_vmcs12(vcpu)) + offset;
if (offset < 0)
return offset;
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_U16:
*(u16 *)p = field_value;
return 0;
case VMCS_FIELD_TYPE_U32:
*(u32 *)p = field_value;
return 0;
case VMCS_FIELD_TYPE_U64:
*(u64 *)p = field_value;
return 0;
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
*(natural_width *)p = field_value;
return 0;
default:
WARN_ON(1);
return -ENOENT;
}
}
static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
{
int i;
unsigned long field;
u64 field_value;
struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
const unsigned long *fields = shadow_read_write_fields;
const int num_fields = max_shadow_read_write_fields;
preempt_disable();
vmcs_load(shadow_vmcs);
for (i = 0; i < num_fields; i++) {
field = fields[i];
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_U16:
field_value = vmcs_read16(field);
break;
case VMCS_FIELD_TYPE_U32:
field_value = vmcs_read32(field);
break;
case VMCS_FIELD_TYPE_U64:
field_value = vmcs_read64(field);
break;
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
field_value = vmcs_readl(field);
break;
default:
WARN_ON(1);
continue;
}
vmcs12_write_any(&vmx->vcpu, field, field_value);
}
vmcs_clear(shadow_vmcs);
vmcs_load(vmx->loaded_vmcs->vmcs);
preempt_enable();
}
static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
{
const unsigned long *fields[] = {
shadow_read_write_fields,
shadow_read_only_fields
};
const int max_fields[] = {
max_shadow_read_write_fields,
max_shadow_read_only_fields
};
int i, q;
unsigned long field;
u64 field_value = 0;
struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
vmcs_load(shadow_vmcs);
for (q = 0; q < ARRAY_SIZE(fields); q++) {
for (i = 0; i < max_fields[q]; i++) {
field = fields[q][i];
vmcs12_read_any(&vmx->vcpu, field, &field_value);
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_U16:
vmcs_write16(field, (u16)field_value);
break;
case VMCS_FIELD_TYPE_U32:
vmcs_write32(field, (u32)field_value);
break;
case VMCS_FIELD_TYPE_U64:
vmcs_write64(field, (u64)field_value);
break;
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
vmcs_writel(field, (long)field_value);
break;
default:
WARN_ON(1);
break;
}
}
}
vmcs_clear(shadow_vmcs);
vmcs_load(vmx->loaded_vmcs->vmcs);
}
/*
* VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
* used before) all generate the same failure when it is missing.
*/
static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (vmx->nested.current_vmptr == -1ull) {
nested_vmx_failInvalid(vcpu);
return 0;
}
return 1;
}
static int handle_vmread(struct kvm_vcpu *vcpu)
{
unsigned long field;
u64 field_value;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t gva = 0;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
return kvm_skip_emulated_instruction(vcpu);
/* Decode instruction info and find the field to read */
field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
/* Read the field, zero-extended to a u64 field_value */
if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
/*
* Now copy part of this value to register or memory, as requested.
* Note that the number of bits actually copied is 32 or 64 depending
* on the guest's mode (32 or 64 bit), not on the given field's length.
*/
if (vmx_instruction_info & (1u << 10)) {
kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
field_value);
} else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &gva))
return 1;
/* _system ok, as nested_vmx_check_permission verified cpl=0 */
kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_vmwrite(struct kvm_vcpu *vcpu)
{
unsigned long field;
gva_t gva;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
/* The value to write might be 32 or 64 bits, depending on L1's long
* mode, and eventually we need to write that into a field of several
* possible lengths. The code below first zero-extends the value to 64
* bit (field_value), and then copies only the appropriate number of
* bits into the vmcs12 field.
*/
u64 field_value = 0;
struct x86_exception e;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
return kvm_skip_emulated_instruction(vcpu);
if (vmx_instruction_info & (1u << 10))
field_value = kvm_register_readl(vcpu,
(((vmx_instruction_info) >> 3) & 0xf));
else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, false, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
}
field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
if (vmcs_field_readonly(field)) {
nested_vmx_failValid(vcpu,
VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
if (vmcs12_write_any(vcpu, field, field_value) < 0) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
/* Emulate the VMPTRLD instruction */
static int handle_vmptrld(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
gpa_t vmptr;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMPTRLD, &vmptr))
return 1;
if (vmx->nested.current_vmptr != vmptr) {
struct vmcs12 *new_vmcs12;
struct page *page;
page = nested_get_page(vcpu, vmptr);
if (page == NULL) {
nested_vmx_failInvalid(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
new_vmcs12 = kmap(page);
if (new_vmcs12->revision_id != VMCS12_REVISION) {
kunmap(page);
nested_release_page_clean(page);
nested_vmx_failValid(vcpu,
VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
return kvm_skip_emulated_instruction(vcpu);
}
nested_release_vmcs12(vmx);
vmx->nested.current_vmptr = vmptr;
vmx->nested.current_vmcs12 = new_vmcs12;
vmx->nested.current_vmcs12_page = page;
/*
* Load VMCS12 from guest memory since it is not already
* cached.
*/
memcpy(vmx->nested.cached_vmcs12,
vmx->nested.current_vmcs12, VMCS12_SIZE);
if (enable_shadow_vmcs) {
vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_SHADOW_VMCS);
vmcs_write64(VMCS_LINK_POINTER,
__pa(vmx->vmcs01.shadow_vmcs));
vmx->nested.sync_shadow_vmcs = true;
}
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
/* Emulate the VMPTRST instruction */
static int handle_vmptrst(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t vmcs_gva;
struct x86_exception e;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &vmcs_gva))
return 1;
/* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
(void *)&to_vmx(vcpu)->nested.current_vmptr,
sizeof(u64), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
/* Emulate the INVEPT instruction */
static int handle_invept(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 vmx_instruction_info, types;
unsigned long type;
gva_t gva;
struct x86_exception e;
struct {
u64 eptp, gpa;
} operand;
if (!(vmx->nested.nested_vmx_secondary_ctls_high &
SECONDARY_EXEC_ENABLE_EPT) ||
!(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
if (type >= 32 || !(types & (1 << type))) {
nested_vmx_failValid(vcpu,
VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
return kvm_skip_emulated_instruction(vcpu);
}
/* According to the Intel VMX instruction reference, the memory
* operand is read even if it isn't needed (e.g., for type==global)
*/
if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
vmx_instruction_info, false, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
sizeof(operand), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
switch (type) {
case VMX_EPT_EXTENT_GLOBAL:
/*
* TODO: track mappings and invalidate
* single context requests appropriately
*/
case VMX_EPT_EXTENT_CONTEXT:
kvm_mmu_sync_roots(vcpu);
kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
nested_vmx_succeed(vcpu);
break;
default:
BUG_ON(1);
break;
}
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_invvpid(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 vmx_instruction_info;
unsigned long type, types;
gva_t gva;
struct x86_exception e;
int vpid;
if (!(vmx->nested.nested_vmx_secondary_ctls_high &
SECONDARY_EXEC_ENABLE_VPID) ||
!(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
if (!nested_vmx_check_permission(vcpu))
return 1;
vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
types = (vmx->nested.nested_vmx_vpid_caps &
VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
if (type >= 32 || !(types & (1 << type))) {
nested_vmx_failValid(vcpu,
VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
return kvm_skip_emulated_instruction(vcpu);
}
/* according to the intel vmx instruction reference, the memory
* operand is read even if it isn't needed (e.g., for type==global)
*/
if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
vmx_instruction_info, false, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vpid,
sizeof(u32), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
switch (type) {
case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
case VMX_VPID_EXTENT_SINGLE_CONTEXT:
case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
if (!vpid) {
nested_vmx_failValid(vcpu,
VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
return kvm_skip_emulated_instruction(vcpu);
}
break;
case VMX_VPID_EXTENT_ALL_CONTEXT:
break;
default:
WARN_ON_ONCE(1);
return kvm_skip_emulated_instruction(vcpu);
}
__vmx_flush_tlb(vcpu, vmx->nested.vpid02);
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_pml_full(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
trace_kvm_pml_full(vcpu->vcpu_id);
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
/*
* PML buffer FULL happened while executing iret from NMI,
* "blocked by NMI" bit has to be set before next VM entry.
*/
if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
cpu_has_virtual_nmis() &&
(exit_qualification & INTR_INFO_UNBLOCK_NMI))
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
/*
* PML buffer already flushed at beginning of VMEXIT. Nothing to do
* here.., and there's no userspace involvement needed for PML.
*/
return 1;
}
static int handle_preemption_timer(struct kvm_vcpu *vcpu)
{
kvm_lapic_expired_hv_timer(vcpu);
return 1;
}
/*
* The exit handlers return 1 if the exit was handled fully and guest execution
* may resume. Otherwise they set the kvm_run parameter to indicate what needs
* to be done to userspace and return 0.
*/
static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
[EXIT_REASON_EXCEPTION_NMI] = handle_exception,
[EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
[EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
[EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
[EXIT_REASON_IO_INSTRUCTION] = handle_io,
[EXIT_REASON_CR_ACCESS] = handle_cr,
[EXIT_REASON_DR_ACCESS] = handle_dr,
[EXIT_REASON_CPUID] = handle_cpuid,
[EXIT_REASON_MSR_READ] = handle_rdmsr,
[EXIT_REASON_MSR_WRITE] = handle_wrmsr,
[EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
[EXIT_REASON_HLT] = handle_halt,
[EXIT_REASON_INVD] = handle_invd,
[EXIT_REASON_INVLPG] = handle_invlpg,
[EXIT_REASON_RDPMC] = handle_rdpmc,
[EXIT_REASON_VMCALL] = handle_vmcall,
[EXIT_REASON_VMCLEAR] = handle_vmclear,
[EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
[EXIT_REASON_VMPTRLD] = handle_vmptrld,
[EXIT_REASON_VMPTRST] = handle_vmptrst,
[EXIT_REASON_VMREAD] = handle_vmread,
[EXIT_REASON_VMRESUME] = handle_vmresume,
[EXIT_REASON_VMWRITE] = handle_vmwrite,
[EXIT_REASON_VMOFF] = handle_vmoff,
[EXIT_REASON_VMON] = handle_vmon,
[EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
[EXIT_REASON_APIC_ACCESS] = handle_apic_access,
[EXIT_REASON_APIC_WRITE] = handle_apic_write,
[EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
[EXIT_REASON_WBINVD] = handle_wbinvd,
[EXIT_REASON_XSETBV] = handle_xsetbv,
[EXIT_REASON_TASK_SWITCH] = handle_task_switch,
[EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
[EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
[EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
[EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
[EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
[EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
[EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
[EXIT_REASON_INVEPT] = handle_invept,
[EXIT_REASON_INVVPID] = handle_invvpid,
[EXIT_REASON_XSAVES] = handle_xsaves,
[EXIT_REASON_XRSTORS] = handle_xrstors,
[EXIT_REASON_PML_FULL] = handle_pml_full,
[EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
};
static const int kvm_vmx_max_exit_handlers =
ARRAY_SIZE(kvm_vmx_exit_handlers);
static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
unsigned long exit_qualification;
gpa_t bitmap, last_bitmap;
unsigned int port;
int size;
u8 b;
if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
port = exit_qualification >> 16;
size = (exit_qualification & 7) + 1;
last_bitmap = (gpa_t)-1;
b = -1;
while (size > 0) {
if (port < 0x8000)
bitmap = vmcs12->io_bitmap_a;
else if (port < 0x10000)
bitmap = vmcs12->io_bitmap_b;
else
return true;
bitmap += (port & 0x7fff) / 8;
if (last_bitmap != bitmap)
if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
return true;
if (b & (1 << (port & 7)))
return true;
port++;
size--;
last_bitmap = bitmap;
}
return false;
}
/*
* Return 1 if we should exit from L2 to L1 to handle an MSR access access,
* rather than handle it ourselves in L0. I.e., check whether L1 expressed
* disinterest in the current event (read or write a specific MSR) by using an
* MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
*/
static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12, u32 exit_reason)
{
u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
gpa_t bitmap;
if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
return true;
/*
* The MSR_BITMAP page is divided into four 1024-byte bitmaps,
* for the four combinations of read/write and low/high MSR numbers.
* First we need to figure out which of the four to use:
*/
bitmap = vmcs12->msr_bitmap;
if (exit_reason == EXIT_REASON_MSR_WRITE)
bitmap += 2048;
if (msr_index >= 0xc0000000) {
msr_index -= 0xc0000000;
bitmap += 1024;
}
/* Then read the msr_index'th bit from this bitmap: */
if (msr_index < 1024*8) {
unsigned char b;
if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
return true;
return 1 & (b >> (msr_index & 7));
} else
return true; /* let L1 handle the wrong parameter */
}
/*
* Return 1 if we should exit from L2 to L1 to handle a CR access exit,
* rather than handle it ourselves in L0. I.e., check if L1 wanted to
* intercept (via guest_host_mask etc.) the current event.
*/
static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
int cr = exit_qualification & 15;
int reg = (exit_qualification >> 8) & 15;
unsigned long val = kvm_register_readl(vcpu, reg);
switch ((exit_qualification >> 4) & 3) {
case 0: /* mov to cr */
switch (cr) {
case 0:
if (vmcs12->cr0_guest_host_mask &
(val ^ vmcs12->cr0_read_shadow))
return true;
break;
case 3:
if ((vmcs12->cr3_target_count >= 1 &&
vmcs12->cr3_target_value0 == val) ||
(vmcs12->cr3_target_count >= 2 &&
vmcs12->cr3_target_value1 == val) ||
(vmcs12->cr3_target_count >= 3 &&
vmcs12->cr3_target_value2 == val) ||
(vmcs12->cr3_target_count >= 4 &&
vmcs12->cr3_target_value3 == val))
return false;
if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
return true;
break;
case 4:
if (vmcs12->cr4_guest_host_mask &
(vmcs12->cr4_read_shadow ^ val))
return true;
break;
case 8:
if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
return true;
break;
}
break;
case 2: /* clts */
if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
(vmcs12->cr0_read_shadow & X86_CR0_TS))
return true;
break;
case 1: /* mov from cr */
switch (cr) {
case 3:
if (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_CR3_STORE_EXITING)
return true;
break;
case 8:
if (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_CR8_STORE_EXITING)
return true;
break;
}
break;
case 3: /* lmsw */
/*
* lmsw can change bits 1..3 of cr0, and only set bit 0 of
* cr0. Other attempted changes are ignored, with no exit.
*/
if (vmcs12->cr0_guest_host_mask & 0xe &
(val ^ vmcs12->cr0_read_shadow))
return true;
if ((vmcs12->cr0_guest_host_mask & 0x1) &&
!(vmcs12->cr0_read_shadow & 0x1) &&
(val & 0x1))
return true;
break;
}
return false;
}
/*
* Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
* should handle it ourselves in L0 (and then continue L2). Only call this
* when in is_guest_mode (L2).
*/
static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
{
u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
u32 exit_reason = vmx->exit_reason;
trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
vmcs_readl(EXIT_QUALIFICATION),
vmx->idt_vectoring_info,
intr_info,
vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
KVM_ISA_VMX);
if (vmx->nested.nested_run_pending)
return false;
if (unlikely(vmx->fail)) {
pr_info_ratelimited("%s failed vm entry %x\n", __func__,
vmcs_read32(VM_INSTRUCTION_ERROR));
return true;
}
switch (exit_reason) {
case EXIT_REASON_EXCEPTION_NMI:
if (!is_exception(intr_info))
return false;
else if (is_page_fault(intr_info))
return enable_ept;
else if (is_no_device(intr_info) &&
!(vmcs12->guest_cr0 & X86_CR0_TS))
return false;
else if (is_debug(intr_info) &&
vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
return false;
else if (is_breakpoint(intr_info) &&
vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
return false;
return vmcs12->exception_bitmap &
(1u << (intr_info & INTR_INFO_VECTOR_MASK));
case EXIT_REASON_EXTERNAL_INTERRUPT:
return false;
case EXIT_REASON_TRIPLE_FAULT:
return true;
case EXIT_REASON_PENDING_INTERRUPT:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
case EXIT_REASON_NMI_WINDOW:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
case EXIT_REASON_TASK_SWITCH:
return true;
case EXIT_REASON_CPUID:
if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa)
return false;
return true;
case EXIT_REASON_HLT:
return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
case EXIT_REASON_INVD:
return true;
case EXIT_REASON_INVLPG:
return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
case EXIT_REASON_RDPMC:
return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
/*
* VMX instructions trap unconditionally. This allows L1 to
* emulate them for its L2 guest, i.e., allows 3-level nesting!
*/
return true;
case EXIT_REASON_CR_ACCESS:
return nested_vmx_exit_handled_cr(vcpu, vmcs12);
case EXIT_REASON_DR_ACCESS:
return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
case EXIT_REASON_IO_INSTRUCTION:
return nested_vmx_exit_handled_io(vcpu, vmcs12);
case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
case EXIT_REASON_MSR_READ:
case EXIT_REASON_MSR_WRITE:
return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
case EXIT_REASON_INVALID_STATE:
return true;
case EXIT_REASON_MWAIT_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
case EXIT_REASON_MONITOR_TRAP_FLAG:
return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
case EXIT_REASON_MONITOR_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
case EXIT_REASON_PAUSE_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
nested_cpu_has2(vmcs12,
SECONDARY_EXEC_PAUSE_LOOP_EXITING);
case EXIT_REASON_MCE_DURING_VMENTRY:
return false;
case EXIT_REASON_TPR_BELOW_THRESHOLD:
return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
case EXIT_REASON_APIC_ACCESS:
return nested_cpu_has2(vmcs12,
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
case EXIT_REASON_APIC_WRITE:
case EXIT_REASON_EOI_INDUCED:
/* apic_write and eoi_induced should exit unconditionally. */
return true;
case EXIT_REASON_EPT_VIOLATION:
/*
* L0 always deals with the EPT violation. If nested EPT is
* used, and the nested mmu code discovers that the address is
* missing in the guest EPT table (EPT12), the EPT violation
* will be injected with nested_ept_inject_page_fault()
*/
return false;
case EXIT_REASON_EPT_MISCONFIG:
/*
* L2 never uses directly L1's EPT, but rather L0's own EPT
* table (shadow on EPT) or a merged EPT table that L0 built
* (EPT on EPT). So any problems with the structure of the
* table is L0's fault.
*/
return false;
case EXIT_REASON_WBINVD:
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
case EXIT_REASON_XSETBV:
return true;
case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
/*
* This should never happen, since it is not possible to
* set XSS to a non-zero value---neither in L1 nor in L2.
* If if it were, XSS would have to be checked against
* the XSS exit bitmap in vmcs12.
*/
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
case EXIT_REASON_PREEMPTION_TIMER:
return false;
default:
return true;
}
}
static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
{
*info1 = vmcs_readl(EXIT_QUALIFICATION);
*info2 = vmcs_read32(VM_EXIT_INTR_INFO);
}
static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
{
if (vmx->pml_pg) {
__free_page(vmx->pml_pg);
vmx->pml_pg = NULL;
}
}
static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 *pml_buf;
u16 pml_idx;
pml_idx = vmcs_read16(GUEST_PML_INDEX);
/* Do nothing if PML buffer is empty */
if (pml_idx == (PML_ENTITY_NUM - 1))
return;
/* PML index always points to next available PML buffer entity */
if (pml_idx >= PML_ENTITY_NUM)
pml_idx = 0;
else
pml_idx++;
pml_buf = page_address(vmx->pml_pg);
for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
u64 gpa;
gpa = pml_buf[pml_idx];
WARN_ON(gpa & (PAGE_SIZE - 1));
kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
}
/* reset PML index */
vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
}
/*
* Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
* Called before reporting dirty_bitmap to userspace.
*/
static void kvm_flush_pml_buffers(struct kvm *kvm)
{
int i;
struct kvm_vcpu *vcpu;
/*
* We only need to kick vcpu out of guest mode here, as PML buffer
* is flushed at beginning of all VMEXITs, and it's obvious that only
* vcpus running in guest are possible to have unflushed GPAs in PML
* buffer.
*/
kvm_for_each_vcpu(i, vcpu, kvm)
kvm_vcpu_kick(vcpu);
}
static void vmx_dump_sel(char *name, uint32_t sel)
{
pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
name, vmcs_read32(sel),
vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
}
static void vmx_dump_dtsel(char *name, uint32_t limit)
{
pr_err("%s limit=0x%08x, base=0x%016lx\n",
name, vmcs_read32(limit),
vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
}
static void dump_vmcs(void)
{
u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
u32 secondary_exec_control = 0;
unsigned long cr4 = vmcs_readl(GUEST_CR4);
u64 efer = vmcs_read64(GUEST_IA32_EFER);
int i, n;
if (cpu_has_secondary_exec_ctrls())
secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
pr_err("*** Guest State ***\n");
pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
vmcs_readl(CR0_GUEST_HOST_MASK));
pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
(cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
{
pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
}
pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
vmcs_readl(GUEST_SYSENTER_ESP),
vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
(vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
efer, vmcs_read64(GUEST_IA32_PAT));
pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
vmcs_read64(GUEST_IA32_DEBUGCTL),
vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
pr_err("PerfGlobCtl = 0x%016llx\n",
vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
pr_err("Interruptibility = %08x ActivityState = %08x\n",
vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
vmcs_read32(GUEST_ACTIVITY_STATE));
if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
pr_err("InterruptStatus = %04x\n",
vmcs_read16(GUEST_INTR_STATUS));
pr_err("*** Host State ***\n");
pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
vmcs_read16(HOST_TR_SELECTOR));
pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
vmcs_readl(HOST_TR_BASE));
pr_err("GDTBase=%016lx IDTBase=%016lx\n",
vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
vmcs_readl(HOST_CR4));
pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
vmcs_readl(HOST_IA32_SYSENTER_ESP),
vmcs_read32(HOST_IA32_SYSENTER_CS),
vmcs_readl(HOST_IA32_SYSENTER_EIP));
if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
vmcs_read64(HOST_IA32_EFER),
vmcs_read64(HOST_IA32_PAT));
if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
pr_err("PerfGlobCtl = 0x%016llx\n",
vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
pr_err("*** Control State ***\n");
pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
vmcs_read32(EXCEPTION_BITMAP),
vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
vmcs_read32(VM_EXIT_INTR_INFO),
vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
pr_err(" reason=%08x qualification=%016lx\n",
vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
pr_err("IDTVectoring: info=%08x errcode=%08x\n",
vmcs_read32(IDT_VECTORING_INFO_FIELD),
vmcs_read32(IDT_VECTORING_ERROR_CODE));
pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
pr_err("TSC Multiplier = 0x%016llx\n",
vmcs_read64(TSC_MULTIPLIER));
if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
n = vmcs_read32(CR3_TARGET_COUNT);
for (i = 0; i + 1 < n; i += 4)
pr_err("CR3 target%u=%016lx target%u=%016lx\n",
i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
if (i < n)
pr_err("CR3 target%u=%016lx\n",
i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
pr_err("PLE Gap=%08x Window=%08x\n",
vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
pr_err("Virtual processor ID = 0x%04x\n",
vmcs_read16(VIRTUAL_PROCESSOR_ID));
}
/*
* The guest has exited. See if we can fix it or if we need userspace
* assistance.
*/
static int vmx_handle_exit(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 exit_reason = vmx->exit_reason;
u32 vectoring_info = vmx->idt_vectoring_info;
trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
/*
* Flush logged GPAs PML buffer, this will make dirty_bitmap more
* updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
* querying dirty_bitmap, we only need to kick all vcpus out of guest
* mode as if vcpus is in root mode, the PML buffer must has been
* flushed already.
*/
if (enable_pml)
vmx_flush_pml_buffer(vcpu);
/* If guest state is invalid, start emulating */
if (vmx->emulation_required)
return handle_invalid_guest_state(vcpu);
if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
nested_vmx_vmexit(vcpu, exit_reason,
vmcs_read32(VM_EXIT_INTR_INFO),
vmcs_readl(EXIT_QUALIFICATION));
return 1;
}
if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
dump_vmcs();
vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
vcpu->run->fail_entry.hardware_entry_failure_reason
= exit_reason;
return 0;
}
if (unlikely(vmx->fail)) {
vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
vcpu->run->fail_entry.hardware_entry_failure_reason
= vmcs_read32(VM_INSTRUCTION_ERROR);
return 0;
}
/*
* Note:
* Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
* delivery event since it indicates guest is accessing MMIO.
* The vm-exit can be triggered again after return to guest that
* will cause infinite loop.
*/
if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
(exit_reason != EXIT_REASON_EXCEPTION_NMI &&
exit_reason != EXIT_REASON_EPT_VIOLATION &&
exit_reason != EXIT_REASON_PML_FULL &&
exit_reason != EXIT_REASON_TASK_SWITCH)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
vcpu->run->internal.ndata = 2;
vcpu->run->internal.data[0] = vectoring_info;
vcpu->run->internal.data[1] = exit_reason;
return 0;
}
if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
!(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
get_vmcs12(vcpu))))) {
if (vmx_interrupt_allowed(vcpu)) {
vmx->soft_vnmi_blocked = 0;
} else if (vmx->vnmi_blocked_time > 1000000000LL &&
vcpu->arch.nmi_pending) {
/*
* This CPU don't support us in finding the end of an
* NMI-blocked window if the guest runs with IRQs
* disabled. So we pull the trigger after 1 s of
* futile waiting, but inform the user about this.
*/
printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
"state on VCPU %d after 1 s timeout\n",
__func__, vcpu->vcpu_id);
vmx->soft_vnmi_blocked = 0;
}
}
if (exit_reason < kvm_vmx_max_exit_handlers
&& kvm_vmx_exit_handlers[exit_reason])
return kvm_vmx_exit_handlers[exit_reason](vcpu);
else {
WARN_ONCE(1, "vmx: unexpected exit reason 0x%x\n", exit_reason);
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
}
static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
if (is_guest_mode(vcpu) &&
nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
return;
if (irr == -1 || tpr < irr) {
vmcs_write32(TPR_THRESHOLD, 0);
return;
}
vmcs_write32(TPR_THRESHOLD, irr);
}
static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
{
u32 sec_exec_control;
/* Postpone execution until vmcs01 is the current VMCS. */
if (is_guest_mode(vcpu)) {
to_vmx(vcpu)->nested.change_vmcs01_virtual_x2apic_mode = true;
return;
}
if (!cpu_has_vmx_virtualize_x2apic_mode())
return;
if (!cpu_need_tpr_shadow(vcpu))
return;
sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
if (set) {
sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
} else {
sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
}
vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
vmx_set_msr_bitmap(vcpu);
}
static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
/*
* Currently we do not handle the nested case where L2 has an
* APIC access page of its own; that page is still pinned.
* Hence, we skip the case where the VCPU is in guest mode _and_
* L1 prepared an APIC access page for L2.
*
* For the case where L1 and L2 share the same APIC access page
* (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
* in the vmcs12), this function will only update either the vmcs01
* or the vmcs02. If the former, the vmcs02 will be updated by
* prepare_vmcs02. If the latter, the vmcs01 will be updated in
* the next L2->L1 exit.
*/
if (!is_guest_mode(vcpu) ||
!nested_cpu_has2(get_vmcs12(&vmx->vcpu),
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
vmcs_write64(APIC_ACCESS_ADDR, hpa);
}
static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
{
u16 status;
u8 old;
if (max_isr == -1)
max_isr = 0;
status = vmcs_read16(GUEST_INTR_STATUS);
old = status >> 8;
if (max_isr != old) {
status &= 0xff;
status |= max_isr << 8;
vmcs_write16(GUEST_INTR_STATUS, status);
}
}
static void vmx_set_rvi(int vector)
{
u16 status;
u8 old;
if (vector == -1)
vector = 0;
status = vmcs_read16(GUEST_INTR_STATUS);
old = (u8)status & 0xff;
if ((u8)vector != old) {
status &= ~0xff;
status |= (u8)vector;
vmcs_write16(GUEST_INTR_STATUS, status);
}
}
static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
{
if (!is_guest_mode(vcpu)) {
vmx_set_rvi(max_irr);
return;
}
if (max_irr == -1)
return;
/*
* In guest mode. If a vmexit is needed, vmx_check_nested_events
* handles it.
*/
if (nested_exit_on_intr(vcpu))
return;
/*
* Else, fall back to pre-APICv interrupt injection since L2
* is run without virtual interrupt delivery.
*/
if (!kvm_event_needs_reinjection(vcpu) &&
vmx_interrupt_allowed(vcpu)) {
kvm_queue_interrupt(vcpu, max_irr, false);
vmx_inject_irq(vcpu);
}
}
static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
{
if (!kvm_vcpu_apicv_active(vcpu))
return;
vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
}
static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
{
u32 exit_intr_info;
if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
|| vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
return;
vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
exit_intr_info = vmx->exit_intr_info;
/* Handle machine checks before interrupts are enabled */
if (is_machine_check(exit_intr_info))
kvm_machine_check();
/* We need to handle NMIs before interrupts are enabled */
if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
(exit_intr_info & INTR_INFO_VALID_MASK)) {
kvm_before_handle_nmi(&vmx->vcpu);
asm("int $2");
kvm_after_handle_nmi(&vmx->vcpu);
}
}
static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
{
u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
register void *__sp asm(_ASM_SP);
if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
== (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
unsigned int vector;
unsigned long entry;
gate_desc *desc;
struct vcpu_vmx *vmx = to_vmx(vcpu);
#ifdef CONFIG_X86_64
unsigned long tmp;
#endif
vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
desc = (gate_desc *)vmx->host_idt_base + vector;
entry = gate_offset(*desc);
asm volatile(
#ifdef CONFIG_X86_64
"mov %%" _ASM_SP ", %[sp]\n\t"
"and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
"push $%c[ss]\n\t"
"push %[sp]\n\t"
#endif
"pushf\n\t"
__ASM_SIZE(push) " $%c[cs]\n\t"
"call *%[entry]\n\t"
:
#ifdef CONFIG_X86_64
[sp]"=&r"(tmp),
#endif
"+r"(__sp)
:
[entry]"r"(entry),
[ss]"i"(__KERNEL_DS),
[cs]"i"(__KERNEL_CS)
);
}
}
static bool vmx_has_high_real_mode_segbase(void)
{
return enable_unrestricted_guest || emulate_invalid_guest_state;
}
static bool vmx_mpx_supported(void)
{
return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
(vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
}
static bool vmx_xsaves_supported(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_XSAVES;
}
static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
{
u32 exit_intr_info;
bool unblock_nmi;
u8 vector;
bool idtv_info_valid;
idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
if (cpu_has_virtual_nmis()) {
if (vmx->nmi_known_unmasked)
return;
/*
* Can't use vmx->exit_intr_info since we're not sure what
* the exit reason is.
*/
exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
/*
* SDM 3: 27.7.1.2 (September 2008)
* Re-set bit "block by NMI" before VM entry if vmexit caused by
* a guest IRET fault.
* SDM 3: 23.2.2 (September 2008)
* Bit 12 is undefined in any of the following cases:
* If the VM exit sets the valid bit in the IDT-vectoring
* information field.
* If the VM exit is due to a double fault.
*/
if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
vector != DF_VECTOR && !idtv_info_valid)
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
else
vmx->nmi_known_unmasked =
!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
& GUEST_INTR_STATE_NMI);
} else if (unlikely(vmx->soft_vnmi_blocked))
vmx->vnmi_blocked_time +=
ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
}
static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
u32 idt_vectoring_info,
int instr_len_field,
int error_code_field)
{
u8 vector;
int type;
bool idtv_info_valid;
idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
vcpu->arch.nmi_injected = false;
kvm_clear_exception_queue(vcpu);
kvm_clear_interrupt_queue(vcpu);
if (!idtv_info_valid)
return;
kvm_make_request(KVM_REQ_EVENT, vcpu);
vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
switch (type) {
case INTR_TYPE_NMI_INTR:
vcpu->arch.nmi_injected = true;
/*
* SDM 3: 27.7.1.2 (September 2008)
* Clear bit "block by NMI" before VM entry if a NMI
* delivery faulted.
*/
vmx_set_nmi_mask(vcpu, false);
break;
case INTR_TYPE_SOFT_EXCEPTION:
vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
/* fall through */
case INTR_TYPE_HARD_EXCEPTION:
if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
u32 err = vmcs_read32(error_code_field);
kvm_requeue_exception_e(vcpu, vector, err);
} else
kvm_requeue_exception(vcpu, vector);
break;
case INTR_TYPE_SOFT_INTR:
vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
/* fall through */
case INTR_TYPE_EXT_INTR:
kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
break;
default:
break;
}
}
static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
{
__vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
VM_EXIT_INSTRUCTION_LEN,
IDT_VECTORING_ERROR_CODE);
}
static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
{
__vmx_complete_interrupts(vcpu,
vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
VM_ENTRY_INSTRUCTION_LEN,
VM_ENTRY_EXCEPTION_ERROR_CODE);
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
}
static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
{
int i, nr_msrs;
struct perf_guest_switch_msr *msrs;
msrs = perf_guest_get_msrs(&nr_msrs);
if (!msrs)
return;
for (i = 0; i < nr_msrs; i++)
if (msrs[i].host == msrs[i].guest)
clear_atomic_switch_msr(vmx, msrs[i].msr);
else
add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
msrs[i].host);
}
static void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 tscl;
u32 delta_tsc;
if (vmx->hv_deadline_tsc == -1)
return;
tscl = rdtsc();
if (vmx->hv_deadline_tsc > tscl)
/* sure to be 32 bit only because checked on set_hv_timer */
delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
cpu_preemption_timer_multi);
else
delta_tsc = 0;
vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
}
static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long debugctlmsr, cr4;
/* Record the guest's net vcpu time for enforced NMI injections. */
if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
vmx->entry_time = ktime_get();
/* Don't enter VMX if guest state is invalid, let the exit handler
start emulation until we arrive back to a valid state */
if (vmx->emulation_required)
return;
if (vmx->ple_window_dirty) {
vmx->ple_window_dirty = false;
vmcs_write32(PLE_WINDOW, vmx->ple_window);
}
if (vmx->nested.sync_shadow_vmcs) {
copy_vmcs12_to_shadow(vmx);
vmx->nested.sync_shadow_vmcs = false;
}
if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
cr4 = cr4_read_shadow();
if (unlikely(cr4 != vmx->host_state.vmcs_host_cr4)) {
vmcs_writel(HOST_CR4, cr4);
vmx->host_state.vmcs_host_cr4 = cr4;
}
/* When single-stepping over STI and MOV SS, we must clear the
* corresponding interruptibility bits in the guest state. Otherwise
* vmentry fails as it then expects bit 14 (BS) in pending debug
* exceptions being set, but that's not correct for the guest debugging
* case. */
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
vmx_set_interrupt_shadow(vcpu, 0);
if (vmx->guest_pkru_valid)
__write_pkru(vmx->guest_pkru);
atomic_switch_perf_msrs(vmx);
debugctlmsr = get_debugctlmsr();
vmx_arm_hv_timer(vcpu);
vmx->__launched = vmx->loaded_vmcs->launched;
asm(
/* Store host registers */
"push %%" _ASM_DX "; push %%" _ASM_BP ";"
"push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
"push %%" _ASM_CX " \n\t"
"cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
"je 1f \n\t"
"mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
__ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
"1: \n\t"
/* Reload cr2 if changed */
"mov %c[cr2](%0), %%" _ASM_AX " \n\t"
"mov %%cr2, %%" _ASM_DX " \n\t"
"cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
"je 2f \n\t"
"mov %%" _ASM_AX", %%cr2 \n\t"
"2: \n\t"
/* Check if vmlaunch of vmresume is needed */
"cmpl $0, %c[launched](%0) \n\t"
/* Load guest registers. Don't clobber flags. */
"mov %c[rax](%0), %%" _ASM_AX " \n\t"
"mov %c[rbx](%0), %%" _ASM_BX " \n\t"
"mov %c[rdx](%0), %%" _ASM_DX " \n\t"
"mov %c[rsi](%0), %%" _ASM_SI " \n\t"
"mov %c[rdi](%0), %%" _ASM_DI " \n\t"
"mov %c[rbp](%0), %%" _ASM_BP " \n\t"
#ifdef CONFIG_X86_64
"mov %c[r8](%0), %%r8 \n\t"
"mov %c[r9](%0), %%r9 \n\t"
"mov %c[r10](%0), %%r10 \n\t"
"mov %c[r11](%0), %%r11 \n\t"
"mov %c[r12](%0), %%r12 \n\t"
"mov %c[r13](%0), %%r13 \n\t"
"mov %c[r14](%0), %%r14 \n\t"
"mov %c[r15](%0), %%r15 \n\t"
#endif
"mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
/* Enter guest mode */
"jne 1f \n\t"
__ex(ASM_VMX_VMLAUNCH) "\n\t"
"jmp 2f \n\t"
"1: " __ex(ASM_VMX_VMRESUME) "\n\t"
"2: "
/* Save guest registers, load host registers, keep flags */
"mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
"pop %0 \n\t"
"mov %%" _ASM_AX ", %c[rax](%0) \n\t"
"mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
__ASM_SIZE(pop) " %c[rcx](%0) \n\t"
"mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
"mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
"mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
"mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
#ifdef CONFIG_X86_64
"mov %%r8, %c[r8](%0) \n\t"
"mov %%r9, %c[r9](%0) \n\t"
"mov %%r10, %c[r10](%0) \n\t"
"mov %%r11, %c[r11](%0) \n\t"
"mov %%r12, %c[r12](%0) \n\t"
"mov %%r13, %c[r13](%0) \n\t"
"mov %%r14, %c[r14](%0) \n\t"
"mov %%r15, %c[r15](%0) \n\t"
#endif
"mov %%cr2, %%" _ASM_AX " \n\t"
"mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
"pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
"setbe %c[fail](%0) \n\t"
".pushsection .rodata \n\t"
".global vmx_return \n\t"
"vmx_return: " _ASM_PTR " 2b \n\t"
".popsection"
: : "c"(vmx), "d"((unsigned long)HOST_RSP),
[launched]"i"(offsetof(struct vcpu_vmx, __launched)),
[fail]"i"(offsetof(struct vcpu_vmx, fail)),
[host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
[rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
[rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
[rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
[rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
[rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
[rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
[rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
#ifdef CONFIG_X86_64
[r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
[r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
[r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
[r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
[r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
[r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
[r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
[r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
#endif
[cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
[wordsize]"i"(sizeof(ulong))
: "cc", "memory"
#ifdef CONFIG_X86_64
, "rax", "rbx", "rdi", "rsi"
, "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
#else
, "eax", "ebx", "edi", "esi"
#endif
);
/* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
if (debugctlmsr)
update_debugctlmsr(debugctlmsr);
#ifndef CONFIG_X86_64
/*
* The sysexit path does not restore ds/es, so we must set them to
* a reasonable value ourselves.
*
* We can't defer this to vmx_load_host_state() since that function
* may be executed in interrupt context, which saves and restore segments
* around it, nullifying its effect.
*/
loadsegment(ds, __USER_DS);
loadsegment(es, __USER_DS);
#endif
vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
| (1 << VCPU_EXREG_RFLAGS)
| (1 << VCPU_EXREG_PDPTR)
| (1 << VCPU_EXREG_SEGMENTS)
| (1 << VCPU_EXREG_CR3));
vcpu->arch.regs_dirty = 0;
vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
vmx->loaded_vmcs->launched = 1;
vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
/*
* eager fpu is enabled if PKEY is supported and CR4 is switched
* back on host, so it is safe to read guest PKRU from current
* XSAVE.
*/
if (boot_cpu_has(X86_FEATURE_OSPKE)) {
vmx->guest_pkru = __read_pkru();
if (vmx->guest_pkru != vmx->host_pkru) {
vmx->guest_pkru_valid = true;
__write_pkru(vmx->host_pkru);
} else
vmx->guest_pkru_valid = false;
}
/*
* the KVM_REQ_EVENT optimization bit is only on for one entry, and if
* we did not inject a still-pending event to L1 now because of
* nested_run_pending, we need to re-enable this bit.
*/
if (vmx->nested.nested_run_pending)
kvm_make_request(KVM_REQ_EVENT, vcpu);
vmx->nested.nested_run_pending = 0;
vmx_complete_atomic_exit(vmx);
vmx_recover_nmi_blocking(vmx);
vmx_complete_interrupts(vmx);
}
static void vmx_load_vmcs01(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int cpu;
if (vmx->loaded_vmcs == &vmx->vmcs01)
return;
cpu = get_cpu();
vmx->loaded_vmcs = &vmx->vmcs01;
vmx_vcpu_put(vcpu);
vmx_vcpu_load(vcpu, cpu);
vcpu->cpu = cpu;
put_cpu();
}
/*
* Ensure that the current vmcs of the logical processor is the
* vmcs01 of the vcpu before calling free_nested().
*/
static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int r;
r = vcpu_load(vcpu);
BUG_ON(r);
vmx_load_vmcs01(vcpu);
free_nested(vmx);
vcpu_put(vcpu);
}
static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (enable_pml)
vmx_destroy_pml_buffer(vmx);
free_vpid(vmx->vpid);
leave_guest_mode(vcpu);
vmx_free_vcpu_nested(vcpu);
free_loaded_vmcs(vmx->loaded_vmcs);
kfree(vmx->guest_msrs);
kvm_vcpu_uninit(vcpu);
kmem_cache_free(kvm_vcpu_cache, vmx);
}
static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
{
int err;
struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
int cpu;
if (!vmx)
return ERR_PTR(-ENOMEM);
vmx->vpid = allocate_vpid();
err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
if (err)
goto free_vcpu;
err = -ENOMEM;
/*
* If PML is turned on, failure on enabling PML just results in failure
* of creating the vcpu, therefore we can simplify PML logic (by
* avoiding dealing with cases, such as enabling PML partially on vcpus
* for the guest, etc.
*/
if (enable_pml) {
vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!vmx->pml_pg)
goto uninit_vcpu;
}
vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
> PAGE_SIZE);
if (!vmx->guest_msrs)
goto free_pml;
vmx->loaded_vmcs = &vmx->vmcs01;
vmx->loaded_vmcs->vmcs = alloc_vmcs();
vmx->loaded_vmcs->shadow_vmcs = NULL;
if (!vmx->loaded_vmcs->vmcs)
goto free_msrs;
if (!vmm_exclusive)
kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
loaded_vmcs_init(vmx->loaded_vmcs);
if (!vmm_exclusive)
kvm_cpu_vmxoff();
cpu = get_cpu();
vmx_vcpu_load(&vmx->vcpu, cpu);
vmx->vcpu.cpu = cpu;
err = vmx_vcpu_setup(vmx);
vmx_vcpu_put(&vmx->vcpu);
put_cpu();
if (err)
goto free_vmcs;
if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
err = alloc_apic_access_page(kvm);
if (err)
goto free_vmcs;
}
if (enable_ept) {
if (!kvm->arch.ept_identity_map_addr)
kvm->arch.ept_identity_map_addr =
VMX_EPT_IDENTITY_PAGETABLE_ADDR;
err = init_rmode_identity_map(kvm);
if (err)
goto free_vmcs;
}
if (nested) {
nested_vmx_setup_ctls_msrs(vmx);
vmx->nested.vpid02 = allocate_vpid();
}
vmx->nested.posted_intr_nv = -1;
vmx->nested.current_vmptr = -1ull;
vmx->nested.current_vmcs12 = NULL;
vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
return &vmx->vcpu;
free_vmcs:
free_vpid(vmx->nested.vpid02);
free_loaded_vmcs(vmx->loaded_vmcs);
free_msrs:
kfree(vmx->guest_msrs);
free_pml:
vmx_destroy_pml_buffer(vmx);
uninit_vcpu:
kvm_vcpu_uninit(&vmx->vcpu);
free_vcpu:
free_vpid(vmx->vpid);
kmem_cache_free(kvm_vcpu_cache, vmx);
return ERR_PTR(err);
}
static void __init vmx_check_processor_compat(void *rtn)
{
struct vmcs_config vmcs_conf;
*(int *)rtn = 0;
if (setup_vmcs_config(&vmcs_conf) < 0)
*(int *)rtn = -EIO;
if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
smp_processor_id());
*(int *)rtn = -EIO;
}
}
static int get_ept_level(void)
{
return VMX_EPT_DEFAULT_GAW + 1;
}
static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
{
u8 cache;
u64 ipat = 0;
/* For VT-d and EPT combination
* 1. MMIO: always map as UC
* 2. EPT with VT-d:
* a. VT-d without snooping control feature: can't guarantee the
* result, try to trust guest.
* b. VT-d with snooping control feature: snooping control feature of
* VT-d engine can guarantee the cache correctness. Just set it
* to WB to keep consistent with host. So the same as item 3.
* 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
* consistent with host MTRR
*/
if (is_mmio) {
cache = MTRR_TYPE_UNCACHABLE;
goto exit;
}
if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
ipat = VMX_EPT_IPAT_BIT;
cache = MTRR_TYPE_WRBACK;
goto exit;
}
if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
ipat = VMX_EPT_IPAT_BIT;
if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
cache = MTRR_TYPE_WRBACK;
else
cache = MTRR_TYPE_UNCACHABLE;
goto exit;
}
cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
exit:
return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
}
static int vmx_get_lpage_level(void)
{
if (enable_ept && !cpu_has_vmx_ept_1g_page())
return PT_DIRECTORY_LEVEL;
else
/* For shadow and EPT supported 1GB page */
return PT_PDPE_LEVEL;
}
static void vmcs_set_secondary_exec_control(u32 new_ctl)
{
/*
* These bits in the secondary execution controls field
* are dynamic, the others are mostly based on the hypervisor
* architecture and the guest's CPUID. Do not touch the
* dynamic bits.
*/
u32 mask =
SECONDARY_EXEC_SHADOW_VMCS |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
(new_ctl & ~mask) | (cur_ctl & mask));
}
/*
* Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
* (indicating "allowed-1") if they are supported in the guest's CPUID.
*/
static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_cpuid_entry2 *entry;
vmx->nested.nested_vmx_cr0_fixed1 = 0xffffffff;
vmx->nested.nested_vmx_cr4_fixed1 = X86_CR4_PCE;
#define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
if (entry && (entry->_reg & (_cpuid_mask))) \
vmx->nested.nested_vmx_cr4_fixed1 |= (_cr4_mask); \
} while (0)
entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
/* TODO: Use X86_CR4_UMIP and X86_FEATURE_UMIP macros */
cr4_fixed1_update(bit(11), ecx, bit(2));
#undef cr4_fixed1_update
}
static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
{
struct kvm_cpuid_entry2 *best;
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 secondary_exec_ctl = vmx_secondary_exec_control(vmx);
if (vmx_rdtscp_supported()) {
bool rdtscp_enabled = guest_cpuid_has_rdtscp(vcpu);
if (!rdtscp_enabled)
secondary_exec_ctl &= ~SECONDARY_EXEC_RDTSCP;
if (nested) {
if (rdtscp_enabled)
vmx->nested.nested_vmx_secondary_ctls_high |=
SECONDARY_EXEC_RDTSCP;
else
vmx->nested.nested_vmx_secondary_ctls_high &=
~SECONDARY_EXEC_RDTSCP;
}
}
/* Exposing INVPCID only when PCID is exposed */
best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
if (vmx_invpcid_supported() &&
(!best || !(best->ebx & bit(X86_FEATURE_INVPCID)) ||
!guest_cpuid_has_pcid(vcpu))) {
secondary_exec_ctl &= ~SECONDARY_EXEC_ENABLE_INVPCID;
if (best)
best->ebx &= ~bit(X86_FEATURE_INVPCID);
}
if (cpu_has_secondary_exec_ctrls())
vmcs_set_secondary_exec_control(secondary_exec_ctl);
if (nested_vmx_allowed(vcpu))
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
else
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
if (nested_vmx_allowed(vcpu))
nested_vmx_cr_fixed1_bits_update(vcpu);
}
static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
{
if (func == 1 && nested)
entry->ecx |= bit(X86_FEATURE_VMX);
}
static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
struct x86_exception *fault)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
u32 exit_reason;
if (fault->error_code & PFERR_RSVD_MASK)
exit_reason = EXIT_REASON_EPT_MISCONFIG;
else
exit_reason = EXIT_REASON_EPT_VIOLATION;
nested_vmx_vmexit(vcpu, exit_reason, 0, vcpu->arch.exit_qualification);
vmcs12->guest_physical_address = fault->address;
}
/* Callbacks for nested_ept_init_mmu_context: */
static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
{
/* return the page table to be shadowed - in our case, EPT12 */
return get_vmcs12(vcpu)->ept_pointer;
}
static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
{
WARN_ON(mmu_is_nested(vcpu));
kvm_init_shadow_ept_mmu(vcpu,
to_vmx(vcpu)->nested.nested_vmx_ept_caps &
VMX_EPT_EXECUTE_ONLY_BIT);
vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
}
static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
{
vcpu->arch.walk_mmu = &vcpu->arch.mmu;
}
static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
u16 error_code)
{
bool inequality, bit;
bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
inequality =
(error_code & vmcs12->page_fault_error_code_mask) !=
vmcs12->page_fault_error_code_match;
return inequality ^ bit;
}
static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
struct x86_exception *fault)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
WARN_ON(!is_guest_mode(vcpu));
if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code))
nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
vmcs_read32(VM_EXIT_INTR_INFO),
vmcs_readl(EXIT_QUALIFICATION));
else
kvm_inject_page_fault(vcpu, fault);
}
static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int maxphyaddr = cpuid_maxphyaddr(vcpu);
if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
if (!PAGE_ALIGNED(vmcs12->apic_access_addr) ||
vmcs12->apic_access_addr >> maxphyaddr)
return false;
/*
* Translate L1 physical address to host physical
* address for vmcs02. Keep the page pinned, so this
* physical address remains valid. We keep a reference
* to it so we can release it later.
*/
if (vmx->nested.apic_access_page) /* shouldn't happen */
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page =
nested_get_page(vcpu, vmcs12->apic_access_addr);
}
if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
if (!PAGE_ALIGNED(vmcs12->virtual_apic_page_addr) ||
vmcs12->virtual_apic_page_addr >> maxphyaddr)
return false;
if (vmx->nested.virtual_apic_page) /* shouldn't happen */
nested_release_page(vmx->nested.virtual_apic_page);
vmx->nested.virtual_apic_page =
nested_get_page(vcpu, vmcs12->virtual_apic_page_addr);
/*
* Failing the vm entry is _not_ what the processor does
* but it's basically the only possibility we have.
* We could still enter the guest if CR8 load exits are
* enabled, CR8 store exits are enabled, and virtualize APIC
* access is disabled; in this case the processor would never
* use the TPR shadow and we could simply clear the bit from
* the execution control. But such a configuration is useless,
* so let's keep the code simple.
*/
if (!vmx->nested.virtual_apic_page)
return false;
}
if (nested_cpu_has_posted_intr(vmcs12)) {
if (!IS_ALIGNED(vmcs12->posted_intr_desc_addr, 64) ||
vmcs12->posted_intr_desc_addr >> maxphyaddr)
return false;
if (vmx->nested.pi_desc_page) { /* shouldn't happen */
kunmap(vmx->nested.pi_desc_page);
nested_release_page(vmx->nested.pi_desc_page);
}
vmx->nested.pi_desc_page =
nested_get_page(vcpu, vmcs12->posted_intr_desc_addr);
if (!vmx->nested.pi_desc_page)
return false;
vmx->nested.pi_desc =
(struct pi_desc *)kmap(vmx->nested.pi_desc_page);
if (!vmx->nested.pi_desc) {
nested_release_page_clean(vmx->nested.pi_desc_page);
return false;
}
vmx->nested.pi_desc =
(struct pi_desc *)((void *)vmx->nested.pi_desc +
(unsigned long)(vmcs12->posted_intr_desc_addr &
(PAGE_SIZE - 1)));
}
return true;
}
static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
{
u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (vcpu->arch.virtual_tsc_khz == 0)
return;
/* Make sure short timeouts reliably trigger an immediate vmexit.
* hrtimer_start does not guarantee this. */
if (preemption_timeout <= 1) {
vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
return;
}
preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
preemption_timeout *= 1000000;
do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
hrtimer_start(&vmx->nested.preemption_timer,
ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
}
static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
int maxphyaddr;
u64 addr;
if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
return 0;
if (vmcs12_read_any(vcpu, MSR_BITMAP, &addr)) {
WARN_ON(1);
return -EINVAL;
}
maxphyaddr = cpuid_maxphyaddr(vcpu);
if (!PAGE_ALIGNED(vmcs12->msr_bitmap) ||
((addr + PAGE_SIZE) >> maxphyaddr))
return -EINVAL;
return 0;
}
/*
* Merge L0's and L1's MSR bitmap, return false to indicate that
* we do not use the hardware.
*/
static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
int msr;
struct page *page;
unsigned long *msr_bitmap_l1;
unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.msr_bitmap;
/* This shortcut is ok because we support only x2APIC MSRs so far. */
if (!nested_cpu_has_virt_x2apic_mode(vmcs12))
return false;
page = nested_get_page(vcpu, vmcs12->msr_bitmap);
if (!page) {
WARN_ON(1);
return false;
}
msr_bitmap_l1 = (unsigned long *)kmap(page);
if (!msr_bitmap_l1) {
nested_release_page_clean(page);
WARN_ON(1);
return false;
}
memset(msr_bitmap_l0, 0xff, PAGE_SIZE);
if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
if (nested_cpu_has_apic_reg_virt(vmcs12))
for (msr = 0x800; msr <= 0x8ff; msr++)
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
msr, MSR_TYPE_R);
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
APIC_BASE_MSR + (APIC_TASKPRI >> 4),
MSR_TYPE_R | MSR_TYPE_W);
if (nested_cpu_has_vid(vmcs12)) {
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
APIC_BASE_MSR + (APIC_EOI >> 4),
MSR_TYPE_W);
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
MSR_TYPE_W);
}
}
kunmap(page);
nested_release_page_clean(page);
return true;
}
static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
!nested_cpu_has_apic_reg_virt(vmcs12) &&
!nested_cpu_has_vid(vmcs12) &&
!nested_cpu_has_posted_intr(vmcs12))
return 0;
/*
* If virtualize x2apic mode is enabled,
* virtualize apic access must be disabled.
*/
if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
return -EINVAL;
/*
* If virtual interrupt delivery is enabled,
* we must exit on external interrupts.
*/
if (nested_cpu_has_vid(vmcs12) &&
!nested_exit_on_intr(vcpu))
return -EINVAL;
/*
* bits 15:8 should be zero in posted_intr_nv,
* the descriptor address has been already checked
* in nested_get_vmcs12_pages.
*/
if (nested_cpu_has_posted_intr(vmcs12) &&
(!nested_cpu_has_vid(vmcs12) ||
!nested_exit_intr_ack_set(vcpu) ||
vmcs12->posted_intr_nv & 0xff00))
return -EINVAL;
/* tpr shadow is needed by all apicv features. */
if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
return -EINVAL;
return 0;
}
static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
unsigned long count_field,
unsigned long addr_field)
{
int maxphyaddr;
u64 count, addr;
if (vmcs12_read_any(vcpu, count_field, &count) ||
vmcs12_read_any(vcpu, addr_field, &addr)) {
WARN_ON(1);
return -EINVAL;
}
if (count == 0)
return 0;
maxphyaddr = cpuid_maxphyaddr(vcpu);
if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
(addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
pr_debug_ratelimited(
"nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
addr_field, maxphyaddr, count, addr);
return -EINVAL;
}
return 0;
}
static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
if (vmcs12->vm_exit_msr_load_count == 0 &&
vmcs12->vm_exit_msr_store_count == 0 &&
vmcs12->vm_entry_msr_load_count == 0)
return 0; /* Fast path */
if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
VM_EXIT_MSR_LOAD_ADDR) ||
nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
VM_EXIT_MSR_STORE_ADDR) ||
nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
VM_ENTRY_MSR_LOAD_ADDR))
return -EINVAL;
return 0;
}
static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
struct vmx_msr_entry *e)
{
/* x2APIC MSR accesses are not allowed */
if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
return -EINVAL;
if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
e->index == MSR_IA32_UCODE_REV)
return -EINVAL;
if (e->reserved != 0)
return -EINVAL;
return 0;
}
static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
struct vmx_msr_entry *e)
{
if (e->index == MSR_FS_BASE ||
e->index == MSR_GS_BASE ||
e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
nested_vmx_msr_check_common(vcpu, e))
return -EINVAL;
return 0;
}
static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
struct vmx_msr_entry *e)
{
if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
nested_vmx_msr_check_common(vcpu, e))
return -EINVAL;
return 0;
}
/*
* Load guest's/host's msr at nested entry/exit.
* return 0 for success, entry index for failure.
*/
static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
{
u32 i;
struct vmx_msr_entry e;
struct msr_data msr;
msr.host_initiated = false;
for (i = 0; i < count; i++) {
if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
&e, sizeof(e))) {
pr_debug_ratelimited(
"%s cannot read MSR entry (%u, 0x%08llx)\n",
__func__, i, gpa + i * sizeof(e));
goto fail;
}
if (nested_vmx_load_msr_check(vcpu, &e)) {
pr_debug_ratelimited(
"%s check failed (%u, 0x%x, 0x%x)\n",
__func__, i, e.index, e.reserved);
goto fail;
}
msr.index = e.index;
msr.data = e.value;
if (kvm_set_msr(vcpu, &msr)) {
pr_debug_ratelimited(
"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
__func__, i, e.index, e.value);
goto fail;
}
}
return 0;
fail:
return i + 1;
}
static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
{
u32 i;
struct vmx_msr_entry e;
for (i = 0; i < count; i++) {
struct msr_data msr_info;
if (kvm_vcpu_read_guest(vcpu,
gpa + i * sizeof(e),
&e, 2 * sizeof(u32))) {
pr_debug_ratelimited(
"%s cannot read MSR entry (%u, 0x%08llx)\n",
__func__, i, gpa + i * sizeof(e));
return -EINVAL;
}
if (nested_vmx_store_msr_check(vcpu, &e)) {
pr_debug_ratelimited(
"%s check failed (%u, 0x%x, 0x%x)\n",
__func__, i, e.index, e.reserved);
return -EINVAL;
}
msr_info.host_initiated = false;
msr_info.index = e.index;
if (kvm_get_msr(vcpu, &msr_info)) {
pr_debug_ratelimited(
"%s cannot read MSR (%u, 0x%x)\n",
__func__, i, e.index);
return -EINVAL;
}
if (kvm_vcpu_write_guest(vcpu,
gpa + i * sizeof(e) +
offsetof(struct vmx_msr_entry, value),
&msr_info.data, sizeof(msr_info.data))) {
pr_debug_ratelimited(
"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
__func__, i, e.index, msr_info.data);
return -EINVAL;
}
}
return 0;
}
static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
{
unsigned long invalid_mask;
invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
return (val & invalid_mask) == 0;
}
/*
* Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
* emulating VM entry into a guest with EPT enabled.
* Returns 0 on success, 1 on failure. Invalid state exit qualification code
* is assigned to entry_failure_code on failure.
*/
static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
unsigned long *entry_failure_code)
{
if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
if (!nested_cr3_valid(vcpu, cr3)) {
*entry_failure_code = ENTRY_FAIL_DEFAULT;
return 1;
}
/*
* If PAE paging and EPT are both on, CR3 is not used by the CPU and
* must not be dereferenced.
*/
if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
!nested_ept) {
if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
*entry_failure_code = ENTRY_FAIL_PDPTE;
return 1;
}
}
vcpu->arch.cr3 = cr3;
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
}
kvm_mmu_reset_context(vcpu);
return 0;
}
/*
* prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
* L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
* with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
* guest in a way that will both be appropriate to L1's requests, and our
* needs. In addition to modifying the active vmcs (which is vmcs02), this
* function also has additional necessary side-effects, like setting various
* vcpu->arch fields.
* Returns 0 on success, 1 on failure. Invalid state exit qualification code
* is assigned to entry_failure_code on failure.
*/
static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
unsigned long *entry_failure_code)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 exec_control;
bool nested_ept_enabled = false;
vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
} else {
kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
}
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
vmcs12->vm_entry_intr_info_field);
vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
vmcs12->vm_entry_exception_error_code);
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmcs12->vm_entry_instruction_len);
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
vmcs12->guest_interruptibility_info);
vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
vmx_set_rflags(vcpu, vmcs12->guest_rflags);
vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
vmcs12->guest_pending_dbg_exceptions);
vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
if (nested_cpu_has_xsaves(vmcs12))
vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
vmcs_write64(VMCS_LINK_POINTER, -1ull);
exec_control = vmcs12->pin_based_vm_exec_control;
/* Preemption timer setting is only taken from vmcs01. */
exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
exec_control |= vmcs_config.pin_based_exec_ctrl;
if (vmx->hv_deadline_tsc == -1)
exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
/* Posted interrupts setting is only taken from vmcs12. */
if (nested_cpu_has_posted_intr(vmcs12)) {
/*
* Note that we use L0's vector here and in
* vmx_deliver_nested_posted_interrupt.
*/
vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
vmx->nested.pi_pending = false;
vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
vmcs_write64(POSTED_INTR_DESC_ADDR,
page_to_phys(vmx->nested.pi_desc_page) +
(unsigned long)(vmcs12->posted_intr_desc_addr &
(PAGE_SIZE - 1)));
} else
exec_control &= ~PIN_BASED_POSTED_INTR;
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
vmx->nested.preemption_timer_expired = false;
if (nested_cpu_has_preemption_timer(vmcs12))
vmx_start_preemption_timer(vcpu);
/*
* Whether page-faults are trapped is determined by a combination of
* 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
* If enable_ept, L0 doesn't care about page faults and we should
* set all of these to L1's desires. However, if !enable_ept, L0 does
* care about (at least some) page faults, and because it is not easy
* (if at all possible?) to merge L0 and L1's desires, we simply ask
* to exit on each and every L2 page fault. This is done by setting
* MASK=MATCH=0 and (see below) EB.PF=1.
* Note that below we don't need special code to set EB.PF beyond the
* "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
* vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
* !enable_ept, EB.PF is 1, so the "or" will always be 1.
*
* A problem with this approach (when !enable_ept) is that L1 may be
* injected with more page faults than it asked for. This could have
* caused problems, but in practice existing hypervisors don't care.
* To fix this, we will need to emulate the PFEC checking (on the L1
* page tables), using walk_addr(), when injecting PFs to L1.
*/
vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
enable_ept ? vmcs12->page_fault_error_code_mask : 0);
vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
enable_ept ? vmcs12->page_fault_error_code_match : 0);
if (cpu_has_secondary_exec_ctrls()) {
exec_control = vmx_secondary_exec_control(vmx);
/* Take the following fields only from vmcs12 */
exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
SECONDARY_EXEC_RDTSCP |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
SECONDARY_EXEC_APIC_REGISTER_VIRT);
if (nested_cpu_has(vmcs12,
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
exec_control |= vmcs12->secondary_vm_exec_control;
if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
/*
* If translation failed, no matter: This feature asks
* to exit when accessing the given address, and if it
* can never be accessed, this feature won't do
* anything anyway.
*/
if (!vmx->nested.apic_access_page)
exec_control &=
~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
else
vmcs_write64(APIC_ACCESS_ADDR,
page_to_phys(vmx->nested.apic_access_page));
} else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
exec_control |=
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
kvm_vcpu_reload_apic_access_page(vcpu);
}
if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
vmcs_write64(EOI_EXIT_BITMAP0,
vmcs12->eoi_exit_bitmap0);
vmcs_write64(EOI_EXIT_BITMAP1,
vmcs12->eoi_exit_bitmap1);
vmcs_write64(EOI_EXIT_BITMAP2,
vmcs12->eoi_exit_bitmap2);
vmcs_write64(EOI_EXIT_BITMAP3,
vmcs12->eoi_exit_bitmap3);
vmcs_write16(GUEST_INTR_STATUS,
vmcs12->guest_intr_status);
}
nested_ept_enabled = (exec_control & SECONDARY_EXEC_ENABLE_EPT) != 0;
vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
}
/*
* Set host-state according to L0's settings (vmcs12 is irrelevant here)
* Some constant fields are set here by vmx_set_constant_host_state().
* Other fields are different per CPU, and will be set later when
* vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
*/
vmx_set_constant_host_state(vmx);
/*
* Set the MSR load/store lists to match L0's settings.
*/
vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
/*
* HOST_RSP is normally set correctly in vmx_vcpu_run() just before
* entry, but only if the current (host) sp changed from the value
* we wrote last (vmx->host_rsp). This cache is no longer relevant
* if we switch vmcs, and rather than hold a separate cache per vmcs,
* here we just force the write to happen on entry.
*/
vmx->host_rsp = 0;
exec_control = vmx_exec_control(vmx); /* L0's desires */
exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
exec_control &= ~CPU_BASED_TPR_SHADOW;
exec_control |= vmcs12->cpu_based_vm_exec_control;
if (exec_control & CPU_BASED_TPR_SHADOW) {
vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
page_to_phys(vmx->nested.virtual_apic_page));
vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
}
if (cpu_has_vmx_msr_bitmap() &&
exec_control & CPU_BASED_USE_MSR_BITMAPS &&
nested_vmx_merge_msr_bitmap(vcpu, vmcs12))
; /* MSR_BITMAP will be set by following vmx_set_efer. */
else
exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
/*
* Merging of IO bitmap not currently supported.
* Rather, exit every time.
*/
exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
exec_control |= CPU_BASED_UNCOND_IO_EXITING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
/* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
* bitwise-or of what L1 wants to trap for L2, and what we want to
* trap. Note that CR0.TS also needs updating - we do this later.
*/
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
/* L2->L1 exit controls are emulated - the hardware exit is to L0 so
* we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
* bits are further modified by vmx_set_efer() below.
*/
vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
/* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
* emulated by vmx_set_efer(), below.
*/
vm_entry_controls_init(vmx,
(vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
~VM_ENTRY_IA32E_MODE) |
(vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) {
vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
vcpu->arch.pat = vmcs12->guest_ia32_pat;
} else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
set_cr4_guest_host_mask(vmx);
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
vmcs_write64(TSC_OFFSET,
vcpu->arch.tsc_offset + vmcs12->tsc_offset);
else
vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
if (kvm_has_tsc_control)
decache_tsc_multiplier(vmx);
if (enable_vpid) {
/*
* There is no direct mapping between vpid02 and vpid12, the
* vpid02 is per-vCPU for L0 and reused while the value of
* vpid12 is changed w/ one invvpid during nested vmentry.
* The vpid12 is allocated by L1 for L2, so it will not
* influence global bitmap(for vpid01 and vpid02 allocation)
* even if spawn a lot of nested vCPUs.
*/
if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
vmx->nested.last_vpid = vmcs12->virtual_processor_id;
__vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
}
} else {
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
vmx_flush_tlb(vcpu);
}
}
if (nested_cpu_has_ept(vmcs12)) {
kvm_mmu_unload(vcpu);
nested_ept_init_mmu_context(vcpu);
}
/*
* This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
* TS bit (for lazy fpu) and bits which we consider mandatory enabled.
* The CR0_READ_SHADOW is what L2 should have expected to read given
* the specifications by L1; It's not enough to take
* vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
* have more bits than L1 expected.
*/
vmx_set_cr0(vcpu, vmcs12->guest_cr0);
vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
vmx_set_cr4(vcpu, vmcs12->guest_cr4);
vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
vcpu->arch.efer = vmcs12->guest_ia32_efer;
else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
vcpu->arch.efer |= (EFER_LMA | EFER_LME);
else
vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
/* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
vmx_set_efer(vcpu, vcpu->arch.efer);
/* Shadow page tables on either EPT or shadow page tables. */
if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_ept_enabled,
entry_failure_code))
return 1;
kvm_mmu_reset_context(vcpu);
if (!enable_ept)
vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
/*
* L1 may access the L2's PDPTR, so save them to construct vmcs12
*/
if (enable_ept) {
vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
}
kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
return 0;
}
/*
* nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
* for running an L2 nested guest.
*/
static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
{
struct vmcs12 *vmcs12;
struct vcpu_vmx *vmx = to_vmx(vcpu);
int cpu;
struct loaded_vmcs *vmcs02;
bool ia32e;
u32 msr_entry_idx;
unsigned long exit_qualification;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
goto out;
vmcs12 = get_vmcs12(vcpu);
if (enable_shadow_vmcs)
copy_shadow_to_vmcs12(vmx);
/*
* The nested entry process starts with enforcing various prerequisites
* on vmcs12 as required by the Intel SDM, and act appropriately when
* they fail: As the SDM explains, some conditions should cause the
* instruction to fail, while others will cause the instruction to seem
* to succeed, but return an EXIT_REASON_INVALID_STATE.
* To speed up the normal (success) code path, we should avoid checking
* for misconfigurations which will anyway be caught by the processor
* when using the merged vmcs02.
*/
if (vmcs12->launch_state == launch) {
nested_vmx_failValid(vcpu,
launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
: VMXERR_VMRESUME_NONLAUNCHED_VMCS);
goto out;
}
if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (!nested_get_vmcs12_pages(vcpu, vmcs12)) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12)) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (nested_vmx_check_apicv_controls(vcpu, vmcs12)) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12)) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
vmx->nested.nested_vmx_procbased_ctls_low,
vmx->nested.nested_vmx_procbased_ctls_high) ||
!vmx_control_verify(vmcs12->secondary_vm_exec_control,
vmx->nested.nested_vmx_secondary_ctls_low,
vmx->nested.nested_vmx_secondary_ctls_high) ||
!vmx_control_verify(vmcs12->pin_based_vm_exec_control,
vmx->nested.nested_vmx_pinbased_ctls_low,
vmx->nested.nested_vmx_pinbased_ctls_high) ||
!vmx_control_verify(vmcs12->vm_exit_controls,
vmx->nested.nested_vmx_exit_ctls_low,
vmx->nested.nested_vmx_exit_ctls_high) ||
!vmx_control_verify(vmcs12->vm_entry_controls,
vmx->nested.nested_vmx_entry_ctls_low,
vmx->nested.nested_vmx_entry_ctls_high))
{
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
!nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
!nested_cr3_valid(vcpu, vmcs12->host_cr3)) {
nested_vmx_failValid(vcpu,
VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
goto out;
}
if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
!nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4)) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
goto out;
}
if (vmcs12->vmcs_link_pointer != -1ull) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
goto out;
}
/*
* If the load IA32_EFER VM-entry control is 1, the following checks
* are performed on the field for the IA32_EFER MSR:
* - Bits reserved in the IA32_EFER MSR must be 0.
* - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
* the IA-32e mode guest VM-exit control. It must also be identical
* to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
* CR0.PG) is 1.
*/
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) {
ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
((vmcs12->guest_cr0 & X86_CR0_PG) &&
ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
goto out;
}
}
/*
* If the load IA32_EFER VM-exit control is 1, bits reserved in the
* IA32_EFER MSR must be 0 in the field for that register. In addition,
* the values of the LMA and LME bits in the field must each be that of
* the host address-space size VM-exit control.
*/
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
ia32e = (vmcs12->vm_exit_controls &
VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
goto out;
}
}
/*
* We're finally done with prerequisite checking, and can start with
* the nested entry.
*/
vmcs02 = nested_get_current_vmcs02(vmx);
if (!vmcs02)
return -ENOMEM;
/*
* After this point, the trap flag no longer triggers a singlestep trap
* on the vm entry instructions. Don't call
* kvm_skip_emulated_instruction.
*/
skip_emulated_instruction(vcpu);
enter_guest_mode(vcpu);
if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
cpu = get_cpu();
vmx->loaded_vmcs = vmcs02;
vmx_vcpu_put(vcpu);
vmx_vcpu_load(vcpu, cpu);
vcpu->cpu = cpu;
put_cpu();
vmx_segment_cache_clear(vmx);
if (prepare_vmcs02(vcpu, vmcs12, &exit_qualification)) {
leave_guest_mode(vcpu);
vmx_load_vmcs01(vcpu);
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, exit_qualification);
return 1;
}
msr_entry_idx = nested_vmx_load_msr(vcpu,
vmcs12->vm_entry_msr_load_addr,
vmcs12->vm_entry_msr_load_count);
if (msr_entry_idx) {
leave_guest_mode(vcpu);
vmx_load_vmcs01(vcpu);
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
return 1;
}
vmcs12->launch_state = 1;
if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
return kvm_vcpu_halt(vcpu);
vmx->nested.nested_run_pending = 1;
/*
* Note no nested_vmx_succeed or nested_vmx_fail here. At this point
* we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
* returned as far as L1 is concerned. It will only return (and set
* the success flag) when L2 exits (see nested_vmx_vmexit()).
*/
return 1;
out:
return kvm_skip_emulated_instruction(vcpu);
}
/*
* On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
* because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
* This function returns the new value we should put in vmcs12.guest_cr0.
* It's not enough to just return the vmcs02 GUEST_CR0. Rather,
* 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
* available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
* didn't trap the bit, because if L1 did, so would L0).
* 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
* been modified by L2, and L1 knows it. So just leave the old value of
* the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
* isn't relevant, because if L0 traps this bit it can set it to anything.
* 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
* changed these bits, and therefore they need to be updated, but L0
* didn't necessarily allow them to be changed in GUEST_CR0 - and rather
* put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
*/
static inline unsigned long
vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
{
return
/*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
/*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
/*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
vcpu->arch.cr0_guest_owned_bits));
}
static inline unsigned long
vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
{
return
/*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
/*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
/*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
vcpu->arch.cr4_guest_owned_bits));
}
static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
u32 idt_vectoring;
unsigned int nr;
if (vcpu->arch.exception.pending && vcpu->arch.exception.reinject) {
nr = vcpu->arch.exception.nr;
idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
if (kvm_exception_is_soft(nr)) {
vmcs12->vm_exit_instruction_len =
vcpu->arch.event_exit_inst_len;
idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
} else
idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
if (vcpu->arch.exception.has_error_code) {
idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
vmcs12->idt_vectoring_error_code =
vcpu->arch.exception.error_code;
}
vmcs12->idt_vectoring_info_field = idt_vectoring;
} else if (vcpu->arch.nmi_injected) {
vmcs12->idt_vectoring_info_field =
INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
} else if (vcpu->arch.interrupt.pending) {
nr = vcpu->arch.interrupt.nr;
idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
if (vcpu->arch.interrupt.soft) {
idt_vectoring |= INTR_TYPE_SOFT_INTR;
vmcs12->vm_entry_instruction_len =
vcpu->arch.event_exit_inst_len;
} else
idt_vectoring |= INTR_TYPE_EXT_INTR;
vmcs12->idt_vectoring_info_field = idt_vectoring;
}
}
static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
vmx->nested.preemption_timer_expired) {
if (vmx->nested.nested_run_pending)
return -EBUSY;
nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
return 0;
}
if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
if (vmx->nested.nested_run_pending ||
vcpu->arch.interrupt.pending)
return -EBUSY;
nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
NMI_VECTOR | INTR_TYPE_NMI_INTR |
INTR_INFO_VALID_MASK, 0);
/*
* The NMI-triggered VM exit counts as injection:
* clear this one and block further NMIs.
*/
vcpu->arch.nmi_pending = 0;
vmx_set_nmi_mask(vcpu, true);
return 0;
}
if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
nested_exit_on_intr(vcpu)) {
if (vmx->nested.nested_run_pending)
return -EBUSY;
nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
return 0;
}
return vmx_complete_nested_posted_interrupt(vcpu);
}
static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
{
ktime_t remaining =
hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
u64 value;
if (ktime_to_ns(remaining) <= 0)
return 0;
value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
do_div(value, 1000000);
return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
}
/*
* prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
* and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
* and this function updates it to reflect the changes to the guest state while
* L2 was running (and perhaps made some exits which were handled directly by L0
* without going back to L1), and to reflect the exit reason.
* Note that we do not have to copy here all VMCS fields, just those that
* could have changed by the L2 guest or the exit - i.e., the guest-state and
* exit-information fields only. Other fields are modified by L1 with VMWRITE,
* which already writes to vmcs12 directly.
*/
static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
u32 exit_reason, u32 exit_intr_info,
unsigned long exit_qualification)
{
/* update guest state fields: */
vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
vmcs12->guest_interruptibility_info =
vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
vmcs12->guest_pending_dbg_exceptions =
vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
else
vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
if (nested_cpu_has_preemption_timer(vmcs12)) {
if (vmcs12->vm_exit_controls &
VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
vmcs12->vmx_preemption_timer_value =
vmx_get_preemption_timer_value(vcpu);
hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
}
/*
* In some cases (usually, nested EPT), L2 is allowed to change its
* own CR3 without exiting. If it has changed it, we must keep it.
* Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
* by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
*
* Additionally, restore L2's PDPTR to vmcs12.
*/
if (enable_ept) {
vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
}
if (nested_cpu_has_ept(vmcs12))
vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
if (nested_cpu_has_vid(vmcs12))
vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
vmcs12->vm_entry_controls =
(vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
(vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
}
/* TODO: These cannot have changed unless we have MSR bitmaps and
* the relevant bit asks not to trap the change */
if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
vmcs12->guest_ia32_efer = vcpu->arch.efer;
vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
if (kvm_mpx_supported())
vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
if (nested_cpu_has_xsaves(vmcs12))
vmcs12->xss_exit_bitmap = vmcs_read64(XSS_EXIT_BITMAP);
/* update exit information fields: */
vmcs12->vm_exit_reason = exit_reason;
vmcs12->exit_qualification = exit_qualification;
vmcs12->vm_exit_intr_info = exit_intr_info;
if ((vmcs12->vm_exit_intr_info &
(INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
(INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK))
vmcs12->vm_exit_intr_error_code =
vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
vmcs12->idt_vectoring_info_field = 0;
vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
/* vm_entry_intr_info_field is cleared on exit. Emulate this
* instead of reading the real value. */
vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
/*
* Transfer the event that L0 or L1 may wanted to inject into
* L2 to IDT_VECTORING_INFO_FIELD.
*/
vmcs12_save_pending_event(vcpu, vmcs12);
}
/*
* Drop what we picked up for L2 via vmx_complete_interrupts. It is
* preserved above and would only end up incorrectly in L1.
*/
vcpu->arch.nmi_injected = false;
kvm_clear_exception_queue(vcpu);
kvm_clear_interrupt_queue(vcpu);
}
/*
* A part of what we need to when the nested L2 guest exits and we want to
* run its L1 parent, is to reset L1's guest state to the host state specified
* in vmcs12.
* This function is to be called not only on normal nested exit, but also on
* a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
* Failures During or After Loading Guest State").
* This function should be called when the active VMCS is L1's (vmcs01).
*/
static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
struct kvm_segment seg;
unsigned long entry_failure_code;
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
vcpu->arch.efer = vmcs12->host_ia32_efer;
else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
vcpu->arch.efer |= (EFER_LMA | EFER_LME);
else
vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
vmx_set_efer(vcpu, vcpu->arch.efer);
kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
/*
* Note that calling vmx_set_cr0 is important, even if cr0 hasn't
* actually changed, because it depends on the current state of
* fpu_active (which may have changed).
* Note that vmx_set_cr0 refers to efer set above.
*/
vmx_set_cr0(vcpu, vmcs12->host_cr0);
/*
* If we did fpu_activate()/fpu_deactivate() during L2's run, we need
* to apply the same changes to L1's vmcs. We just set cr0 correctly,
* but we also need to update cr0_guest_host_mask and exception_bitmap.
*/
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
/*
* Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
* (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
*/
vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
kvm_set_cr4(vcpu, vmcs12->host_cr4);
nested_ept_uninit_mmu_context(vcpu);
/*
* Only PDPTE load can fail as the value of cr3 was checked on entry and
* couldn't have changed.
*/
if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
if (!enable_ept)
vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
if (enable_vpid) {
/*
* Trivially support vpid by letting L2s share their parent
* L1's vpid. TODO: move to a more elaborate solution, giving
* each L2 its own vpid and exposing the vpid feature to L1.
*/
vmx_flush_tlb(vcpu);
}
vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
/* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
vmcs_write64(GUEST_BNDCFGS, 0);
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
vcpu->arch.pat = vmcs12->host_ia32_pat;
}
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
vmcs12->host_ia32_perf_global_ctrl);
/* Set L1 segment info according to Intel SDM
27.5.2 Loading Host Segment and Descriptor-Table Registers */
seg = (struct kvm_segment) {
.base = 0,
.limit = 0xFFFFFFFF,
.selector = vmcs12->host_cs_selector,
.type = 11,
.present = 1,
.s = 1,
.g = 1
};
if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
seg.l = 1;
else
seg.db = 1;
vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
seg = (struct kvm_segment) {
.base = 0,
.limit = 0xFFFFFFFF,
.type = 3,
.present = 1,
.s = 1,
.db = 1,
.g = 1
};
seg.selector = vmcs12->host_ds_selector;
vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
seg.selector = vmcs12->host_es_selector;
vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
seg.selector = vmcs12->host_ss_selector;
vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
seg.selector = vmcs12->host_fs_selector;
seg.base = vmcs12->host_fs_base;
vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
seg.selector = vmcs12->host_gs_selector;
seg.base = vmcs12->host_gs_base;
vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
seg = (struct kvm_segment) {
.base = vmcs12->host_tr_base,
.limit = 0x67,
.selector = vmcs12->host_tr_selector,
.type = 11,
.present = 1
};
vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
kvm_set_dr(vcpu, 7, 0x400);
vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
if (cpu_has_vmx_msr_bitmap())
vmx_set_msr_bitmap(vcpu);
if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
vmcs12->vm_exit_msr_load_count))
nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
}
/*
* Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
* and modify vmcs12 to make it see what it would expect to see there if
* L2 was its real guest. Must only be called when in L2 (is_guest_mode())
*/
static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
u32 exit_intr_info,
unsigned long exit_qualification)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
u32 vm_inst_error = 0;
/* trying to cancel vmlaunch/vmresume is a bug */
WARN_ON_ONCE(vmx->nested.nested_run_pending);
leave_guest_mode(vcpu);
prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
exit_qualification);
if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
vmcs12->vm_exit_msr_store_count))
nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
if (unlikely(vmx->fail))
vm_inst_error = vmcs_read32(VM_INSTRUCTION_ERROR);
vmx_load_vmcs01(vcpu);
if ((exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
&& nested_exit_intr_ack_set(vcpu)) {
int irq = kvm_cpu_get_interrupt(vcpu);
WARN_ON(irq < 0);
vmcs12->vm_exit_intr_info = irq |
INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
}
trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
vmcs12->exit_qualification,
vmcs12->idt_vectoring_info_field,
vmcs12->vm_exit_intr_info,
vmcs12->vm_exit_intr_error_code,
KVM_ISA_VMX);
vm_entry_controls_reset_shadow(vmx);
vm_exit_controls_reset_shadow(vmx);
vmx_segment_cache_clear(vmx);
/* if no vmcs02 cache requested, remove the one we used */
if (VMCS02_POOL_SIZE == 0)
nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
load_vmcs12_host_state(vcpu, vmcs12);
/* Update any VMCS fields that might have changed while L2 ran */
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
if (vmx->hv_deadline_tsc == -1)
vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
PIN_BASED_VMX_PREEMPTION_TIMER);
else
vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
PIN_BASED_VMX_PREEMPTION_TIMER);
if (kvm_has_tsc_control)
decache_tsc_multiplier(vmx);
if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
vmx_set_virtual_x2apic_mode(vcpu,
vcpu->arch.apic_base & X2APIC_ENABLE);
}
/* This is needed for same reason as it was needed in prepare_vmcs02 */
vmx->host_rsp = 0;
/* Unpin physical memory we referred to in vmcs02 */
if (vmx->nested.apic_access_page) {
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page = NULL;
}
if (vmx->nested.virtual_apic_page) {
nested_release_page(vmx->nested.virtual_apic_page);
vmx->nested.virtual_apic_page = NULL;
}
if (vmx->nested.pi_desc_page) {
kunmap(vmx->nested.pi_desc_page);
nested_release_page(vmx->nested.pi_desc_page);
vmx->nested.pi_desc_page = NULL;
vmx->nested.pi_desc = NULL;
}
/*
* We are now running in L2, mmu_notifier will force to reload the
* page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
*/
kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
/*
* Exiting from L2 to L1, we're now back to L1 which thinks it just
* finished a VMLAUNCH or VMRESUME instruction, so we need to set the
* success or failure flag accordingly.
*/
if (unlikely(vmx->fail)) {
vmx->fail = 0;
nested_vmx_failValid(vcpu, vm_inst_error);
} else
nested_vmx_succeed(vcpu);
if (enable_shadow_vmcs)
vmx->nested.sync_shadow_vmcs = true;
/* in case we halted in L2 */
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
}
/*
* Forcibly leave nested mode in order to be able to reset the VCPU later on.
*/
static void vmx_leave_nested(struct kvm_vcpu *vcpu)
{
if (is_guest_mode(vcpu))
nested_vmx_vmexit(vcpu, -1, 0, 0);
free_nested(to_vmx(vcpu));
}
/*
* L1's failure to enter L2 is a subset of a normal exit, as explained in
* 23.7 "VM-entry failures during or after loading guest state" (this also
* lists the acceptable exit-reason and exit-qualification parameters).
* It should only be called before L2 actually succeeded to run, and when
* vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
*/
static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12,
u32 reason, unsigned long qualification)
{
load_vmcs12_host_state(vcpu, vmcs12);
vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
vmcs12->exit_qualification = qualification;
nested_vmx_succeed(vcpu);
if (enable_shadow_vmcs)
to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
}
static int vmx_check_intercept(struct kvm_vcpu *vcpu,
struct x86_instruction_info *info,
enum x86_intercept_stage stage)
{
return X86EMUL_CONTINUE;
}
#ifdef CONFIG_X86_64
/* (a << shift) / divisor, return 1 if overflow otherwise 0 */
static inline int u64_shl_div_u64(u64 a, unsigned int shift,
u64 divisor, u64 *result)
{
u64 low = a << shift, high = a >> (64 - shift);
/* To avoid the overflow on divq */
if (high >= divisor)
return 1;
/* Low hold the result, high hold rem which is discarded */
asm("divq %2\n\t" : "=a" (low), "=d" (high) :
"rm" (divisor), "0" (low), "1" (high));
*result = low;
return 0;
}
static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 tscl = rdtsc();
u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
/* Convert to host delta tsc if tsc scaling is enabled */
if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
u64_shl_div_u64(delta_tsc,
kvm_tsc_scaling_ratio_frac_bits,
vcpu->arch.tsc_scaling_ratio,
&delta_tsc))
return -ERANGE;
/*
* If the delta tsc can't fit in the 32 bit after the multi shift,
* we can't use the preemption timer.
* It's possible that it fits on later vmentries, but checking
* on every vmentry is costly so we just use an hrtimer.
*/
if (delta_tsc >> (cpu_preemption_timer_multi + 32))
return -ERANGE;
vmx->hv_deadline_tsc = tscl + delta_tsc;
vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
PIN_BASED_VMX_PREEMPTION_TIMER);
return 0;
}
static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmx->hv_deadline_tsc = -1;
vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
PIN_BASED_VMX_PREEMPTION_TIMER);
}
#endif
static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
{
if (ple_gap)
shrink_ple_window(vcpu);
}
static void vmx_slot_enable_log_dirty(struct kvm *kvm,
struct kvm_memory_slot *slot)
{
kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
}
static void vmx_slot_disable_log_dirty(struct kvm *kvm,
struct kvm_memory_slot *slot)
{
kvm_mmu_slot_set_dirty(kvm, slot);
}
static void vmx_flush_log_dirty(struct kvm *kvm)
{
kvm_flush_pml_buffers(kvm);
}
static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
struct kvm_memory_slot *memslot,
gfn_t offset, unsigned long mask)
{
kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
}
/*
* This routine does the following things for vCPU which is going
* to be blocked if VT-d PI is enabled.
* - Store the vCPU to the wakeup list, so when interrupts happen
* we can find the right vCPU to wake up.
* - Change the Posted-interrupt descriptor as below:
* 'NDST' <-- vcpu->pre_pcpu
* 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
* - If 'ON' is set during this process, which means at least one
* interrupt is posted for this vCPU, we cannot block it, in
* this case, return 1, otherwise, return 0.
*
*/
static int pi_pre_block(struct kvm_vcpu *vcpu)
{
unsigned long flags;
unsigned int dest;
struct pi_desc old, new;
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(vcpu))
return 0;
vcpu->pre_pcpu = vcpu->cpu;
spin_lock_irqsave(&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
list_add_tail(&vcpu->blocked_vcpu_list,
&per_cpu(blocked_vcpu_on_cpu,
vcpu->pre_pcpu));
spin_unlock_irqrestore(&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
do {
old.control = new.control = pi_desc->control;
/*
* We should not block the vCPU if
* an interrupt is posted for it.
*/
if (pi_test_on(pi_desc) == 1) {
spin_lock_irqsave(&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
list_del(&vcpu->blocked_vcpu_list);
spin_unlock_irqrestore(
&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
vcpu->pre_pcpu = -1;
return 1;
}
WARN((pi_desc->sn == 1),
"Warning: SN field of posted-interrupts "
"is set before blocking\n");
/*
* Since vCPU can be preempted during this process,
* vcpu->cpu could be different with pre_pcpu, we
* need to set pre_pcpu as the destination of wakeup
* notification event, then we can find the right vCPU
* to wakeup in wakeup handler if interrupts happen
* when the vCPU is in blocked state.
*/
dest = cpu_physical_id(vcpu->pre_pcpu);
if (x2apic_enabled())
new.ndst = dest;
else
new.ndst = (dest << 8) & 0xFF00;
/* set 'NV' to 'wakeup vector' */
new.nv = POSTED_INTR_WAKEUP_VECTOR;
} while (cmpxchg(&pi_desc->control, old.control,
new.control) != old.control);
return 0;
}
static int vmx_pre_block(struct kvm_vcpu *vcpu)
{
if (pi_pre_block(vcpu))
return 1;
if (kvm_lapic_hv_timer_in_use(vcpu))
kvm_lapic_switch_to_sw_timer(vcpu);
return 0;
}
static void pi_post_block(struct kvm_vcpu *vcpu)
{
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
struct pi_desc old, new;
unsigned int dest;
unsigned long flags;
if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(vcpu))
return;
do {
old.control = new.control = pi_desc->control;
dest = cpu_physical_id(vcpu->cpu);
if (x2apic_enabled())
new.ndst = dest;
else
new.ndst = (dest << 8) & 0xFF00;
/* Allow posting non-urgent interrupts */
new.sn = 0;
/* set 'NV' to 'notification vector' */
new.nv = POSTED_INTR_VECTOR;
} while (cmpxchg(&pi_desc->control, old.control,
new.control) != old.control);
if(vcpu->pre_pcpu != -1) {
spin_lock_irqsave(
&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
list_del(&vcpu->blocked_vcpu_list);
spin_unlock_irqrestore(
&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
vcpu->pre_pcpu = -1;
}
}
static void vmx_post_block(struct kvm_vcpu *vcpu)
{
if (kvm_x86_ops->set_hv_timer)
kvm_lapic_switch_to_hv_timer(vcpu);
pi_post_block(vcpu);
}
/*
* vmx_update_pi_irte - set IRTE for Posted-Interrupts
*
* @kvm: kvm
* @host_irq: host irq of the interrupt
* @guest_irq: gsi of the interrupt
* @set: set or unset PI
* returns 0 on success, < 0 on failure
*/
static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
uint32_t guest_irq, bool set)
{
struct kvm_kernel_irq_routing_entry *e;
struct kvm_irq_routing_table *irq_rt;
struct kvm_lapic_irq irq;
struct kvm_vcpu *vcpu;
struct vcpu_data vcpu_info;
int idx, ret = -EINVAL;
if (!kvm_arch_has_assigned_device(kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(kvm->vcpus[0]))
return 0;
idx = srcu_read_lock(&kvm->irq_srcu);
irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
BUG_ON(guest_irq >= irq_rt->nr_rt_entries);
hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
if (e->type != KVM_IRQ_ROUTING_MSI)
continue;
/*
* VT-d PI cannot support posting multicast/broadcast
* interrupts to a vCPU, we still use interrupt remapping
* for these kind of interrupts.
*
* For lowest-priority interrupts, we only support
* those with single CPU as the destination, e.g. user
* configures the interrupts via /proc/irq or uses
* irqbalance to make the interrupts single-CPU.
*
* We will support full lowest-priority interrupt later.
*/
kvm_set_msi_irq(kvm, e, &irq);
if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
/*
* Make sure the IRTE is in remapped mode if
* we don't handle it in posted mode.
*/
ret = irq_set_vcpu_affinity(host_irq, NULL);
if (ret < 0) {
printk(KERN_INFO
"failed to back to remapped mode, irq: %u\n",
host_irq);
goto out;
}
continue;
}
vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
vcpu_info.vector = irq.vector;
trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
vcpu_info.vector, vcpu_info.pi_desc_addr, set);
if (set)
ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
else {
/* suppress notification event before unposting */
pi_set_sn(vcpu_to_pi_desc(vcpu));
ret = irq_set_vcpu_affinity(host_irq, NULL);
pi_clear_sn(vcpu_to_pi_desc(vcpu));
}
if (ret < 0) {
printk(KERN_INFO "%s: failed to update PI IRTE\n",
__func__);
goto out;
}
}
ret = 0;
out:
srcu_read_unlock(&kvm->irq_srcu, idx);
return ret;
}
static void vmx_setup_mce(struct kvm_vcpu *vcpu)
{
if (vcpu->arch.mcg_cap & MCG_LMCE_P)
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
FEATURE_CONTROL_LMCE;
else
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
~FEATURE_CONTROL_LMCE;
}
static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
.cpu_has_kvm_support = cpu_has_kvm_support,
.disabled_by_bios = vmx_disabled_by_bios,
.hardware_setup = hardware_setup,
.hardware_unsetup = hardware_unsetup,
.check_processor_compatibility = vmx_check_processor_compat,
.hardware_enable = hardware_enable,
.hardware_disable = hardware_disable,
.cpu_has_accelerated_tpr = report_flexpriority,
.cpu_has_high_real_mode_segbase = vmx_has_high_real_mode_segbase,
.vcpu_create = vmx_create_vcpu,
.vcpu_free = vmx_free_vcpu,
.vcpu_reset = vmx_vcpu_reset,
.prepare_guest_switch = vmx_save_host_state,
.vcpu_load = vmx_vcpu_load,
.vcpu_put = vmx_vcpu_put,
.update_bp_intercept = update_exception_bitmap,
.get_msr = vmx_get_msr,
.set_msr = vmx_set_msr,
.get_segment_base = vmx_get_segment_base,
.get_segment = vmx_get_segment,
.set_segment = vmx_set_segment,
.get_cpl = vmx_get_cpl,
.get_cs_db_l_bits = vmx_get_cs_db_l_bits,
.decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
.decache_cr3 = vmx_decache_cr3,
.decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
.set_cr0 = vmx_set_cr0,
.set_cr3 = vmx_set_cr3,
.set_cr4 = vmx_set_cr4,
.set_efer = vmx_set_efer,
.get_idt = vmx_get_idt,
.set_idt = vmx_set_idt,
.get_gdt = vmx_get_gdt,
.set_gdt = vmx_set_gdt,
.get_dr6 = vmx_get_dr6,
.set_dr6 = vmx_set_dr6,
.set_dr7 = vmx_set_dr7,
.sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
.cache_reg = vmx_cache_reg,
.get_rflags = vmx_get_rflags,
.set_rflags = vmx_set_rflags,
.get_pkru = vmx_get_pkru,
.fpu_activate = vmx_fpu_activate,
.fpu_deactivate = vmx_fpu_deactivate,
.tlb_flush = vmx_flush_tlb,
.run = vmx_vcpu_run,
.handle_exit = vmx_handle_exit,
.skip_emulated_instruction = skip_emulated_instruction,
.set_interrupt_shadow = vmx_set_interrupt_shadow,
.get_interrupt_shadow = vmx_get_interrupt_shadow,
.patch_hypercall = vmx_patch_hypercall,
.set_irq = vmx_inject_irq,
.set_nmi = vmx_inject_nmi,
.queue_exception = vmx_queue_exception,
.cancel_injection = vmx_cancel_injection,
.interrupt_allowed = vmx_interrupt_allowed,
.nmi_allowed = vmx_nmi_allowed,
.get_nmi_mask = vmx_get_nmi_mask,
.set_nmi_mask = vmx_set_nmi_mask,
.enable_nmi_window = enable_nmi_window,
.enable_irq_window = enable_irq_window,
.update_cr8_intercept = update_cr8_intercept,
.set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
.set_apic_access_page_addr = vmx_set_apic_access_page_addr,
.get_enable_apicv = vmx_get_enable_apicv,
.refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
.load_eoi_exitmap = vmx_load_eoi_exitmap,
.hwapic_irr_update = vmx_hwapic_irr_update,
.hwapic_isr_update = vmx_hwapic_isr_update,
.sync_pir_to_irr = vmx_sync_pir_to_irr,
.deliver_posted_interrupt = vmx_deliver_posted_interrupt,
.set_tss_addr = vmx_set_tss_addr,
.get_tdp_level = get_ept_level,
.get_mt_mask = vmx_get_mt_mask,
.get_exit_info = vmx_get_exit_info,
.get_lpage_level = vmx_get_lpage_level,
.cpuid_update = vmx_cpuid_update,
.rdtscp_supported = vmx_rdtscp_supported,
.invpcid_supported = vmx_invpcid_supported,
.set_supported_cpuid = vmx_set_supported_cpuid,
.has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
.write_tsc_offset = vmx_write_tsc_offset,
.set_tdp_cr3 = vmx_set_cr3,
.check_intercept = vmx_check_intercept,
.handle_external_intr = vmx_handle_external_intr,
.mpx_supported = vmx_mpx_supported,
.xsaves_supported = vmx_xsaves_supported,
.check_nested_events = vmx_check_nested_events,
.sched_in = vmx_sched_in,
.slot_enable_log_dirty = vmx_slot_enable_log_dirty,
.slot_disable_log_dirty = vmx_slot_disable_log_dirty,
.flush_log_dirty = vmx_flush_log_dirty,
.enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
.pre_block = vmx_pre_block,
.post_block = vmx_post_block,
.pmu_ops = &intel_pmu_ops,
.update_pi_irte = vmx_update_pi_irte,
#ifdef CONFIG_X86_64
.set_hv_timer = vmx_set_hv_timer,
.cancel_hv_timer = vmx_cancel_hv_timer,
#endif
.setup_mce = vmx_setup_mce,
};
static int __init vmx_init(void)
{
int r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
__alignof__(struct vcpu_vmx), THIS_MODULE);
if (r)
return r;
#ifdef CONFIG_KEXEC_CORE
rcu_assign_pointer(crash_vmclear_loaded_vmcss,
crash_vmclear_local_loaded_vmcss);
#endif
return 0;
}
static void __exit vmx_exit(void)
{
#ifdef CONFIG_KEXEC_CORE
RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
synchronize_rcu();
#endif
kvm_exit();
}
module_init(vmx_init)
module_exit(vmx_exit)
| ./CrossVul/dataset_final_sorted/CWE-388/c/bad_5494_0 |
crossvul-cpp_data_bad_3289_0 | /*
* Simple NUMA memory policy for the Linux kernel.
*
* Copyright 2003,2004 Andi Kleen, SuSE Labs.
* (C) Copyright 2005 Christoph Lameter, Silicon Graphics, Inc.
* Subject to the GNU Public License, version 2.
*
* NUMA policy allows the user to give hints in which node(s) memory should
* be allocated.
*
* Support four policies per VMA and per process:
*
* The VMA policy has priority over the process policy for a page fault.
*
* interleave Allocate memory interleaved over a set of nodes,
* with normal fallback if it fails.
* For VMA based allocations this interleaves based on the
* offset into the backing object or offset into the mapping
* for anonymous memory. For process policy an process counter
* is used.
*
* bind Only allocate memory on a specific set of nodes,
* no fallback.
* FIXME: memory is allocated starting with the first node
* to the last. It would be better if bind would truly restrict
* the allocation to memory nodes instead
*
* preferred Try a specific node first before normal fallback.
* As a special case NUMA_NO_NODE here means do the allocation
* on the local CPU. This is normally identical to default,
* but useful to set in a VMA when you have a non default
* process policy.
*
* default Allocate on the local node first, or when on a VMA
* use the process policy. This is what Linux always did
* in a NUMA aware kernel and still does by, ahem, default.
*
* The process policy is applied for most non interrupt memory allocations
* in that process' context. Interrupts ignore the policies and always
* try to allocate on the local CPU. The VMA policy is only applied for memory
* allocations for a VMA in the VM.
*
* Currently there are a few corner cases in swapping where the policy
* is not applied, but the majority should be handled. When process policy
* is used it is not remembered over swap outs/swap ins.
*
* Only the highest zone in the zone hierarchy gets policied. Allocations
* requesting a lower zone just use default policy. This implies that
* on systems with highmem kernel lowmem allocation don't get policied.
* Same with GFP_DMA allocations.
*
* For shmfs/tmpfs/hugetlbfs shared memory the policy is shared between
* all users and remembered even when nobody has memory mapped.
*/
/* Notebook:
fix mmap readahead to honour policy and enable policy for any page cache
object
statistics for bigpages
global policy for page cache? currently it uses process policy. Requires
first item above.
handle mremap for shared memory (currently ignored for the policy)
grows down?
make bind policy root only? It can trigger oom much faster and the
kernel is not always grateful with that.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/mempolicy.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/hugetlb.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/sched/mm.h>
#include <linux/sched/numa_balancing.h>
#include <linux/sched/task.h>
#include <linux/nodemask.h>
#include <linux/cpuset.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/export.h>
#include <linux/nsproxy.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/compat.h>
#include <linux/swap.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/migrate.h>
#include <linux/ksm.h>
#include <linux/rmap.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/ctype.h>
#include <linux/mm_inline.h>
#include <linux/mmu_notifier.h>
#include <linux/printk.h>
#include <asm/tlbflush.h>
#include <linux/uaccess.h>
#include "internal.h"
/* Internal flags */
#define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0) /* Skip checks for continuous vmas */
#define MPOL_MF_INVERT (MPOL_MF_INTERNAL << 1) /* Invert check for nodemask */
static struct kmem_cache *policy_cache;
static struct kmem_cache *sn_cache;
/* Highest zone. An specific allocation for a zone below that is not
policied. */
enum zone_type policy_zone = 0;
/*
* run-time system-wide default policy => local allocation
*/
static struct mempolicy default_policy = {
.refcnt = ATOMIC_INIT(1), /* never free it */
.mode = MPOL_PREFERRED,
.flags = MPOL_F_LOCAL,
};
static struct mempolicy preferred_node_policy[MAX_NUMNODES];
struct mempolicy *get_task_policy(struct task_struct *p)
{
struct mempolicy *pol = p->mempolicy;
int node;
if (pol)
return pol;
node = numa_node_id();
if (node != NUMA_NO_NODE) {
pol = &preferred_node_policy[node];
/* preferred_node_policy is not initialised early in boot */
if (pol->mode)
return pol;
}
return &default_policy;
}
static const struct mempolicy_operations {
int (*create)(struct mempolicy *pol, const nodemask_t *nodes);
/*
* If read-side task has no lock to protect task->mempolicy, write-side
* task will rebind the task->mempolicy by two step. The first step is
* setting all the newly nodes, and the second step is cleaning all the
* disallowed nodes. In this way, we can avoid finding no node to alloc
* page.
* If we have a lock to protect task->mempolicy in read-side, we do
* rebind directly.
*
* step:
* MPOL_REBIND_ONCE - do rebind work at once
* MPOL_REBIND_STEP1 - set all the newly nodes
* MPOL_REBIND_STEP2 - clean all the disallowed nodes
*/
void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes,
enum mpol_rebind_step step);
} mpol_ops[MPOL_MAX];
static inline int mpol_store_user_nodemask(const struct mempolicy *pol)
{
return pol->flags & MPOL_MODE_FLAGS;
}
static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig,
const nodemask_t *rel)
{
nodemask_t tmp;
nodes_fold(tmp, *orig, nodes_weight(*rel));
nodes_onto(*ret, tmp, *rel);
}
static int mpol_new_interleave(struct mempolicy *pol, const nodemask_t *nodes)
{
if (nodes_empty(*nodes))
return -EINVAL;
pol->v.nodes = *nodes;
return 0;
}
static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes)
{
if (!nodes)
pol->flags |= MPOL_F_LOCAL; /* local allocation */
else if (nodes_empty(*nodes))
return -EINVAL; /* no allowed nodes */
else
pol->v.preferred_node = first_node(*nodes);
return 0;
}
static int mpol_new_bind(struct mempolicy *pol, const nodemask_t *nodes)
{
if (nodes_empty(*nodes))
return -EINVAL;
pol->v.nodes = *nodes;
return 0;
}
/*
* mpol_set_nodemask is called after mpol_new() to set up the nodemask, if
* any, for the new policy. mpol_new() has already validated the nodes
* parameter with respect to the policy mode and flags. But, we need to
* handle an empty nodemask with MPOL_PREFERRED here.
*
* Must be called holding task's alloc_lock to protect task's mems_allowed
* and mempolicy. May also be called holding the mmap_semaphore for write.
*/
static int mpol_set_nodemask(struct mempolicy *pol,
const nodemask_t *nodes, struct nodemask_scratch *nsc)
{
int ret;
/* if mode is MPOL_DEFAULT, pol is NULL. This is right. */
if (pol == NULL)
return 0;
/* Check N_MEMORY */
nodes_and(nsc->mask1,
cpuset_current_mems_allowed, node_states[N_MEMORY]);
VM_BUG_ON(!nodes);
if (pol->mode == MPOL_PREFERRED && nodes_empty(*nodes))
nodes = NULL; /* explicit local allocation */
else {
if (pol->flags & MPOL_F_RELATIVE_NODES)
mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1);
else
nodes_and(nsc->mask2, *nodes, nsc->mask1);
if (mpol_store_user_nodemask(pol))
pol->w.user_nodemask = *nodes;
else
pol->w.cpuset_mems_allowed =
cpuset_current_mems_allowed;
}
if (nodes)
ret = mpol_ops[pol->mode].create(pol, &nsc->mask2);
else
ret = mpol_ops[pol->mode].create(pol, NULL);
return ret;
}
/*
* This function just creates a new policy, does some check and simple
* initialization. You must invoke mpol_set_nodemask() to set nodes.
*/
static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags,
nodemask_t *nodes)
{
struct mempolicy *policy;
pr_debug("setting mode %d flags %d nodes[0] %lx\n",
mode, flags, nodes ? nodes_addr(*nodes)[0] : NUMA_NO_NODE);
if (mode == MPOL_DEFAULT) {
if (nodes && !nodes_empty(*nodes))
return ERR_PTR(-EINVAL);
return NULL;
}
VM_BUG_ON(!nodes);
/*
* MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or
* MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation).
* All other modes require a valid pointer to a non-empty nodemask.
*/
if (mode == MPOL_PREFERRED) {
if (nodes_empty(*nodes)) {
if (((flags & MPOL_F_STATIC_NODES) ||
(flags & MPOL_F_RELATIVE_NODES)))
return ERR_PTR(-EINVAL);
}
} else if (mode == MPOL_LOCAL) {
if (!nodes_empty(*nodes) ||
(flags & MPOL_F_STATIC_NODES) ||
(flags & MPOL_F_RELATIVE_NODES))
return ERR_PTR(-EINVAL);
mode = MPOL_PREFERRED;
} else if (nodes_empty(*nodes))
return ERR_PTR(-EINVAL);
policy = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!policy)
return ERR_PTR(-ENOMEM);
atomic_set(&policy->refcnt, 1);
policy->mode = mode;
policy->flags = flags;
return policy;
}
/* Slow path of a mpol destructor. */
void __mpol_put(struct mempolicy *p)
{
if (!atomic_dec_and_test(&p->refcnt))
return;
kmem_cache_free(policy_cache, p);
}
static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes,
enum mpol_rebind_step step)
{
}
/*
* step:
* MPOL_REBIND_ONCE - do rebind work at once
* MPOL_REBIND_STEP1 - set all the newly nodes
* MPOL_REBIND_STEP2 - clean all the disallowed nodes
*/
static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes,
enum mpol_rebind_step step)
{
nodemask_t tmp;
if (pol->flags & MPOL_F_STATIC_NODES)
nodes_and(tmp, pol->w.user_nodemask, *nodes);
else if (pol->flags & MPOL_F_RELATIVE_NODES)
mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
else {
/*
* if step == 1, we use ->w.cpuset_mems_allowed to cache the
* result
*/
if (step == MPOL_REBIND_ONCE || step == MPOL_REBIND_STEP1) {
nodes_remap(tmp, pol->v.nodes,
pol->w.cpuset_mems_allowed, *nodes);
pol->w.cpuset_mems_allowed = step ? tmp : *nodes;
} else if (step == MPOL_REBIND_STEP2) {
tmp = pol->w.cpuset_mems_allowed;
pol->w.cpuset_mems_allowed = *nodes;
} else
BUG();
}
if (nodes_empty(tmp))
tmp = *nodes;
if (step == MPOL_REBIND_STEP1)
nodes_or(pol->v.nodes, pol->v.nodes, tmp);
else if (step == MPOL_REBIND_ONCE || step == MPOL_REBIND_STEP2)
pol->v.nodes = tmp;
else
BUG();
if (!node_isset(current->il_next, tmp)) {
current->il_next = next_node_in(current->il_next, tmp);
if (current->il_next >= MAX_NUMNODES)
current->il_next = numa_node_id();
}
}
static void mpol_rebind_preferred(struct mempolicy *pol,
const nodemask_t *nodes,
enum mpol_rebind_step step)
{
nodemask_t tmp;
if (pol->flags & MPOL_F_STATIC_NODES) {
int node = first_node(pol->w.user_nodemask);
if (node_isset(node, *nodes)) {
pol->v.preferred_node = node;
pol->flags &= ~MPOL_F_LOCAL;
} else
pol->flags |= MPOL_F_LOCAL;
} else if (pol->flags & MPOL_F_RELATIVE_NODES) {
mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
pol->v.preferred_node = first_node(tmp);
} else if (!(pol->flags & MPOL_F_LOCAL)) {
pol->v.preferred_node = node_remap(pol->v.preferred_node,
pol->w.cpuset_mems_allowed,
*nodes);
pol->w.cpuset_mems_allowed = *nodes;
}
}
/*
* mpol_rebind_policy - Migrate a policy to a different set of nodes
*
* If read-side task has no lock to protect task->mempolicy, write-side
* task will rebind the task->mempolicy by two step. The first step is
* setting all the newly nodes, and the second step is cleaning all the
* disallowed nodes. In this way, we can avoid finding no node to alloc
* page.
* If we have a lock to protect task->mempolicy in read-side, we do
* rebind directly.
*
* step:
* MPOL_REBIND_ONCE - do rebind work at once
* MPOL_REBIND_STEP1 - set all the newly nodes
* MPOL_REBIND_STEP2 - clean all the disallowed nodes
*/
static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask,
enum mpol_rebind_step step)
{
if (!pol)
return;
if (!mpol_store_user_nodemask(pol) && step == MPOL_REBIND_ONCE &&
nodes_equal(pol->w.cpuset_mems_allowed, *newmask))
return;
if (step == MPOL_REBIND_STEP1 && (pol->flags & MPOL_F_REBINDING))
return;
if (step == MPOL_REBIND_STEP2 && !(pol->flags & MPOL_F_REBINDING))
BUG();
if (step == MPOL_REBIND_STEP1)
pol->flags |= MPOL_F_REBINDING;
else if (step == MPOL_REBIND_STEP2)
pol->flags &= ~MPOL_F_REBINDING;
else if (step >= MPOL_REBIND_NSTEP)
BUG();
mpol_ops[pol->mode].rebind(pol, newmask, step);
}
/*
* Wrapper for mpol_rebind_policy() that just requires task
* pointer, and updates task mempolicy.
*
* Called with task's alloc_lock held.
*/
void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new,
enum mpol_rebind_step step)
{
mpol_rebind_policy(tsk->mempolicy, new, step);
}
/*
* Rebind each vma in mm to new nodemask.
*
* Call holding a reference to mm. Takes mm->mmap_sem during call.
*/
void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new)
{
struct vm_area_struct *vma;
down_write(&mm->mmap_sem);
for (vma = mm->mmap; vma; vma = vma->vm_next)
mpol_rebind_policy(vma->vm_policy, new, MPOL_REBIND_ONCE);
up_write(&mm->mmap_sem);
}
static const struct mempolicy_operations mpol_ops[MPOL_MAX] = {
[MPOL_DEFAULT] = {
.rebind = mpol_rebind_default,
},
[MPOL_INTERLEAVE] = {
.create = mpol_new_interleave,
.rebind = mpol_rebind_nodemask,
},
[MPOL_PREFERRED] = {
.create = mpol_new_preferred,
.rebind = mpol_rebind_preferred,
},
[MPOL_BIND] = {
.create = mpol_new_bind,
.rebind = mpol_rebind_nodemask,
},
};
static void migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags);
struct queue_pages {
struct list_head *pagelist;
unsigned long flags;
nodemask_t *nmask;
struct vm_area_struct *prev;
};
/*
* Scan through pages checking if pages follow certain conditions,
* and move them to the pagelist if they do.
*/
static int queue_pages_pte_range(pmd_t *pmd, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct page *page;
struct queue_pages *qp = walk->private;
unsigned long flags = qp->flags;
int nid, ret;
pte_t *pte;
spinlock_t *ptl;
if (pmd_trans_huge(*pmd)) {
ptl = pmd_lock(walk->mm, pmd);
if (pmd_trans_huge(*pmd)) {
page = pmd_page(*pmd);
if (is_huge_zero_page(page)) {
spin_unlock(ptl);
__split_huge_pmd(vma, pmd, addr, false, NULL);
} else {
get_page(page);
spin_unlock(ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (ret)
return 0;
}
} else {
spin_unlock(ptl);
}
}
if (pmd_trans_unstable(pmd))
return 0;
retry:
pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE) {
if (!pte_present(*pte))
continue;
page = vm_normal_page(vma, addr, *pte);
if (!page)
continue;
/*
* vm_normal_page() filters out zero pages, but there might
* still be PageReserved pages to skip, perhaps in a VDSO.
*/
if (PageReserved(page))
continue;
nid = page_to_nid(page);
if (node_isset(nid, *qp->nmask) == !!(flags & MPOL_MF_INVERT))
continue;
if (PageTransCompound(page)) {
get_page(page);
pte_unmap_unlock(pte, ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
/* Failed to split -- skip. */
if (ret) {
pte = pte_offset_map_lock(walk->mm, pmd,
addr, &ptl);
continue;
}
goto retry;
}
migrate_page_add(page, qp->pagelist, flags);
}
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 0;
}
static int queue_pages_hugetlb(pte_t *pte, unsigned long hmask,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
#ifdef CONFIG_HUGETLB_PAGE
struct queue_pages *qp = walk->private;
unsigned long flags = qp->flags;
int nid;
struct page *page;
spinlock_t *ptl;
pte_t entry;
ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
entry = huge_ptep_get(pte);
if (!pte_present(entry))
goto unlock;
page = pte_page(entry);
nid = page_to_nid(page);
if (node_isset(nid, *qp->nmask) == !!(flags & MPOL_MF_INVERT))
goto unlock;
/* With MPOL_MF_MOVE, we migrate only unshared hugepage. */
if (flags & (MPOL_MF_MOVE_ALL) ||
(flags & MPOL_MF_MOVE && page_mapcount(page) == 1))
isolate_huge_page(page, qp->pagelist);
unlock:
spin_unlock(ptl);
#else
BUG();
#endif
return 0;
}
#ifdef CONFIG_NUMA_BALANCING
/*
* This is used to mark a range of virtual addresses to be inaccessible.
* These are later cleared by a NUMA hinting fault. Depending on these
* faults, pages may be migrated for better NUMA placement.
*
* This is assuming that NUMA faults are handled using PROT_NONE. If
* an architecture makes a different choice, it will need further
* changes to the core.
*/
unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
int nr_updated;
nr_updated = change_protection(vma, addr, end, PAGE_NONE, 0, 1);
if (nr_updated)
count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated);
return nr_updated;
}
#else
static unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
return 0;
}
#endif /* CONFIG_NUMA_BALANCING */
static int queue_pages_test_walk(unsigned long start, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct queue_pages *qp = walk->private;
unsigned long endvma = vma->vm_end;
unsigned long flags = qp->flags;
if (!vma_migratable(vma))
return 1;
if (endvma > end)
endvma = end;
if (vma->vm_start > start)
start = vma->vm_start;
if (!(flags & MPOL_MF_DISCONTIG_OK)) {
if (!vma->vm_next && vma->vm_end < end)
return -EFAULT;
if (qp->prev && qp->prev->vm_end < vma->vm_start)
return -EFAULT;
}
qp->prev = vma;
if (flags & MPOL_MF_LAZY) {
/* Similar to task_numa_work, skip inaccessible VMAs */
if (!is_vm_hugetlb_page(vma) &&
(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)) &&
!(vma->vm_flags & VM_MIXEDMAP))
change_prot_numa(vma, start, endvma);
return 1;
}
/* queue pages from current vma */
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
return 0;
return 1;
}
/*
* Walk through page tables and collect pages to be migrated.
*
* If pages found in a given range are on a set of nodes (determined by
* @nodes and @flags,) it's isolated and queued to the pagelist which is
* passed via @private.)
*/
static int
queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end,
nodemask_t *nodes, unsigned long flags,
struct list_head *pagelist)
{
struct queue_pages qp = {
.pagelist = pagelist,
.flags = flags,
.nmask = nodes,
.prev = NULL,
};
struct mm_walk queue_pages_walk = {
.hugetlb_entry = queue_pages_hugetlb,
.pmd_entry = queue_pages_pte_range,
.test_walk = queue_pages_test_walk,
.mm = mm,
.private = &qp,
};
return walk_page_range(start, end, &queue_pages_walk);
}
/*
* Apply policy to a single VMA
* This must be called with the mmap_sem held for writing.
*/
static int vma_replace_policy(struct vm_area_struct *vma,
struct mempolicy *pol)
{
int err;
struct mempolicy *old;
struct mempolicy *new;
pr_debug("vma %lx-%lx/%lx vm_ops %p vm_file %p set_policy %p\n",
vma->vm_start, vma->vm_end, vma->vm_pgoff,
vma->vm_ops, vma->vm_file,
vma->vm_ops ? vma->vm_ops->set_policy : NULL);
new = mpol_dup(pol);
if (IS_ERR(new))
return PTR_ERR(new);
if (vma->vm_ops && vma->vm_ops->set_policy) {
err = vma->vm_ops->set_policy(vma, new);
if (err)
goto err_out;
}
old = vma->vm_policy;
vma->vm_policy = new; /* protected by mmap_sem */
mpol_put(old);
return 0;
err_out:
mpol_put(new);
return err;
}
/* Step 2: apply policy to a range and do splits. */
static int mbind_range(struct mm_struct *mm, unsigned long start,
unsigned long end, struct mempolicy *new_pol)
{
struct vm_area_struct *next;
struct vm_area_struct *prev;
struct vm_area_struct *vma;
int err = 0;
pgoff_t pgoff;
unsigned long vmstart;
unsigned long vmend;
vma = find_vma(mm, start);
if (!vma || vma->vm_start > start)
return -EFAULT;
prev = vma->vm_prev;
if (start > vma->vm_start)
prev = vma;
for (; vma && vma->vm_start < end; prev = vma, vma = next) {
next = vma->vm_next;
vmstart = max(start, vma->vm_start);
vmend = min(end, vma->vm_end);
if (mpol_equal(vma_policy(vma), new_pol))
continue;
pgoff = vma->vm_pgoff +
((vmstart - vma->vm_start) >> PAGE_SHIFT);
prev = vma_merge(mm, prev, vmstart, vmend, vma->vm_flags,
vma->anon_vma, vma->vm_file, pgoff,
new_pol, vma->vm_userfaultfd_ctx);
if (prev) {
vma = prev;
next = vma->vm_next;
if (mpol_equal(vma_policy(vma), new_pol))
continue;
/* vma_merge() joined vma && vma->next, case 8 */
goto replace;
}
if (vma->vm_start != vmstart) {
err = split_vma(vma->vm_mm, vma, vmstart, 1);
if (err)
goto out;
}
if (vma->vm_end != vmend) {
err = split_vma(vma->vm_mm, vma, vmend, 0);
if (err)
goto out;
}
replace:
err = vma_replace_policy(vma, new_pol);
if (err)
goto out;
}
out:
return err;
}
/* Set the process memory policy */
static long do_set_mempolicy(unsigned short mode, unsigned short flags,
nodemask_t *nodes)
{
struct mempolicy *new, *old;
NODEMASK_SCRATCH(scratch);
int ret;
if (!scratch)
return -ENOMEM;
new = mpol_new(mode, flags, nodes);
if (IS_ERR(new)) {
ret = PTR_ERR(new);
goto out;
}
task_lock(current);
ret = mpol_set_nodemask(new, nodes, scratch);
if (ret) {
task_unlock(current);
mpol_put(new);
goto out;
}
old = current->mempolicy;
current->mempolicy = new;
if (new && new->mode == MPOL_INTERLEAVE &&
nodes_weight(new->v.nodes))
current->il_next = first_node(new->v.nodes);
task_unlock(current);
mpol_put(old);
ret = 0;
out:
NODEMASK_SCRATCH_FREE(scratch);
return ret;
}
/*
* Return nodemask for policy for get_mempolicy() query
*
* Called with task's alloc_lock held
*/
static void get_policy_nodemask(struct mempolicy *p, nodemask_t *nodes)
{
nodes_clear(*nodes);
if (p == &default_policy)
return;
switch (p->mode) {
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
*nodes = p->v.nodes;
break;
case MPOL_PREFERRED:
if (!(p->flags & MPOL_F_LOCAL))
node_set(p->v.preferred_node, *nodes);
/* else return empty node mask for local allocation */
break;
default:
BUG();
}
}
static int lookup_node(unsigned long addr)
{
struct page *p;
int err;
err = get_user_pages(addr & PAGE_MASK, 1, 0, &p, NULL);
if (err >= 0) {
err = page_to_nid(p);
put_page(p);
}
return err;
}
/* Retrieve NUMA policy */
static long do_get_mempolicy(int *policy, nodemask_t *nmask,
unsigned long addr, unsigned long flags)
{
int err;
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = NULL;
struct mempolicy *pol = current->mempolicy;
if (flags &
~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
return -EINVAL;
if (flags & MPOL_F_MEMS_ALLOWED) {
if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
return -EINVAL;
*policy = 0; /* just so it's initialized */
task_lock(current);
*nmask = cpuset_current_mems_allowed;
task_unlock(current);
return 0;
}
if (flags & MPOL_F_ADDR) {
/*
* Do NOT fall back to task policy if the
* vma/shared policy at addr is NULL. We
* want to return MPOL_DEFAULT in this case.
*/
down_read(&mm->mmap_sem);
vma = find_vma_intersection(mm, addr, addr+1);
if (!vma) {
up_read(&mm->mmap_sem);
return -EFAULT;
}
if (vma->vm_ops && vma->vm_ops->get_policy)
pol = vma->vm_ops->get_policy(vma, addr);
else
pol = vma->vm_policy;
} else if (addr)
return -EINVAL;
if (!pol)
pol = &default_policy; /* indicates default behavior */
if (flags & MPOL_F_NODE) {
if (flags & MPOL_F_ADDR) {
err = lookup_node(addr);
if (err < 0)
goto out;
*policy = err;
} else if (pol == current->mempolicy &&
pol->mode == MPOL_INTERLEAVE) {
*policy = current->il_next;
} else {
err = -EINVAL;
goto out;
}
} else {
*policy = pol == &default_policy ? MPOL_DEFAULT :
pol->mode;
/*
* Internal mempolicy flags must be masked off before exposing
* the policy to userspace.
*/
*policy |= (pol->flags & MPOL_MODE_FLAGS);
}
if (vma) {
up_read(¤t->mm->mmap_sem);
vma = NULL;
}
err = 0;
if (nmask) {
if (mpol_store_user_nodemask(pol)) {
*nmask = pol->w.user_nodemask;
} else {
task_lock(current);
get_policy_nodemask(pol, nmask);
task_unlock(current);
}
}
out:
mpol_cond_put(pol);
if (vma)
up_read(¤t->mm->mmap_sem);
return err;
}
#ifdef CONFIG_MIGRATION
/*
* page migration
*/
static void migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags)
{
/*
* Avoid migrating a page that is shared with others.
*/
if ((flags & MPOL_MF_MOVE_ALL) || page_mapcount(page) == 1) {
if (!isolate_lru_page(page)) {
list_add_tail(&page->lru, pagelist);
inc_node_page_state(page, NR_ISOLATED_ANON +
page_is_file_cache(page));
}
}
}
static struct page *new_node_page(struct page *page, unsigned long node, int **x)
{
if (PageHuge(page))
return alloc_huge_page_node(page_hstate(compound_head(page)),
node);
else
return __alloc_pages_node(node, GFP_HIGHUSER_MOVABLE |
__GFP_THISNODE, 0);
}
/*
* Migrate pages from one node to a target node.
* Returns error or the number of pages not migrated.
*/
static int migrate_to_node(struct mm_struct *mm, int source, int dest,
int flags)
{
nodemask_t nmask;
LIST_HEAD(pagelist);
int err = 0;
nodes_clear(nmask);
node_set(source, nmask);
/*
* This does not "check" the range but isolates all pages that
* need migration. Between passing in the full user address
* space range and MPOL_MF_DISCONTIG_OK, this call can not fail.
*/
VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)));
queue_pages_range(mm, mm->mmap->vm_start, mm->task_size, &nmask,
flags | MPOL_MF_DISCONTIG_OK, &pagelist);
if (!list_empty(&pagelist)) {
err = migrate_pages(&pagelist, new_node_page, NULL, dest,
MIGRATE_SYNC, MR_SYSCALL);
if (err)
putback_movable_pages(&pagelist);
}
return err;
}
/*
* Move pages between the two nodesets so as to preserve the physical
* layout as much as possible.
*
* Returns the number of page that could not be moved.
*/
int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
const nodemask_t *to, int flags)
{
int busy = 0;
int err;
nodemask_t tmp;
err = migrate_prep();
if (err)
return err;
down_read(&mm->mmap_sem);
/*
* Find a 'source' bit set in 'tmp' whose corresponding 'dest'
* bit in 'to' is not also set in 'tmp'. Clear the found 'source'
* bit in 'tmp', and return that <source, dest> pair for migration.
* The pair of nodemasks 'to' and 'from' define the map.
*
* If no pair of bits is found that way, fallback to picking some
* pair of 'source' and 'dest' bits that are not the same. If the
* 'source' and 'dest' bits are the same, this represents a node
* that will be migrating to itself, so no pages need move.
*
* If no bits are left in 'tmp', or if all remaining bits left
* in 'tmp' correspond to the same bit in 'to', return false
* (nothing left to migrate).
*
* This lets us pick a pair of nodes to migrate between, such that
* if possible the dest node is not already occupied by some other
* source node, minimizing the risk of overloading the memory on a
* node that would happen if we migrated incoming memory to a node
* before migrating outgoing memory source that same node.
*
* A single scan of tmp is sufficient. As we go, we remember the
* most recent <s, d> pair that moved (s != d). If we find a pair
* that not only moved, but what's better, moved to an empty slot
* (d is not set in tmp), then we break out then, with that pair.
* Otherwise when we finish scanning from_tmp, we at least have the
* most recent <s, d> pair that moved. If we get all the way through
* the scan of tmp without finding any node that moved, much less
* moved to an empty node, then there is nothing left worth migrating.
*/
tmp = *from;
while (!nodes_empty(tmp)) {
int s,d;
int source = NUMA_NO_NODE;
int dest = 0;
for_each_node_mask(s, tmp) {
/*
* do_migrate_pages() tries to maintain the relative
* node relationship of the pages established between
* threads and memory areas.
*
* However if the number of source nodes is not equal to
* the number of destination nodes we can not preserve
* this node relative relationship. In that case, skip
* copying memory from a node that is in the destination
* mask.
*
* Example: [2,3,4] -> [3,4,5] moves everything.
* [0-7] - > [3,4,5] moves only 0,1,2,6,7.
*/
if ((nodes_weight(*from) != nodes_weight(*to)) &&
(node_isset(s, *to)))
continue;
d = node_remap(s, *from, *to);
if (s == d)
continue;
source = s; /* Node moved. Memorize */
dest = d;
/* dest not in remaining from nodes? */
if (!node_isset(dest, tmp))
break;
}
if (source == NUMA_NO_NODE)
break;
node_clear(source, tmp);
err = migrate_to_node(mm, source, dest, flags);
if (err > 0)
busy += err;
if (err < 0)
break;
}
up_read(&mm->mmap_sem);
if (err < 0)
return err;
return busy;
}
/*
* Allocate a new page for page migration based on vma policy.
* Start by assuming the page is mapped by the same vma as contains @start.
* Search forward from there, if not. N.B., this assumes that the
* list of pages handed to migrate_pages()--which is how we get here--
* is in virtual address order.
*/
static struct page *new_page(struct page *page, unsigned long start, int **x)
{
struct vm_area_struct *vma;
unsigned long uninitialized_var(address);
vma = find_vma(current->mm, start);
while (vma) {
address = page_address_in_vma(page, vma);
if (address != -EFAULT)
break;
vma = vma->vm_next;
}
if (PageHuge(page)) {
BUG_ON(!vma);
return alloc_huge_page_noerr(vma, address, 1);
}
/*
* if !vma, alloc_page_vma() will use task or system default policy
*/
return alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
}
#else
static void migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags)
{
}
int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
const nodemask_t *to, int flags)
{
return -ENOSYS;
}
static struct page *new_page(struct page *page, unsigned long start, int **x)
{
return NULL;
}
#endif
static long do_mbind(unsigned long start, unsigned long len,
unsigned short mode, unsigned short mode_flags,
nodemask_t *nmask, unsigned long flags)
{
struct mm_struct *mm = current->mm;
struct mempolicy *new;
unsigned long end;
int err;
LIST_HEAD(pagelist);
if (flags & ~(unsigned long)MPOL_MF_VALID)
return -EINVAL;
if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
return -EPERM;
if (start & ~PAGE_MASK)
return -EINVAL;
if (mode == MPOL_DEFAULT)
flags &= ~MPOL_MF_STRICT;
len = (len + PAGE_SIZE - 1) & PAGE_MASK;
end = start + len;
if (end < start)
return -EINVAL;
if (end == start)
return 0;
new = mpol_new(mode, mode_flags, nmask);
if (IS_ERR(new))
return PTR_ERR(new);
if (flags & MPOL_MF_LAZY)
new->flags |= MPOL_F_MOF;
/*
* If we are using the default policy then operation
* on discontinuous address spaces is okay after all
*/
if (!new)
flags |= MPOL_MF_DISCONTIG_OK;
pr_debug("mbind %lx-%lx mode:%d flags:%d nodes:%lx\n",
start, start + len, mode, mode_flags,
nmask ? nodes_addr(*nmask)[0] : NUMA_NO_NODE);
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) {
err = migrate_prep();
if (err)
goto mpol_out;
}
{
NODEMASK_SCRATCH(scratch);
if (scratch) {
down_write(&mm->mmap_sem);
task_lock(current);
err = mpol_set_nodemask(new, nmask, scratch);
task_unlock(current);
if (err)
up_write(&mm->mmap_sem);
} else
err = -ENOMEM;
NODEMASK_SCRATCH_FREE(scratch);
}
if (err)
goto mpol_out;
err = queue_pages_range(mm, start, end, nmask,
flags | MPOL_MF_INVERT, &pagelist);
if (!err)
err = mbind_range(mm, start, end, new);
if (!err) {
int nr_failed = 0;
if (!list_empty(&pagelist)) {
WARN_ON_ONCE(flags & MPOL_MF_LAZY);
nr_failed = migrate_pages(&pagelist, new_page, NULL,
start, MIGRATE_SYNC, MR_MEMPOLICY_MBIND);
if (nr_failed)
putback_movable_pages(&pagelist);
}
if (nr_failed && (flags & MPOL_MF_STRICT))
err = -EIO;
} else
putback_movable_pages(&pagelist);
up_write(&mm->mmap_sem);
mpol_out:
mpol_put(new);
return err;
}
/*
* User space interface with variable sized bitmaps for nodelists.
*/
/* Copy a node mask from user space. */
static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask,
unsigned long maxnode)
{
unsigned long k;
unsigned long nlongs;
unsigned long endmask;
--maxnode;
nodes_clear(*nodes);
if (maxnode == 0 || !nmask)
return 0;
if (maxnode > PAGE_SIZE*BITS_PER_BYTE)
return -EINVAL;
nlongs = BITS_TO_LONGS(maxnode);
if ((maxnode % BITS_PER_LONG) == 0)
endmask = ~0UL;
else
endmask = (1UL << (maxnode % BITS_PER_LONG)) - 1;
/* When the user specified more nodes than supported just check
if the non supported part is all zero. */
if (nlongs > BITS_TO_LONGS(MAX_NUMNODES)) {
if (nlongs > PAGE_SIZE/sizeof(long))
return -EINVAL;
for (k = BITS_TO_LONGS(MAX_NUMNODES); k < nlongs; k++) {
unsigned long t;
if (get_user(t, nmask + k))
return -EFAULT;
if (k == nlongs - 1) {
if (t & endmask)
return -EINVAL;
} else if (t)
return -EINVAL;
}
nlongs = BITS_TO_LONGS(MAX_NUMNODES);
endmask = ~0UL;
}
if (copy_from_user(nodes_addr(*nodes), nmask, nlongs*sizeof(unsigned long)))
return -EFAULT;
nodes_addr(*nodes)[nlongs-1] &= endmask;
return 0;
}
/* Copy a kernel node mask to user space */
static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode,
nodemask_t *nodes)
{
unsigned long copy = ALIGN(maxnode-1, 64) / 8;
const int nbytes = BITS_TO_LONGS(MAX_NUMNODES) * sizeof(long);
if (copy > nbytes) {
if (copy > PAGE_SIZE)
return -EINVAL;
if (clear_user((char __user *)mask + nbytes, copy - nbytes))
return -EFAULT;
copy = nbytes;
}
return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0;
}
SYSCALL_DEFINE6(mbind, unsigned long, start, unsigned long, len,
unsigned long, mode, const unsigned long __user *, nmask,
unsigned long, maxnode, unsigned, flags)
{
nodemask_t nodes;
int err;
unsigned short mode_flags;
mode_flags = mode & MPOL_MODE_FLAGS;
mode &= ~MPOL_MODE_FLAGS;
if (mode >= MPOL_MAX)
return -EINVAL;
if ((mode_flags & MPOL_F_STATIC_NODES) &&
(mode_flags & MPOL_F_RELATIVE_NODES))
return -EINVAL;
err = get_nodes(&nodes, nmask, maxnode);
if (err)
return err;
return do_mbind(start, len, mode, mode_flags, &nodes, flags);
}
/* Set the process memory policy */
SYSCALL_DEFINE3(set_mempolicy, int, mode, const unsigned long __user *, nmask,
unsigned long, maxnode)
{
int err;
nodemask_t nodes;
unsigned short flags;
flags = mode & MPOL_MODE_FLAGS;
mode &= ~MPOL_MODE_FLAGS;
if ((unsigned int)mode >= MPOL_MAX)
return -EINVAL;
if ((flags & MPOL_F_STATIC_NODES) && (flags & MPOL_F_RELATIVE_NODES))
return -EINVAL;
err = get_nodes(&nodes, nmask, maxnode);
if (err)
return err;
return do_set_mempolicy(mode, flags, &nodes);
}
SYSCALL_DEFINE4(migrate_pages, pid_t, pid, unsigned long, maxnode,
const unsigned long __user *, old_nodes,
const unsigned long __user *, new_nodes)
{
const struct cred *cred = current_cred(), *tcred;
struct mm_struct *mm = NULL;
struct task_struct *task;
nodemask_t task_nodes;
int err;
nodemask_t *old;
nodemask_t *new;
NODEMASK_SCRATCH(scratch);
if (!scratch)
return -ENOMEM;
old = &scratch->mask1;
new = &scratch->mask2;
err = get_nodes(old, old_nodes, maxnode);
if (err)
goto out;
err = get_nodes(new, new_nodes, maxnode);
if (err)
goto out;
/* Find the mm_struct */
rcu_read_lock();
task = pid ? find_task_by_vpid(pid) : current;
if (!task) {
rcu_read_unlock();
err = -ESRCH;
goto out;
}
get_task_struct(task);
err = -EINVAL;
/*
* Check if this process has the right to modify the specified
* process. The right exists if the process has administrative
* capabilities, superuser privileges or the same
* userid as the target process.
*/
tcred = __task_cred(task);
if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) &&
!uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) &&
!capable(CAP_SYS_NICE)) {
rcu_read_unlock();
err = -EPERM;
goto out_put;
}
rcu_read_unlock();
task_nodes = cpuset_mems_allowed(task);
/* Is the user allowed to access the target nodes? */
if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) {
err = -EPERM;
goto out_put;
}
if (!nodes_subset(*new, node_states[N_MEMORY])) {
err = -EINVAL;
goto out_put;
}
err = security_task_movememory(task);
if (err)
goto out_put;
mm = get_task_mm(task);
put_task_struct(task);
if (!mm) {
err = -EINVAL;
goto out;
}
err = do_migrate_pages(mm, old, new,
capable(CAP_SYS_NICE) ? MPOL_MF_MOVE_ALL : MPOL_MF_MOVE);
mmput(mm);
out:
NODEMASK_SCRATCH_FREE(scratch);
return err;
out_put:
put_task_struct(task);
goto out;
}
/* Retrieve NUMA policy */
SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
unsigned long __user *, nmask, unsigned long, maxnode,
unsigned long, addr, unsigned long, flags)
{
int err;
int uninitialized_var(pval);
nodemask_t nodes;
if (nmask != NULL && maxnode < MAX_NUMNODES)
return -EINVAL;
err = do_get_mempolicy(&pval, &nodes, addr, flags);
if (err)
return err;
if (policy && put_user(pval, policy))
return -EFAULT;
if (nmask)
err = copy_nodes_to_user(nmask, maxnode, &nodes);
return err;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode,
compat_ulong_t, addr, compat_ulong_t, flags)
{
long err;
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
DECLARE_BITMAP(bm, MAX_NUMNODES);
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask)
nm = compat_alloc_user_space(alloc_size);
err = sys_get_mempolicy(policy, nm, nr_bits+1, addr, flags);
if (!err && nmask) {
unsigned long copy_size;
copy_size = min_t(unsigned long, sizeof(bm), alloc_size);
err = copy_from_user(bm, nm, copy_size);
/* ensure entire bitmap is zeroed */
err |= clear_user(nmask, ALIGN(maxnode-1, 8) / 8);
err |= compat_put_bitmap(nmask, bm, nr_bits);
}
return err;
}
COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode)
{
long err = 0;
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
DECLARE_BITMAP(bm, MAX_NUMNODES);
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask) {
err = compat_get_bitmap(bm, nmask, nr_bits);
nm = compat_alloc_user_space(alloc_size);
err |= copy_to_user(nm, bm, alloc_size);
}
if (err)
return -EFAULT;
return sys_set_mempolicy(mode, nm, nr_bits+1);
}
COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len,
compat_ulong_t, mode, compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode, compat_ulong_t, flags)
{
long err = 0;
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
nodemask_t bm;
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask) {
err = compat_get_bitmap(nodes_addr(bm), nmask, nr_bits);
nm = compat_alloc_user_space(alloc_size);
err |= copy_to_user(nm, nodes_addr(bm), alloc_size);
}
if (err)
return -EFAULT;
return sys_mbind(start, len, mode, nm, nr_bits+1, flags);
}
#endif
struct mempolicy *__get_vma_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct mempolicy *pol = NULL;
if (vma) {
if (vma->vm_ops && vma->vm_ops->get_policy) {
pol = vma->vm_ops->get_policy(vma, addr);
} else if (vma->vm_policy) {
pol = vma->vm_policy;
/*
* shmem_alloc_page() passes MPOL_F_SHARED policy with
* a pseudo vma whose vma->vm_ops=NULL. Take a reference
* count on these policies which will be dropped by
* mpol_cond_put() later
*/
if (mpol_needs_cond_ref(pol))
mpol_get(pol);
}
}
return pol;
}
/*
* get_vma_policy(@vma, @addr)
* @vma: virtual memory area whose policy is sought
* @addr: address in @vma for shared policy lookup
*
* Returns effective policy for a VMA at specified address.
* Falls back to current->mempolicy or system default policy, as necessary.
* Shared policies [those marked as MPOL_F_SHARED] require an extra reference
* count--added by the get_policy() vm_op, as appropriate--to protect against
* freeing by another task. It is the caller's responsibility to free the
* extra reference for shared policies.
*/
static struct mempolicy *get_vma_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct mempolicy *pol = __get_vma_policy(vma, addr);
if (!pol)
pol = get_task_policy(current);
return pol;
}
bool vma_policy_mof(struct vm_area_struct *vma)
{
struct mempolicy *pol;
if (vma->vm_ops && vma->vm_ops->get_policy) {
bool ret = false;
pol = vma->vm_ops->get_policy(vma, vma->vm_start);
if (pol && (pol->flags & MPOL_F_MOF))
ret = true;
mpol_cond_put(pol);
return ret;
}
pol = vma->vm_policy;
if (!pol)
pol = get_task_policy(current);
return pol->flags & MPOL_F_MOF;
}
static int apply_policy_zone(struct mempolicy *policy, enum zone_type zone)
{
enum zone_type dynamic_policy_zone = policy_zone;
BUG_ON(dynamic_policy_zone == ZONE_MOVABLE);
/*
* if policy->v.nodes has movable memory only,
* we apply policy when gfp_zone(gfp) = ZONE_MOVABLE only.
*
* policy->v.nodes is intersect with node_states[N_MEMORY].
* so if the following test faile, it implies
* policy->v.nodes has movable memory only.
*/
if (!nodes_intersects(policy->v.nodes, node_states[N_HIGH_MEMORY]))
dynamic_policy_zone = ZONE_MOVABLE;
return zone >= dynamic_policy_zone;
}
/*
* Return a nodemask representing a mempolicy for filtering nodes for
* page allocation
*/
static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *policy)
{
/* Lower zones don't get a nodemask applied for MPOL_BIND */
if (unlikely(policy->mode == MPOL_BIND) &&
apply_policy_zone(policy, gfp_zone(gfp)) &&
cpuset_nodemask_valid_mems_allowed(&policy->v.nodes))
return &policy->v.nodes;
return NULL;
}
/* Return a zonelist indicated by gfp for node representing a mempolicy */
static struct zonelist *policy_zonelist(gfp_t gfp, struct mempolicy *policy,
int nd)
{
if (policy->mode == MPOL_PREFERRED && !(policy->flags & MPOL_F_LOCAL))
nd = policy->v.preferred_node;
else {
/*
* __GFP_THISNODE shouldn't even be used with the bind policy
* because we might easily break the expectation to stay on the
* requested node and not break the policy.
*/
WARN_ON_ONCE(policy->mode == MPOL_BIND && (gfp & __GFP_THISNODE));
}
return node_zonelist(nd, gfp);
}
/* Do dynamic interleaving for a process */
static unsigned interleave_nodes(struct mempolicy *policy)
{
unsigned nid, next;
struct task_struct *me = current;
nid = me->il_next;
next = next_node_in(nid, policy->v.nodes);
if (next < MAX_NUMNODES)
me->il_next = next;
return nid;
}
/*
* Depending on the memory policy provide a node from which to allocate the
* next slab entry.
*/
unsigned int mempolicy_slab_node(void)
{
struct mempolicy *policy;
int node = numa_mem_id();
if (in_interrupt())
return node;
policy = current->mempolicy;
if (!policy || policy->flags & MPOL_F_LOCAL)
return node;
switch (policy->mode) {
case MPOL_PREFERRED:
/*
* handled MPOL_F_LOCAL above
*/
return policy->v.preferred_node;
case MPOL_INTERLEAVE:
return interleave_nodes(policy);
case MPOL_BIND: {
struct zoneref *z;
/*
* Follow bind policy behavior and start allocation at the
* first node.
*/
struct zonelist *zonelist;
enum zone_type highest_zoneidx = gfp_zone(GFP_KERNEL);
zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK];
z = first_zones_zonelist(zonelist, highest_zoneidx,
&policy->v.nodes);
return z->zone ? z->zone->node : node;
}
default:
BUG();
}
}
/*
* Do static interleaving for a VMA with known offset @n. Returns the n'th
* node in pol->v.nodes (starting from n=0), wrapping around if n exceeds the
* number of present nodes.
*/
static unsigned offset_il_node(struct mempolicy *pol,
struct vm_area_struct *vma, unsigned long n)
{
unsigned nnodes = nodes_weight(pol->v.nodes);
unsigned target;
int i;
int nid;
if (!nnodes)
return numa_node_id();
target = (unsigned int)n % nnodes;
nid = first_node(pol->v.nodes);
for (i = 0; i < target; i++)
nid = next_node(nid, pol->v.nodes);
return nid;
}
/* Determine a node number for interleave */
static inline unsigned interleave_nid(struct mempolicy *pol,
struct vm_area_struct *vma, unsigned long addr, int shift)
{
if (vma) {
unsigned long off;
/*
* for small pages, there is no difference between
* shift and PAGE_SHIFT, so the bit-shift is safe.
* for huge pages, since vm_pgoff is in units of small
* pages, we need to shift off the always 0 bits to get
* a useful offset.
*/
BUG_ON(shift < PAGE_SHIFT);
off = vma->vm_pgoff >> (shift - PAGE_SHIFT);
off += (addr - vma->vm_start) >> shift;
return offset_il_node(pol, vma, off);
} else
return interleave_nodes(pol);
}
#ifdef CONFIG_HUGETLBFS
/*
* huge_zonelist(@vma, @addr, @gfp_flags, @mpol)
* @vma: virtual memory area whose policy is sought
* @addr: address in @vma for shared policy lookup and interleave policy
* @gfp_flags: for requested zone
* @mpol: pointer to mempolicy pointer for reference counted mempolicy
* @nodemask: pointer to nodemask pointer for MPOL_BIND nodemask
*
* Returns a zonelist suitable for a huge page allocation and a pointer
* to the struct mempolicy for conditional unref after allocation.
* If the effective policy is 'BIND, returns a pointer to the mempolicy's
* @nodemask for filtering the zonelist.
*
* Must be protected by read_mems_allowed_begin()
*/
struct zonelist *huge_zonelist(struct vm_area_struct *vma, unsigned long addr,
gfp_t gfp_flags, struct mempolicy **mpol,
nodemask_t **nodemask)
{
struct zonelist *zl;
*mpol = get_vma_policy(vma, addr);
*nodemask = NULL; /* assume !MPOL_BIND */
if (unlikely((*mpol)->mode == MPOL_INTERLEAVE)) {
zl = node_zonelist(interleave_nid(*mpol, vma, addr,
huge_page_shift(hstate_vma(vma))), gfp_flags);
} else {
zl = policy_zonelist(gfp_flags, *mpol, numa_node_id());
if ((*mpol)->mode == MPOL_BIND)
*nodemask = &(*mpol)->v.nodes;
}
return zl;
}
/*
* init_nodemask_of_mempolicy
*
* If the current task's mempolicy is "default" [NULL], return 'false'
* to indicate default policy. Otherwise, extract the policy nodemask
* for 'bind' or 'interleave' policy into the argument nodemask, or
* initialize the argument nodemask to contain the single node for
* 'preferred' or 'local' policy and return 'true' to indicate presence
* of non-default mempolicy.
*
* We don't bother with reference counting the mempolicy [mpol_get/put]
* because the current task is examining it's own mempolicy and a task's
* mempolicy is only ever changed by the task itself.
*
* N.B., it is the caller's responsibility to free a returned nodemask.
*/
bool init_nodemask_of_mempolicy(nodemask_t *mask)
{
struct mempolicy *mempolicy;
int nid;
if (!(mask && current->mempolicy))
return false;
task_lock(current);
mempolicy = current->mempolicy;
switch (mempolicy->mode) {
case MPOL_PREFERRED:
if (mempolicy->flags & MPOL_F_LOCAL)
nid = numa_node_id();
else
nid = mempolicy->v.preferred_node;
init_nodemask_of_node(mask, nid);
break;
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
*mask = mempolicy->v.nodes;
break;
default:
BUG();
}
task_unlock(current);
return true;
}
#endif
/*
* mempolicy_nodemask_intersects
*
* If tsk's mempolicy is "default" [NULL], return 'true' to indicate default
* policy. Otherwise, check for intersection between mask and the policy
* nodemask for 'bind' or 'interleave' policy. For 'perferred' or 'local'
* policy, always return true since it may allocate elsewhere on fallback.
*
* Takes task_lock(tsk) to prevent freeing of its mempolicy.
*/
bool mempolicy_nodemask_intersects(struct task_struct *tsk,
const nodemask_t *mask)
{
struct mempolicy *mempolicy;
bool ret = true;
if (!mask)
return ret;
task_lock(tsk);
mempolicy = tsk->mempolicy;
if (!mempolicy)
goto out;
switch (mempolicy->mode) {
case MPOL_PREFERRED:
/*
* MPOL_PREFERRED and MPOL_F_LOCAL are only preferred nodes to
* allocate from, they may fallback to other nodes when oom.
* Thus, it's possible for tsk to have allocated memory from
* nodes in mask.
*/
break;
case MPOL_BIND:
case MPOL_INTERLEAVE:
ret = nodes_intersects(mempolicy->v.nodes, *mask);
break;
default:
BUG();
}
out:
task_unlock(tsk);
return ret;
}
/* Allocate a page in interleaved policy.
Own path because it needs to do special accounting. */
static struct page *alloc_page_interleave(gfp_t gfp, unsigned order,
unsigned nid)
{
struct zonelist *zl;
struct page *page;
zl = node_zonelist(nid, gfp);
page = __alloc_pages(gfp, order, zl);
if (page && page_zone(page) == zonelist_zone(&zl->_zonerefs[0]))
inc_zone_page_state(page, NUMA_INTERLEAVE_HIT);
return page;
}
/**
* alloc_pages_vma - Allocate a page for a VMA.
*
* @gfp:
* %GFP_USER user allocation.
* %GFP_KERNEL kernel allocations,
* %GFP_HIGHMEM highmem/user allocations,
* %GFP_FS allocation should not call back into a file system.
* %GFP_ATOMIC don't sleep.
*
* @order:Order of the GFP allocation.
* @vma: Pointer to VMA or NULL if not available.
* @addr: Virtual Address of the allocation. Must be inside the VMA.
* @node: Which node to prefer for allocation (modulo policy).
* @hugepage: for hugepages try only the preferred node if possible
*
* This function allocates a page from the kernel page pool and applies
* a NUMA policy associated with the VMA or the current process.
* When VMA is not NULL caller must hold down_read on the mmap_sem of the
* mm_struct of the VMA to prevent it from going away. Should be used for
* all allocations for pages that will be mapped into user space. Returns
* NULL when no page can be allocated.
*/
struct page *
alloc_pages_vma(gfp_t gfp, int order, struct vm_area_struct *vma,
unsigned long addr, int node, bool hugepage)
{
struct mempolicy *pol;
struct page *page;
unsigned int cpuset_mems_cookie;
struct zonelist *zl;
nodemask_t *nmask;
retry_cpuset:
pol = get_vma_policy(vma, addr);
cpuset_mems_cookie = read_mems_allowed_begin();
if (pol->mode == MPOL_INTERLEAVE) {
unsigned nid;
nid = interleave_nid(pol, vma, addr, PAGE_SHIFT + order);
mpol_cond_put(pol);
page = alloc_page_interleave(gfp, order, nid);
goto out;
}
if (unlikely(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && hugepage)) {
int hpage_node = node;
/*
* For hugepage allocation and non-interleave policy which
* allows the current node (or other explicitly preferred
* node) we only try to allocate from the current/preferred
* node and don't fall back to other nodes, as the cost of
* remote accesses would likely offset THP benefits.
*
* If the policy is interleave, or does not allow the current
* node in its nodemask, we allocate the standard way.
*/
if (pol->mode == MPOL_PREFERRED &&
!(pol->flags & MPOL_F_LOCAL))
hpage_node = pol->v.preferred_node;
nmask = policy_nodemask(gfp, pol);
if (!nmask || node_isset(hpage_node, *nmask)) {
mpol_cond_put(pol);
page = __alloc_pages_node(hpage_node,
gfp | __GFP_THISNODE, order);
goto out;
}
}
nmask = policy_nodemask(gfp, pol);
zl = policy_zonelist(gfp, pol, node);
page = __alloc_pages_nodemask(gfp, order, zl, nmask);
mpol_cond_put(pol);
out:
if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
goto retry_cpuset;
return page;
}
/**
* alloc_pages_current - Allocate pages.
*
* @gfp:
* %GFP_USER user allocation,
* %GFP_KERNEL kernel allocation,
* %GFP_HIGHMEM highmem allocation,
* %GFP_FS don't call back into a file system.
* %GFP_ATOMIC don't sleep.
* @order: Power of two of allocation size in pages. 0 is a single page.
*
* Allocate a page from the kernel page pool. When not in
* interrupt context and apply the current process NUMA policy.
* Returns NULL when no page can be allocated.
*
* Don't call cpuset_update_task_memory_state() unless
* 1) it's ok to take cpuset_sem (can WAIT), and
* 2) allocating for current task (not interrupt).
*/
struct page *alloc_pages_current(gfp_t gfp, unsigned order)
{
struct mempolicy *pol = &default_policy;
struct page *page;
unsigned int cpuset_mems_cookie;
if (!in_interrupt() && !(gfp & __GFP_THISNODE))
pol = get_task_policy(current);
retry_cpuset:
cpuset_mems_cookie = read_mems_allowed_begin();
/*
* No reference counting needed for current->mempolicy
* nor system default_policy
*/
if (pol->mode == MPOL_INTERLEAVE)
page = alloc_page_interleave(gfp, order, interleave_nodes(pol));
else
page = __alloc_pages_nodemask(gfp, order,
policy_zonelist(gfp, pol, numa_node_id()),
policy_nodemask(gfp, pol));
if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
goto retry_cpuset;
return page;
}
EXPORT_SYMBOL(alloc_pages_current);
int vma_dup_policy(struct vm_area_struct *src, struct vm_area_struct *dst)
{
struct mempolicy *pol = mpol_dup(vma_policy(src));
if (IS_ERR(pol))
return PTR_ERR(pol);
dst->vm_policy = pol;
return 0;
}
/*
* If mpol_dup() sees current->cpuset == cpuset_being_rebound, then it
* rebinds the mempolicy its copying by calling mpol_rebind_policy()
* with the mems_allowed returned by cpuset_mems_allowed(). This
* keeps mempolicies cpuset relative after its cpuset moves. See
* further kernel/cpuset.c update_nodemask().
*
* current's mempolicy may be rebinded by the other task(the task that changes
* cpuset's mems), so we needn't do rebind work for current task.
*/
/* Slow path of a mempolicy duplicate */
struct mempolicy *__mpol_dup(struct mempolicy *old)
{
struct mempolicy *new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!new)
return ERR_PTR(-ENOMEM);
/* task's mempolicy is protected by alloc_lock */
if (old == current->mempolicy) {
task_lock(current);
*new = *old;
task_unlock(current);
} else
*new = *old;
if (current_cpuset_is_being_rebound()) {
nodemask_t mems = cpuset_mems_allowed(current);
if (new->flags & MPOL_F_REBINDING)
mpol_rebind_policy(new, &mems, MPOL_REBIND_STEP2);
else
mpol_rebind_policy(new, &mems, MPOL_REBIND_ONCE);
}
atomic_set(&new->refcnt, 1);
return new;
}
/* Slow path of a mempolicy comparison */
bool __mpol_equal(struct mempolicy *a, struct mempolicy *b)
{
if (!a || !b)
return false;
if (a->mode != b->mode)
return false;
if (a->flags != b->flags)
return false;
if (mpol_store_user_nodemask(a))
if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask))
return false;
switch (a->mode) {
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
return !!nodes_equal(a->v.nodes, b->v.nodes);
case MPOL_PREFERRED:
return a->v.preferred_node == b->v.preferred_node;
default:
BUG();
return false;
}
}
/*
* Shared memory backing store policy support.
*
* Remember policies even when nobody has shared memory mapped.
* The policies are kept in Red-Black tree linked from the inode.
* They are protected by the sp->lock rwlock, which should be held
* for any accesses to the tree.
*/
/*
* lookup first element intersecting start-end. Caller holds sp->lock for
* reading or for writing
*/
static struct sp_node *
sp_lookup(struct shared_policy *sp, unsigned long start, unsigned long end)
{
struct rb_node *n = sp->root.rb_node;
while (n) {
struct sp_node *p = rb_entry(n, struct sp_node, nd);
if (start >= p->end)
n = n->rb_right;
else if (end <= p->start)
n = n->rb_left;
else
break;
}
if (!n)
return NULL;
for (;;) {
struct sp_node *w = NULL;
struct rb_node *prev = rb_prev(n);
if (!prev)
break;
w = rb_entry(prev, struct sp_node, nd);
if (w->end <= start)
break;
n = prev;
}
return rb_entry(n, struct sp_node, nd);
}
/*
* Insert a new shared policy into the list. Caller holds sp->lock for
* writing.
*/
static void sp_insert(struct shared_policy *sp, struct sp_node *new)
{
struct rb_node **p = &sp->root.rb_node;
struct rb_node *parent = NULL;
struct sp_node *nd;
while (*p) {
parent = *p;
nd = rb_entry(parent, struct sp_node, nd);
if (new->start < nd->start)
p = &(*p)->rb_left;
else if (new->end > nd->end)
p = &(*p)->rb_right;
else
BUG();
}
rb_link_node(&new->nd, parent, p);
rb_insert_color(&new->nd, &sp->root);
pr_debug("inserting %lx-%lx: %d\n", new->start, new->end,
new->policy ? new->policy->mode : 0);
}
/* Find shared policy intersecting idx */
struct mempolicy *
mpol_shared_policy_lookup(struct shared_policy *sp, unsigned long idx)
{
struct mempolicy *pol = NULL;
struct sp_node *sn;
if (!sp->root.rb_node)
return NULL;
read_lock(&sp->lock);
sn = sp_lookup(sp, idx, idx+1);
if (sn) {
mpol_get(sn->policy);
pol = sn->policy;
}
read_unlock(&sp->lock);
return pol;
}
static void sp_free(struct sp_node *n)
{
mpol_put(n->policy);
kmem_cache_free(sn_cache, n);
}
/**
* mpol_misplaced - check whether current page node is valid in policy
*
* @page: page to be checked
* @vma: vm area where page mapped
* @addr: virtual address where page mapped
*
* Lookup current policy node id for vma,addr and "compare to" page's
* node id.
*
* Returns:
* -1 - not misplaced, page is in the right node
* node - node id where the page should be
*
* Policy determination "mimics" alloc_page_vma().
* Called from fault path where we know the vma and faulting address.
*/
int mpol_misplaced(struct page *page, struct vm_area_struct *vma, unsigned long addr)
{
struct mempolicy *pol;
struct zoneref *z;
int curnid = page_to_nid(page);
unsigned long pgoff;
int thiscpu = raw_smp_processor_id();
int thisnid = cpu_to_node(thiscpu);
int polnid = -1;
int ret = -1;
BUG_ON(!vma);
pol = get_vma_policy(vma, addr);
if (!(pol->flags & MPOL_F_MOF))
goto out;
switch (pol->mode) {
case MPOL_INTERLEAVE:
BUG_ON(addr >= vma->vm_end);
BUG_ON(addr < vma->vm_start);
pgoff = vma->vm_pgoff;
pgoff += (addr - vma->vm_start) >> PAGE_SHIFT;
polnid = offset_il_node(pol, vma, pgoff);
break;
case MPOL_PREFERRED:
if (pol->flags & MPOL_F_LOCAL)
polnid = numa_node_id();
else
polnid = pol->v.preferred_node;
break;
case MPOL_BIND:
/*
* allows binding to multiple nodes.
* use current page if in policy nodemask,
* else select nearest allowed node, if any.
* If no allowed nodes, use current [!misplaced].
*/
if (node_isset(curnid, pol->v.nodes))
goto out;
z = first_zones_zonelist(
node_zonelist(numa_node_id(), GFP_HIGHUSER),
gfp_zone(GFP_HIGHUSER),
&pol->v.nodes);
polnid = z->zone->node;
break;
default:
BUG();
}
/* Migrate the page towards the node whose CPU is referencing it */
if (pol->flags & MPOL_F_MORON) {
polnid = thisnid;
if (!should_numa_migrate_memory(current, page, curnid, thiscpu))
goto out;
}
if (curnid != polnid)
ret = polnid;
out:
mpol_cond_put(pol);
return ret;
}
/*
* Drop the (possibly final) reference to task->mempolicy. It needs to be
* dropped after task->mempolicy is set to NULL so that any allocation done as
* part of its kmem_cache_free(), such as by KASAN, doesn't reference a freed
* policy.
*/
void mpol_put_task_policy(struct task_struct *task)
{
struct mempolicy *pol;
task_lock(task);
pol = task->mempolicy;
task->mempolicy = NULL;
task_unlock(task);
mpol_put(pol);
}
static void sp_delete(struct shared_policy *sp, struct sp_node *n)
{
pr_debug("deleting %lx-l%lx\n", n->start, n->end);
rb_erase(&n->nd, &sp->root);
sp_free(n);
}
static void sp_node_init(struct sp_node *node, unsigned long start,
unsigned long end, struct mempolicy *pol)
{
node->start = start;
node->end = end;
node->policy = pol;
}
static struct sp_node *sp_alloc(unsigned long start, unsigned long end,
struct mempolicy *pol)
{
struct sp_node *n;
struct mempolicy *newpol;
n = kmem_cache_alloc(sn_cache, GFP_KERNEL);
if (!n)
return NULL;
newpol = mpol_dup(pol);
if (IS_ERR(newpol)) {
kmem_cache_free(sn_cache, n);
return NULL;
}
newpol->flags |= MPOL_F_SHARED;
sp_node_init(n, start, end, newpol);
return n;
}
/* Replace a policy range. */
static int shared_policy_replace(struct shared_policy *sp, unsigned long start,
unsigned long end, struct sp_node *new)
{
struct sp_node *n;
struct sp_node *n_new = NULL;
struct mempolicy *mpol_new = NULL;
int ret = 0;
restart:
write_lock(&sp->lock);
n = sp_lookup(sp, start, end);
/* Take care of old policies in the same range. */
while (n && n->start < end) {
struct rb_node *next = rb_next(&n->nd);
if (n->start >= start) {
if (n->end <= end)
sp_delete(sp, n);
else
n->start = end;
} else {
/* Old policy spanning whole new range. */
if (n->end > end) {
if (!n_new)
goto alloc_new;
*mpol_new = *n->policy;
atomic_set(&mpol_new->refcnt, 1);
sp_node_init(n_new, end, n->end, mpol_new);
n->end = start;
sp_insert(sp, n_new);
n_new = NULL;
mpol_new = NULL;
break;
} else
n->end = start;
}
if (!next)
break;
n = rb_entry(next, struct sp_node, nd);
}
if (new)
sp_insert(sp, new);
write_unlock(&sp->lock);
ret = 0;
err_out:
if (mpol_new)
mpol_put(mpol_new);
if (n_new)
kmem_cache_free(sn_cache, n_new);
return ret;
alloc_new:
write_unlock(&sp->lock);
ret = -ENOMEM;
n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL);
if (!n_new)
goto err_out;
mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!mpol_new)
goto err_out;
goto restart;
}
/**
* mpol_shared_policy_init - initialize shared policy for inode
* @sp: pointer to inode shared policy
* @mpol: struct mempolicy to install
*
* Install non-NULL @mpol in inode's shared policy rb-tree.
* On entry, the current task has a reference on a non-NULL @mpol.
* This must be released on exit.
* This is called at get_inode() calls and we can use GFP_KERNEL.
*/
void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol)
{
int ret;
sp->root = RB_ROOT; /* empty tree == default mempolicy */
rwlock_init(&sp->lock);
if (mpol) {
struct vm_area_struct pvma;
struct mempolicy *new;
NODEMASK_SCRATCH(scratch);
if (!scratch)
goto put_mpol;
/* contextualize the tmpfs mount point mempolicy */
new = mpol_new(mpol->mode, mpol->flags, &mpol->w.user_nodemask);
if (IS_ERR(new))
goto free_scratch; /* no valid nodemask intersection */
task_lock(current);
ret = mpol_set_nodemask(new, &mpol->w.user_nodemask, scratch);
task_unlock(current);
if (ret)
goto put_new;
/* Create pseudo-vma that contains just the policy */
memset(&pvma, 0, sizeof(struct vm_area_struct));
pvma.vm_end = TASK_SIZE; /* policy covers entire file */
mpol_set_shared_policy(sp, &pvma, new); /* adds ref */
put_new:
mpol_put(new); /* drop initial ref */
free_scratch:
NODEMASK_SCRATCH_FREE(scratch);
put_mpol:
mpol_put(mpol); /* drop our incoming ref on sb mpol */
}
}
int mpol_set_shared_policy(struct shared_policy *info,
struct vm_area_struct *vma, struct mempolicy *npol)
{
int err;
struct sp_node *new = NULL;
unsigned long sz = vma_pages(vma);
pr_debug("set_shared_policy %lx sz %lu %d %d %lx\n",
vma->vm_pgoff,
sz, npol ? npol->mode : -1,
npol ? npol->flags : -1,
npol ? nodes_addr(npol->v.nodes)[0] : NUMA_NO_NODE);
if (npol) {
new = sp_alloc(vma->vm_pgoff, vma->vm_pgoff + sz, npol);
if (!new)
return -ENOMEM;
}
err = shared_policy_replace(info, vma->vm_pgoff, vma->vm_pgoff+sz, new);
if (err && new)
sp_free(new);
return err;
}
/* Free a backing policy store on inode delete. */
void mpol_free_shared_policy(struct shared_policy *p)
{
struct sp_node *n;
struct rb_node *next;
if (!p->root.rb_node)
return;
write_lock(&p->lock);
next = rb_first(&p->root);
while (next) {
n = rb_entry(next, struct sp_node, nd);
next = rb_next(&n->nd);
sp_delete(p, n);
}
write_unlock(&p->lock);
}
#ifdef CONFIG_NUMA_BALANCING
static int __initdata numabalancing_override;
static void __init check_numabalancing_enable(void)
{
bool numabalancing_default = false;
if (IS_ENABLED(CONFIG_NUMA_BALANCING_DEFAULT_ENABLED))
numabalancing_default = true;
/* Parsed by setup_numabalancing. override == 1 enables, -1 disables */
if (numabalancing_override)
set_numabalancing_state(numabalancing_override == 1);
if (num_online_nodes() > 1 && !numabalancing_override) {
pr_info("%s automatic NUMA balancing. Configure with numa_balancing= or the kernel.numa_balancing sysctl\n",
numabalancing_default ? "Enabling" : "Disabling");
set_numabalancing_state(numabalancing_default);
}
}
static int __init setup_numabalancing(char *str)
{
int ret = 0;
if (!str)
goto out;
if (!strcmp(str, "enable")) {
numabalancing_override = 1;
ret = 1;
} else if (!strcmp(str, "disable")) {
numabalancing_override = -1;
ret = 1;
}
out:
if (!ret)
pr_warn("Unable to parse numa_balancing=\n");
return ret;
}
__setup("numa_balancing=", setup_numabalancing);
#else
static inline void __init check_numabalancing_enable(void)
{
}
#endif /* CONFIG_NUMA_BALANCING */
/* assumes fs == KERNEL_DS */
void __init numa_policy_init(void)
{
nodemask_t interleave_nodes;
unsigned long largest = 0;
int nid, prefer = 0;
policy_cache = kmem_cache_create("numa_policy",
sizeof(struct mempolicy),
0, SLAB_PANIC, NULL);
sn_cache = kmem_cache_create("shared_policy_node",
sizeof(struct sp_node),
0, SLAB_PANIC, NULL);
for_each_node(nid) {
preferred_node_policy[nid] = (struct mempolicy) {
.refcnt = ATOMIC_INIT(1),
.mode = MPOL_PREFERRED,
.flags = MPOL_F_MOF | MPOL_F_MORON,
.v = { .preferred_node = nid, },
};
}
/*
* Set interleaving policy for system init. Interleaving is only
* enabled across suitably sized nodes (default is >= 16MB), or
* fall back to the largest node if they're all smaller.
*/
nodes_clear(interleave_nodes);
for_each_node_state(nid, N_MEMORY) {
unsigned long total_pages = node_present_pages(nid);
/* Preserve the largest node */
if (largest < total_pages) {
largest = total_pages;
prefer = nid;
}
/* Interleave this node? */
if ((total_pages << PAGE_SHIFT) >= (16 << 20))
node_set(nid, interleave_nodes);
}
/* All too small, use the largest */
if (unlikely(nodes_empty(interleave_nodes)))
node_set(prefer, interleave_nodes);
if (do_set_mempolicy(MPOL_INTERLEAVE, 0, &interleave_nodes))
pr_err("%s: interleaving failed\n", __func__);
check_numabalancing_enable();
}
/* Reset policy of current process to default */
void numa_default_policy(void)
{
do_set_mempolicy(MPOL_DEFAULT, 0, NULL);
}
/*
* Parse and format mempolicy from/to strings
*/
/*
* "local" is implemented internally by MPOL_PREFERRED with MPOL_F_LOCAL flag.
*/
static const char * const policy_modes[] =
{
[MPOL_DEFAULT] = "default",
[MPOL_PREFERRED] = "prefer",
[MPOL_BIND] = "bind",
[MPOL_INTERLEAVE] = "interleave",
[MPOL_LOCAL] = "local",
};
#ifdef CONFIG_TMPFS
/**
* mpol_parse_str - parse string to mempolicy, for tmpfs mpol mount option.
* @str: string containing mempolicy to parse
* @mpol: pointer to struct mempolicy pointer, returned on success.
*
* Format of input:
* <mode>[=<flags>][:<nodelist>]
*
* On success, returns 0, else 1
*/
int mpol_parse_str(char *str, struct mempolicy **mpol)
{
struct mempolicy *new = NULL;
unsigned short mode;
unsigned short mode_flags;
nodemask_t nodes;
char *nodelist = strchr(str, ':');
char *flags = strchr(str, '=');
int err = 1;
if (nodelist) {
/* NUL-terminate mode or flags string */
*nodelist++ = '\0';
if (nodelist_parse(nodelist, nodes))
goto out;
if (!nodes_subset(nodes, node_states[N_MEMORY]))
goto out;
} else
nodes_clear(nodes);
if (flags)
*flags++ = '\0'; /* terminate mode string */
for (mode = 0; mode < MPOL_MAX; mode++) {
if (!strcmp(str, policy_modes[mode])) {
break;
}
}
if (mode >= MPOL_MAX)
goto out;
switch (mode) {
case MPOL_PREFERRED:
/*
* Insist on a nodelist of one node only
*/
if (nodelist) {
char *rest = nodelist;
while (isdigit(*rest))
rest++;
if (*rest)
goto out;
}
break;
case MPOL_INTERLEAVE:
/*
* Default to online nodes with memory if no nodelist
*/
if (!nodelist)
nodes = node_states[N_MEMORY];
break;
case MPOL_LOCAL:
/*
* Don't allow a nodelist; mpol_new() checks flags
*/
if (nodelist)
goto out;
mode = MPOL_PREFERRED;
break;
case MPOL_DEFAULT:
/*
* Insist on a empty nodelist
*/
if (!nodelist)
err = 0;
goto out;
case MPOL_BIND:
/*
* Insist on a nodelist
*/
if (!nodelist)
goto out;
}
mode_flags = 0;
if (flags) {
/*
* Currently, we only support two mutually exclusive
* mode flags.
*/
if (!strcmp(flags, "static"))
mode_flags |= MPOL_F_STATIC_NODES;
else if (!strcmp(flags, "relative"))
mode_flags |= MPOL_F_RELATIVE_NODES;
else
goto out;
}
new = mpol_new(mode, mode_flags, &nodes);
if (IS_ERR(new))
goto out;
/*
* Save nodes for mpol_to_str() to show the tmpfs mount options
* for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.
*/
if (mode != MPOL_PREFERRED)
new->v.nodes = nodes;
else if (nodelist)
new->v.preferred_node = first_node(nodes);
else
new->flags |= MPOL_F_LOCAL;
/*
* Save nodes for contextualization: this will be used to "clone"
* the mempolicy in a specific context [cpuset] at a later time.
*/
new->w.user_nodemask = nodes;
err = 0;
out:
/* Restore string for error message */
if (nodelist)
*--nodelist = ':';
if (flags)
*--flags = '=';
if (!err)
*mpol = new;
return err;
}
#endif /* CONFIG_TMPFS */
/**
* mpol_to_str - format a mempolicy structure for printing
* @buffer: to contain formatted mempolicy string
* @maxlen: length of @buffer
* @pol: pointer to mempolicy to be formatted
*
* Convert @pol into a string. If @buffer is too short, truncate the string.
* Recommend a @maxlen of at least 32 for the longest mode, "interleave", the
* longest flag, "relative", and to display at least a few node ids.
*/
void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol)
{
char *p = buffer;
nodemask_t nodes = NODE_MASK_NONE;
unsigned short mode = MPOL_DEFAULT;
unsigned short flags = 0;
if (pol && pol != &default_policy && !(pol->flags & MPOL_F_MORON)) {
mode = pol->mode;
flags = pol->flags;
}
switch (mode) {
case MPOL_DEFAULT:
break;
case MPOL_PREFERRED:
if (flags & MPOL_F_LOCAL)
mode = MPOL_LOCAL;
else
node_set(pol->v.preferred_node, nodes);
break;
case MPOL_BIND:
case MPOL_INTERLEAVE:
nodes = pol->v.nodes;
break;
default:
WARN_ON_ONCE(1);
snprintf(p, maxlen, "unknown");
return;
}
p += snprintf(p, maxlen, "%s", policy_modes[mode]);
if (flags & MPOL_MODE_FLAGS) {
p += snprintf(p, buffer + maxlen - p, "=");
/*
* Currently, the only defined flags are mutually exclusive
*/
if (flags & MPOL_F_STATIC_NODES)
p += snprintf(p, buffer + maxlen - p, "static");
else if (flags & MPOL_F_RELATIVE_NODES)
p += snprintf(p, buffer + maxlen - p, "relative");
}
if (!nodes_empty(nodes))
p += scnprintf(p, buffer + maxlen - p, ":%*pbl",
nodemask_pr_args(&nodes));
}
| ./CrossVul/dataset_final_sorted/CWE-388/c/bad_3289_0 |
crossvul-cpp_data_good_3321_0 | /*
* hid-cp2112.c - Silicon Labs HID USB to SMBus master bridge
* Copyright (c) 2013,2014 Uplogix, Inc.
* David Barksdale <dbarksdale@uplogix.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*/
/*
* The Silicon Labs CP2112 chip is a USB HID device which provides an
* SMBus controller for talking to slave devices and 8 GPIO pins. The
* host communicates with the CP2112 via raw HID reports.
*
* Data Sheet:
* http://www.silabs.com/Support%20Documents/TechnicalDocs/CP2112.pdf
* Programming Interface Specification:
* http://www.silabs.com/Support%20Documents/TechnicalDocs/AN495.pdf
*/
#include <linux/gpio.h>
#include <linux/gpio/driver.h>
#include <linux/hid.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/nls.h>
#include <linux/usb/ch9.h>
#include "hid-ids.h"
#define CP2112_REPORT_MAX_LENGTH 64
#define CP2112_GPIO_CONFIG_LENGTH 5
#define CP2112_GPIO_GET_LENGTH 2
#define CP2112_GPIO_SET_LENGTH 3
enum {
CP2112_GPIO_CONFIG = 0x02,
CP2112_GPIO_GET = 0x03,
CP2112_GPIO_SET = 0x04,
CP2112_GET_VERSION_INFO = 0x05,
CP2112_SMBUS_CONFIG = 0x06,
CP2112_DATA_READ_REQUEST = 0x10,
CP2112_DATA_WRITE_READ_REQUEST = 0x11,
CP2112_DATA_READ_FORCE_SEND = 0x12,
CP2112_DATA_READ_RESPONSE = 0x13,
CP2112_DATA_WRITE_REQUEST = 0x14,
CP2112_TRANSFER_STATUS_REQUEST = 0x15,
CP2112_TRANSFER_STATUS_RESPONSE = 0x16,
CP2112_CANCEL_TRANSFER = 0x17,
CP2112_LOCK_BYTE = 0x20,
CP2112_USB_CONFIG = 0x21,
CP2112_MANUFACTURER_STRING = 0x22,
CP2112_PRODUCT_STRING = 0x23,
CP2112_SERIAL_STRING = 0x24,
};
enum {
STATUS0_IDLE = 0x00,
STATUS0_BUSY = 0x01,
STATUS0_COMPLETE = 0x02,
STATUS0_ERROR = 0x03,
};
enum {
STATUS1_TIMEOUT_NACK = 0x00,
STATUS1_TIMEOUT_BUS = 0x01,
STATUS1_ARBITRATION_LOST = 0x02,
STATUS1_READ_INCOMPLETE = 0x03,
STATUS1_WRITE_INCOMPLETE = 0x04,
STATUS1_SUCCESS = 0x05,
};
struct cp2112_smbus_config_report {
u8 report; /* CP2112_SMBUS_CONFIG */
__be32 clock_speed; /* Hz */
u8 device_address; /* Stored in the upper 7 bits */
u8 auto_send_read; /* 1 = enabled, 0 = disabled */
__be16 write_timeout; /* ms, 0 = no timeout */
__be16 read_timeout; /* ms, 0 = no timeout */
u8 scl_low_timeout; /* 1 = enabled, 0 = disabled */
__be16 retry_time; /* # of retries, 0 = no limit */
} __packed;
struct cp2112_usb_config_report {
u8 report; /* CP2112_USB_CONFIG */
__le16 vid; /* Vendor ID */
__le16 pid; /* Product ID */
u8 max_power; /* Power requested in 2mA units */
u8 power_mode; /* 0x00 = bus powered
0x01 = self powered & regulator off
0x02 = self powered & regulator on */
u8 release_major;
u8 release_minor;
u8 mask; /* What fields to program */
} __packed;
struct cp2112_read_req_report {
u8 report; /* CP2112_DATA_READ_REQUEST */
u8 slave_address;
__be16 length;
} __packed;
struct cp2112_write_read_req_report {
u8 report; /* CP2112_DATA_WRITE_READ_REQUEST */
u8 slave_address;
__be16 length;
u8 target_address_length;
u8 target_address[16];
} __packed;
struct cp2112_write_req_report {
u8 report; /* CP2112_DATA_WRITE_REQUEST */
u8 slave_address;
u8 length;
u8 data[61];
} __packed;
struct cp2112_force_read_report {
u8 report; /* CP2112_DATA_READ_FORCE_SEND */
__be16 length;
} __packed;
struct cp2112_xfer_status_report {
u8 report; /* CP2112_TRANSFER_STATUS_RESPONSE */
u8 status0; /* STATUS0_* */
u8 status1; /* STATUS1_* */
__be16 retries;
__be16 length;
} __packed;
struct cp2112_string_report {
u8 dummy; /* force .string to be aligned */
u8 report; /* CP2112_*_STRING */
u8 length; /* length in bytes of everyting after .report */
u8 type; /* USB_DT_STRING */
wchar_t string[30]; /* UTF16_LITTLE_ENDIAN string */
} __packed;
/* Number of times to request transfer status before giving up waiting for a
transfer to complete. This may need to be changed if SMBUS clock, retries,
or read/write/scl_low timeout settings are changed. */
static const int XFER_STATUS_RETRIES = 10;
/* Time in ms to wait for a CP2112_DATA_READ_RESPONSE or
CP2112_TRANSFER_STATUS_RESPONSE. */
static const int RESPONSE_TIMEOUT = 50;
static const struct hid_device_id cp2112_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_CYGNAL, USB_DEVICE_ID_CYGNAL_CP2112) },
{ }
};
MODULE_DEVICE_TABLE(hid, cp2112_devices);
struct cp2112_device {
struct i2c_adapter adap;
struct hid_device *hdev;
wait_queue_head_t wait;
u8 read_data[61];
u8 read_length;
u8 hwversion;
int xfer_status;
atomic_t read_avail;
atomic_t xfer_avail;
struct gpio_chip gc;
u8 *in_out_buffer;
struct mutex lock;
struct gpio_desc *desc[8];
bool gpio_poll;
struct delayed_work gpio_poll_worker;
unsigned long irq_mask;
u8 gpio_prev_state;
};
static int gpio_push_pull = 0xFF;
module_param(gpio_push_pull, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(gpio_push_pull, "GPIO push-pull configuration bitmask");
static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto exit;
}
buf[1] &= ~(1 << offset);
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto exit;
}
ret = 0;
exit:
mutex_unlock(&dev->lock);
return ret < 0 ? ret : -EIO;
}
static void cp2112_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
buf[0] = CP2112_GPIO_SET;
buf[1] = value ? 0xff : 0;
buf[2] = 1 << offset;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_SET, buf,
CP2112_GPIO_SET_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0)
hid_err(hdev, "error setting GPIO values: %d\n", ret);
mutex_unlock(&dev->lock);
}
static int cp2112_gpio_get_all(struct gpio_chip *chip)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_GET, buf,
CP2112_GPIO_GET_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_GET_LENGTH) {
hid_err(hdev, "error requesting GPIO values: %d\n", ret);
ret = ret < 0 ? ret : -EIO;
goto exit;
}
ret = buf[1];
exit:
mutex_unlock(&dev->lock);
return ret;
}
static int cp2112_gpio_get(struct gpio_chip *chip, unsigned int offset)
{
int ret;
ret = cp2112_gpio_get_all(chip);
if (ret < 0)
return ret;
return (ret >> offset) & 1;
}
static int cp2112_gpio_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto fail;
}
buf[1] |= 1 << offset;
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto fail;
}
mutex_unlock(&dev->lock);
/*
* Set gpio value when output direction is already set,
* as specified in AN495, Rev. 0.2, cpt. 4.4
*/
cp2112_gpio_set(chip, offset, value);
return 0;
fail:
mutex_unlock(&dev->lock);
return ret < 0 ? ret : -EIO;
}
static int cp2112_hid_get(struct hid_device *hdev, unsigned char report_number,
u8 *data, size_t count, unsigned char report_type)
{
u8 *buf;
int ret;
buf = kmalloc(count, GFP_KERNEL);
if (!buf)
return -ENOMEM;
ret = hid_hw_raw_request(hdev, report_number, buf, count,
report_type, HID_REQ_GET_REPORT);
memcpy(data, buf, count);
kfree(buf);
return ret;
}
static int cp2112_hid_output(struct hid_device *hdev, u8 *data, size_t count,
unsigned char report_type)
{
u8 *buf;
int ret;
buf = kmemdup(data, count, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (report_type == HID_OUTPUT_REPORT)
ret = hid_hw_output_report(hdev, buf, count);
else
ret = hid_hw_raw_request(hdev, buf[0], buf, count, report_type,
HID_REQ_SET_REPORT);
kfree(buf);
return ret;
}
static int cp2112_wait(struct cp2112_device *dev, atomic_t *avail)
{
int ret = 0;
/* We have sent either a CP2112_TRANSFER_STATUS_REQUEST or a
* CP2112_DATA_READ_FORCE_SEND and we are waiting for the response to
* come in cp2112_raw_event or timeout. There will only be one of these
* in flight at any one time. The timeout is extremely large and is a
* last resort if the CP2112 has died. If we do timeout we don't expect
* to receive the response which would cause data races, it's not like
* we can do anything about it anyway.
*/
ret = wait_event_interruptible_timeout(dev->wait,
atomic_read(avail), msecs_to_jiffies(RESPONSE_TIMEOUT));
if (-ERESTARTSYS == ret)
return ret;
if (!ret)
return -ETIMEDOUT;
atomic_set(avail, 0);
return 0;
}
static int cp2112_xfer_status(struct cp2112_device *dev)
{
struct hid_device *hdev = dev->hdev;
u8 buf[2];
int ret;
buf[0] = CP2112_TRANSFER_STATUS_REQUEST;
buf[1] = 0x01;
atomic_set(&dev->xfer_avail, 0);
ret = cp2112_hid_output(hdev, buf, 2, HID_OUTPUT_REPORT);
if (ret < 0) {
hid_warn(hdev, "Error requesting status: %d\n", ret);
return ret;
}
ret = cp2112_wait(dev, &dev->xfer_avail);
if (ret)
return ret;
return dev->xfer_status;
}
static int cp2112_read(struct cp2112_device *dev, u8 *data, size_t size)
{
struct hid_device *hdev = dev->hdev;
struct cp2112_force_read_report report;
int ret;
if (size > sizeof(dev->read_data))
size = sizeof(dev->read_data);
report.report = CP2112_DATA_READ_FORCE_SEND;
report.length = cpu_to_be16(size);
atomic_set(&dev->read_avail, 0);
ret = cp2112_hid_output(hdev, &report.report, sizeof(report),
HID_OUTPUT_REPORT);
if (ret < 0) {
hid_warn(hdev, "Error requesting data: %d\n", ret);
return ret;
}
ret = cp2112_wait(dev, &dev->read_avail);
if (ret)
return ret;
hid_dbg(hdev, "read %d of %zd bytes requested\n",
dev->read_length, size);
if (size > dev->read_length)
size = dev->read_length;
memcpy(data, dev->read_data, size);
return dev->read_length;
}
static int cp2112_read_req(void *buf, u8 slave_address, u16 length)
{
struct cp2112_read_req_report *report = buf;
if (length < 1 || length > 512)
return -EINVAL;
report->report = CP2112_DATA_READ_REQUEST;
report->slave_address = slave_address << 1;
report->length = cpu_to_be16(length);
return sizeof(*report);
}
static int cp2112_write_read_req(void *buf, u8 slave_address, u16 length,
u8 command, u8 *data, u8 data_length)
{
struct cp2112_write_read_req_report *report = buf;
if (length < 1 || length > 512
|| data_length > sizeof(report->target_address) - 1)
return -EINVAL;
report->report = CP2112_DATA_WRITE_READ_REQUEST;
report->slave_address = slave_address << 1;
report->length = cpu_to_be16(length);
report->target_address_length = data_length + 1;
report->target_address[0] = command;
memcpy(&report->target_address[1], data, data_length);
return data_length + 6;
}
static int cp2112_write_req(void *buf, u8 slave_address, u8 command, u8 *data,
u8 data_length)
{
struct cp2112_write_req_report *report = buf;
if (data_length > sizeof(report->data) - 1)
return -EINVAL;
report->report = CP2112_DATA_WRITE_REQUEST;
report->slave_address = slave_address << 1;
report->length = data_length + 1;
report->data[0] = command;
memcpy(&report->data[1], data, data_length);
return data_length + 4;
}
static int cp2112_i2c_write_req(void *buf, u8 slave_address, u8 *data,
u8 data_length)
{
struct cp2112_write_req_report *report = buf;
if (data_length > sizeof(report->data))
return -EINVAL;
report->report = CP2112_DATA_WRITE_REQUEST;
report->slave_address = slave_address << 1;
report->length = data_length;
memcpy(report->data, data, data_length);
return data_length + 3;
}
static int cp2112_i2c_write_read_req(void *buf, u8 slave_address,
u8 *addr, int addr_length,
int read_length)
{
struct cp2112_write_read_req_report *report = buf;
if (read_length < 1 || read_length > 512 ||
addr_length > sizeof(report->target_address))
return -EINVAL;
report->report = CP2112_DATA_WRITE_READ_REQUEST;
report->slave_address = slave_address << 1;
report->length = cpu_to_be16(read_length);
report->target_address_length = addr_length;
memcpy(report->target_address, addr, addr_length);
return addr_length + 5;
}
static int cp2112_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
int num)
{
struct cp2112_device *dev = (struct cp2112_device *)adap->algo_data;
struct hid_device *hdev = dev->hdev;
u8 buf[64];
ssize_t count;
ssize_t read_length = 0;
u8 *read_buf = NULL;
unsigned int retries;
int ret;
hid_dbg(hdev, "I2C %d messages\n", num);
if (num == 1) {
if (msgs->flags & I2C_M_RD) {
hid_dbg(hdev, "I2C read %#04x len %d\n",
msgs->addr, msgs->len);
read_length = msgs->len;
read_buf = msgs->buf;
count = cp2112_read_req(buf, msgs->addr, msgs->len);
} else {
hid_dbg(hdev, "I2C write %#04x len %d\n",
msgs->addr, msgs->len);
count = cp2112_i2c_write_req(buf, msgs->addr,
msgs->buf, msgs->len);
}
if (count < 0)
return count;
} else if (dev->hwversion > 1 && /* no repeated start in rev 1 */
num == 2 &&
msgs[0].addr == msgs[1].addr &&
!(msgs[0].flags & I2C_M_RD) && (msgs[1].flags & I2C_M_RD)) {
hid_dbg(hdev, "I2C write-read %#04x wlen %d rlen %d\n",
msgs[0].addr, msgs[0].len, msgs[1].len);
read_length = msgs[1].len;
read_buf = msgs[1].buf;
count = cp2112_i2c_write_read_req(buf, msgs[0].addr,
msgs[0].buf, msgs[0].len, msgs[1].len);
if (count < 0)
return count;
} else {
hid_err(hdev,
"Multi-message I2C transactions not supported\n");
return -EOPNOTSUPP;
}
ret = hid_hw_power(hdev, PM_HINT_FULLON);
if (ret < 0) {
hid_err(hdev, "power management error: %d\n", ret);
return ret;
}
ret = cp2112_hid_output(hdev, buf, count, HID_OUTPUT_REPORT);
if (ret < 0) {
hid_warn(hdev, "Error starting transaction: %d\n", ret);
goto power_normal;
}
for (retries = 0; retries < XFER_STATUS_RETRIES; ++retries) {
ret = cp2112_xfer_status(dev);
if (-EBUSY == ret)
continue;
if (ret < 0)
goto power_normal;
break;
}
if (XFER_STATUS_RETRIES <= retries) {
hid_warn(hdev, "Transfer timed out, cancelling.\n");
buf[0] = CP2112_CANCEL_TRANSFER;
buf[1] = 0x01;
ret = cp2112_hid_output(hdev, buf, 2, HID_OUTPUT_REPORT);
if (ret < 0)
hid_warn(hdev, "Error cancelling transaction: %d\n",
ret);
ret = -ETIMEDOUT;
goto power_normal;
}
for (count = 0; count < read_length;) {
ret = cp2112_read(dev, read_buf + count, read_length - count);
if (ret < 0)
goto power_normal;
if (ret == 0) {
hid_err(hdev, "read returned 0\n");
ret = -EIO;
goto power_normal;
}
count += ret;
if (count > read_length) {
/*
* The hardware returned too much data.
* This is mostly harmless because cp2112_read()
* has a limit check so didn't overrun our
* buffer. Nevertheless, we return an error
* because something is seriously wrong and
* it shouldn't go unnoticed.
*/
hid_err(hdev, "long read: %d > %zd\n",
ret, read_length - count + ret);
ret = -EIO;
goto power_normal;
}
}
/* return the number of transferred messages */
ret = num;
power_normal:
hid_hw_power(hdev, PM_HINT_NORMAL);
hid_dbg(hdev, "I2C transfer finished: %d\n", ret);
return ret;
}
static int cp2112_xfer(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write, u8 command,
int size, union i2c_smbus_data *data)
{
struct cp2112_device *dev = (struct cp2112_device *)adap->algo_data;
struct hid_device *hdev = dev->hdev;
u8 buf[64];
__le16 word;
ssize_t count;
size_t read_length = 0;
unsigned int retries;
int ret;
hid_dbg(hdev, "%s addr 0x%x flags 0x%x cmd 0x%x size %d\n",
read_write == I2C_SMBUS_WRITE ? "write" : "read",
addr, flags, command, size);
switch (size) {
case I2C_SMBUS_BYTE:
read_length = 1;
if (I2C_SMBUS_READ == read_write)
count = cp2112_read_req(buf, addr, read_length);
else
count = cp2112_write_req(buf, addr, command, NULL,
0);
break;
case I2C_SMBUS_BYTE_DATA:
read_length = 1;
if (I2C_SMBUS_READ == read_write)
count = cp2112_write_read_req(buf, addr, read_length,
command, NULL, 0);
else
count = cp2112_write_req(buf, addr, command,
&data->byte, 1);
break;
case I2C_SMBUS_WORD_DATA:
read_length = 2;
word = cpu_to_le16(data->word);
if (I2C_SMBUS_READ == read_write)
count = cp2112_write_read_req(buf, addr, read_length,
command, NULL, 0);
else
count = cp2112_write_req(buf, addr, command,
(u8 *)&word, 2);
break;
case I2C_SMBUS_PROC_CALL:
size = I2C_SMBUS_WORD_DATA;
read_write = I2C_SMBUS_READ;
read_length = 2;
word = cpu_to_le16(data->word);
count = cp2112_write_read_req(buf, addr, read_length, command,
(u8 *)&word, 2);
break;
case I2C_SMBUS_I2C_BLOCK_DATA:
size = I2C_SMBUS_BLOCK_DATA;
/* fallthrough */
case I2C_SMBUS_BLOCK_DATA:
if (I2C_SMBUS_READ == read_write) {
count = cp2112_write_read_req(buf, addr,
I2C_SMBUS_BLOCK_MAX,
command, NULL, 0);
} else {
count = cp2112_write_req(buf, addr, command,
data->block,
data->block[0] + 1);
}
break;
case I2C_SMBUS_BLOCK_PROC_CALL:
size = I2C_SMBUS_BLOCK_DATA;
read_write = I2C_SMBUS_READ;
count = cp2112_write_read_req(buf, addr, I2C_SMBUS_BLOCK_MAX,
command, data->block,
data->block[0] + 1);
break;
default:
hid_warn(hdev, "Unsupported transaction %d\n", size);
return -EOPNOTSUPP;
}
if (count < 0)
return count;
ret = hid_hw_power(hdev, PM_HINT_FULLON);
if (ret < 0) {
hid_err(hdev, "power management error: %d\n", ret);
return ret;
}
ret = cp2112_hid_output(hdev, buf, count, HID_OUTPUT_REPORT);
if (ret < 0) {
hid_warn(hdev, "Error starting transaction: %d\n", ret);
goto power_normal;
}
for (retries = 0; retries < XFER_STATUS_RETRIES; ++retries) {
ret = cp2112_xfer_status(dev);
if (-EBUSY == ret)
continue;
if (ret < 0)
goto power_normal;
break;
}
if (XFER_STATUS_RETRIES <= retries) {
hid_warn(hdev, "Transfer timed out, cancelling.\n");
buf[0] = CP2112_CANCEL_TRANSFER;
buf[1] = 0x01;
ret = cp2112_hid_output(hdev, buf, 2, HID_OUTPUT_REPORT);
if (ret < 0)
hid_warn(hdev, "Error cancelling transaction: %d\n",
ret);
ret = -ETIMEDOUT;
goto power_normal;
}
if (I2C_SMBUS_WRITE == read_write) {
ret = 0;
goto power_normal;
}
if (I2C_SMBUS_BLOCK_DATA == size)
read_length = ret;
ret = cp2112_read(dev, buf, read_length);
if (ret < 0)
goto power_normal;
if (ret != read_length) {
hid_warn(hdev, "short read: %d < %zd\n", ret, read_length);
ret = -EIO;
goto power_normal;
}
switch (size) {
case I2C_SMBUS_BYTE:
case I2C_SMBUS_BYTE_DATA:
data->byte = buf[0];
break;
case I2C_SMBUS_WORD_DATA:
data->word = le16_to_cpup((__le16 *)buf);
break;
case I2C_SMBUS_BLOCK_DATA:
if (read_length > I2C_SMBUS_BLOCK_MAX) {
ret = -EPROTO;
goto power_normal;
}
memcpy(data->block, buf, read_length);
break;
}
ret = 0;
power_normal:
hid_hw_power(hdev, PM_HINT_NORMAL);
hid_dbg(hdev, "transfer finished: %d\n", ret);
return ret;
}
static u32 cp2112_functionality(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C |
I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_WORD_DATA |
I2C_FUNC_SMBUS_BLOCK_DATA |
I2C_FUNC_SMBUS_I2C_BLOCK |
I2C_FUNC_SMBUS_PROC_CALL |
I2C_FUNC_SMBUS_BLOCK_PROC_CALL;
}
static const struct i2c_algorithm smbus_algorithm = {
.master_xfer = cp2112_i2c_xfer,
.smbus_xfer = cp2112_xfer,
.functionality = cp2112_functionality,
};
static int cp2112_get_usb_config(struct hid_device *hdev,
struct cp2112_usb_config_report *cfg)
{
int ret;
ret = cp2112_hid_get(hdev, CP2112_USB_CONFIG, (u8 *)cfg, sizeof(*cfg),
HID_FEATURE_REPORT);
if (ret != sizeof(*cfg)) {
hid_err(hdev, "error reading usb config: %d\n", ret);
if (ret < 0)
return ret;
return -EIO;
}
return 0;
}
static int cp2112_set_usb_config(struct hid_device *hdev,
struct cp2112_usb_config_report *cfg)
{
int ret;
BUG_ON(cfg->report != CP2112_USB_CONFIG);
ret = cp2112_hid_output(hdev, (u8 *)cfg, sizeof(*cfg),
HID_FEATURE_REPORT);
if (ret != sizeof(*cfg)) {
hid_err(hdev, "error writing usb config: %d\n", ret);
if (ret < 0)
return ret;
return -EIO;
}
return 0;
}
static void chmod_sysfs_attrs(struct hid_device *hdev);
#define CP2112_CONFIG_ATTR(name, store, format, ...) \
static ssize_t name##_store(struct device *kdev, \
struct device_attribute *attr, const char *buf, \
size_t count) \
{ \
struct hid_device *hdev = to_hid_device(kdev); \
struct cp2112_usb_config_report cfg; \
int ret = cp2112_get_usb_config(hdev, &cfg); \
if (ret) \
return ret; \
store; \
ret = cp2112_set_usb_config(hdev, &cfg); \
if (ret) \
return ret; \
chmod_sysfs_attrs(hdev); \
return count; \
} \
static ssize_t name##_show(struct device *kdev, \
struct device_attribute *attr, char *buf) \
{ \
struct hid_device *hdev = to_hid_device(kdev); \
struct cp2112_usb_config_report cfg; \
int ret = cp2112_get_usb_config(hdev, &cfg); \
if (ret) \
return ret; \
return scnprintf(buf, PAGE_SIZE, format, ##__VA_ARGS__); \
} \
static DEVICE_ATTR_RW(name);
CP2112_CONFIG_ATTR(vendor_id, ({
u16 vid;
if (sscanf(buf, "%hi", &vid) != 1)
return -EINVAL;
cfg.vid = cpu_to_le16(vid);
cfg.mask = 0x01;
}), "0x%04x\n", le16_to_cpu(cfg.vid));
CP2112_CONFIG_ATTR(product_id, ({
u16 pid;
if (sscanf(buf, "%hi", &pid) != 1)
return -EINVAL;
cfg.pid = cpu_to_le16(pid);
cfg.mask = 0x02;
}), "0x%04x\n", le16_to_cpu(cfg.pid));
CP2112_CONFIG_ATTR(max_power, ({
int mA;
if (sscanf(buf, "%i", &mA) != 1)
return -EINVAL;
cfg.max_power = (mA + 1) / 2;
cfg.mask = 0x04;
}), "%u mA\n", cfg.max_power * 2);
CP2112_CONFIG_ATTR(power_mode, ({
if (sscanf(buf, "%hhi", &cfg.power_mode) != 1)
return -EINVAL;
cfg.mask = 0x08;
}), "%u\n", cfg.power_mode);
CP2112_CONFIG_ATTR(release_version, ({
if (sscanf(buf, "%hhi.%hhi", &cfg.release_major, &cfg.release_minor)
!= 2)
return -EINVAL;
cfg.mask = 0x10;
}), "%u.%u\n", cfg.release_major, cfg.release_minor);
#undef CP2112_CONFIG_ATTR
struct cp2112_pstring_attribute {
struct device_attribute attr;
unsigned char report;
};
static ssize_t pstr_store(struct device *kdev,
struct device_attribute *kattr, const char *buf,
size_t count)
{
struct hid_device *hdev = to_hid_device(kdev);
struct cp2112_pstring_attribute *attr =
container_of(kattr, struct cp2112_pstring_attribute, attr);
struct cp2112_string_report report;
int ret;
memset(&report, 0, sizeof(report));
ret = utf8s_to_utf16s(buf, count, UTF16_LITTLE_ENDIAN,
report.string, ARRAY_SIZE(report.string));
report.report = attr->report;
report.length = ret * sizeof(report.string[0]) + 2;
report.type = USB_DT_STRING;
ret = cp2112_hid_output(hdev, &report.report, report.length + 1,
HID_FEATURE_REPORT);
if (ret != report.length + 1) {
hid_err(hdev, "error writing %s string: %d\n", kattr->attr.name,
ret);
if (ret < 0)
return ret;
return -EIO;
}
chmod_sysfs_attrs(hdev);
return count;
}
static ssize_t pstr_show(struct device *kdev,
struct device_attribute *kattr, char *buf)
{
struct hid_device *hdev = to_hid_device(kdev);
struct cp2112_pstring_attribute *attr =
container_of(kattr, struct cp2112_pstring_attribute, attr);
struct cp2112_string_report report;
u8 length;
int ret;
ret = cp2112_hid_get(hdev, attr->report, &report.report,
sizeof(report) - 1, HID_FEATURE_REPORT);
if (ret < 3) {
hid_err(hdev, "error reading %s string: %d\n", kattr->attr.name,
ret);
if (ret < 0)
return ret;
return -EIO;
}
if (report.length < 2) {
hid_err(hdev, "invalid %s string length: %d\n",
kattr->attr.name, report.length);
return -EIO;
}
length = report.length > ret - 1 ? ret - 1 : report.length;
length = (length - 2) / sizeof(report.string[0]);
ret = utf16s_to_utf8s(report.string, length, UTF16_LITTLE_ENDIAN, buf,
PAGE_SIZE - 1);
buf[ret++] = '\n';
return ret;
}
#define CP2112_PSTR_ATTR(name, _report) \
static struct cp2112_pstring_attribute dev_attr_##name = { \
.attr = __ATTR(name, (S_IWUSR | S_IRUGO), pstr_show, pstr_store), \
.report = _report, \
};
CP2112_PSTR_ATTR(manufacturer, CP2112_MANUFACTURER_STRING);
CP2112_PSTR_ATTR(product, CP2112_PRODUCT_STRING);
CP2112_PSTR_ATTR(serial, CP2112_SERIAL_STRING);
#undef CP2112_PSTR_ATTR
static const struct attribute_group cp2112_attr_group = {
.attrs = (struct attribute *[]){
&dev_attr_vendor_id.attr,
&dev_attr_product_id.attr,
&dev_attr_max_power.attr,
&dev_attr_power_mode.attr,
&dev_attr_release_version.attr,
&dev_attr_manufacturer.attr.attr,
&dev_attr_product.attr.attr,
&dev_attr_serial.attr.attr,
NULL
}
};
/* Chmoding our sysfs attributes is simply a way to expose which fields in the
* PROM have already been programmed. We do not depend on this preventing
* writing to these attributes since the CP2112 will simply ignore writes to
* already-programmed fields. This is why there is no sense in fixing this
* racy behaviour.
*/
static void chmod_sysfs_attrs(struct hid_device *hdev)
{
struct attribute **attr;
u8 buf[2];
int ret;
ret = cp2112_hid_get(hdev, CP2112_LOCK_BYTE, buf, sizeof(buf),
HID_FEATURE_REPORT);
if (ret != sizeof(buf)) {
hid_err(hdev, "error reading lock byte: %d\n", ret);
return;
}
for (attr = cp2112_attr_group.attrs; *attr; ++attr) {
umode_t mode = (buf[1] & 1) ? S_IWUSR | S_IRUGO : S_IRUGO;
ret = sysfs_chmod_file(&hdev->dev.kobj, *attr, mode);
if (ret < 0)
hid_err(hdev, "error chmoding sysfs file %s\n",
(*attr)->name);
buf[1] >>= 1;
}
}
static void cp2112_gpio_irq_ack(struct irq_data *d)
{
}
static void cp2112_gpio_irq_mask(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct cp2112_device *dev = gpiochip_get_data(gc);
__clear_bit(d->hwirq, &dev->irq_mask);
}
static void cp2112_gpio_irq_unmask(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct cp2112_device *dev = gpiochip_get_data(gc);
__set_bit(d->hwirq, &dev->irq_mask);
}
static void cp2112_gpio_poll_callback(struct work_struct *work)
{
struct cp2112_device *dev = container_of(work, struct cp2112_device,
gpio_poll_worker.work);
struct irq_data *d;
u8 gpio_mask;
u8 virqs = (u8)dev->irq_mask;
u32 irq_type;
int irq, virq, ret;
ret = cp2112_gpio_get_all(&dev->gc);
if (ret == -ENODEV) /* the hardware has been disconnected */
return;
if (ret < 0)
goto exit;
gpio_mask = ret;
while (virqs) {
virq = ffs(virqs) - 1;
virqs &= ~BIT(virq);
if (!dev->gc.to_irq)
break;
irq = dev->gc.to_irq(&dev->gc, virq);
d = irq_get_irq_data(irq);
if (!d)
continue;
irq_type = irqd_get_trigger_type(d);
if (gpio_mask & BIT(virq)) {
/* Level High */
if (irq_type & IRQ_TYPE_LEVEL_HIGH)
handle_nested_irq(irq);
if ((irq_type & IRQ_TYPE_EDGE_RISING) &&
!(dev->gpio_prev_state & BIT(virq)))
handle_nested_irq(irq);
} else {
/* Level Low */
if (irq_type & IRQ_TYPE_LEVEL_LOW)
handle_nested_irq(irq);
if ((irq_type & IRQ_TYPE_EDGE_FALLING) &&
(dev->gpio_prev_state & BIT(virq)))
handle_nested_irq(irq);
}
}
dev->gpio_prev_state = gpio_mask;
exit:
if (dev->gpio_poll)
schedule_delayed_work(&dev->gpio_poll_worker, 10);
}
static unsigned int cp2112_gpio_irq_startup(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct cp2112_device *dev = gpiochip_get_data(gc);
INIT_DELAYED_WORK(&dev->gpio_poll_worker, cp2112_gpio_poll_callback);
cp2112_gpio_direction_input(gc, d->hwirq);
if (!dev->gpio_poll) {
dev->gpio_poll = true;
schedule_delayed_work(&dev->gpio_poll_worker, 0);
}
cp2112_gpio_irq_unmask(d);
return 0;
}
static void cp2112_gpio_irq_shutdown(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct cp2112_device *dev = gpiochip_get_data(gc);
cancel_delayed_work_sync(&dev->gpio_poll_worker);
}
static int cp2112_gpio_irq_type(struct irq_data *d, unsigned int type)
{
return 0;
}
static struct irq_chip cp2112_gpio_irqchip = {
.name = "cp2112-gpio",
.irq_startup = cp2112_gpio_irq_startup,
.irq_shutdown = cp2112_gpio_irq_shutdown,
.irq_ack = cp2112_gpio_irq_ack,
.irq_mask = cp2112_gpio_irq_mask,
.irq_unmask = cp2112_gpio_irq_unmask,
.irq_set_type = cp2112_gpio_irq_type,
};
static int __maybe_unused cp2112_allocate_irq(struct cp2112_device *dev,
int pin)
{
int ret;
if (dev->desc[pin])
return -EINVAL;
dev->desc[pin] = gpiochip_request_own_desc(&dev->gc, pin,
"HID/I2C:Event");
if (IS_ERR(dev->desc[pin])) {
dev_err(dev->gc.parent, "Failed to request GPIO\n");
return PTR_ERR(dev->desc[pin]);
}
ret = gpiochip_lock_as_irq(&dev->gc, pin);
if (ret) {
dev_err(dev->gc.parent, "Failed to lock GPIO as interrupt\n");
goto err_desc;
}
ret = gpiod_to_irq(dev->desc[pin]);
if (ret < 0) {
dev_err(dev->gc.parent, "Failed to translate GPIO to IRQ\n");
goto err_lock;
}
return ret;
err_lock:
gpiochip_unlock_as_irq(&dev->gc, pin);
err_desc:
gpiochip_free_own_desc(dev->desc[pin]);
dev->desc[pin] = NULL;
return ret;
}
static int cp2112_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
struct cp2112_device *dev;
u8 buf[3];
struct cp2112_smbus_config_report config;
int ret;
dev = devm_kzalloc(&hdev->dev, sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->in_out_buffer = devm_kzalloc(&hdev->dev, CP2112_REPORT_MAX_LENGTH,
GFP_KERNEL);
if (!dev->in_out_buffer)
return -ENOMEM;
mutex_init(&dev->lock);
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
return ret;
}
ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
if (ret) {
hid_err(hdev, "hw start failed\n");
return ret;
}
ret = hid_hw_open(hdev);
if (ret) {
hid_err(hdev, "hw open failed\n");
goto err_hid_stop;
}
ret = hid_hw_power(hdev, PM_HINT_FULLON);
if (ret < 0) {
hid_err(hdev, "power management error: %d\n", ret);
goto err_hid_close;
}
ret = cp2112_hid_get(hdev, CP2112_GET_VERSION_INFO, buf, sizeof(buf),
HID_FEATURE_REPORT);
if (ret != sizeof(buf)) {
hid_err(hdev, "error requesting version\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
hid_info(hdev, "Part Number: 0x%02X Device Version: 0x%02X\n",
buf[1], buf[2]);
ret = cp2112_hid_get(hdev, CP2112_SMBUS_CONFIG, (u8 *)&config,
sizeof(config), HID_FEATURE_REPORT);
if (ret != sizeof(config)) {
hid_err(hdev, "error requesting SMBus config\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
config.retry_time = cpu_to_be16(1);
ret = cp2112_hid_output(hdev, (u8 *)&config, sizeof(config),
HID_FEATURE_REPORT);
if (ret != sizeof(config)) {
hid_err(hdev, "error setting SMBus config\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
hid_set_drvdata(hdev, (void *)dev);
dev->hdev = hdev;
dev->adap.owner = THIS_MODULE;
dev->adap.class = I2C_CLASS_HWMON;
dev->adap.algo = &smbus_algorithm;
dev->adap.algo_data = dev;
dev->adap.dev.parent = &hdev->dev;
snprintf(dev->adap.name, sizeof(dev->adap.name),
"CP2112 SMBus Bridge on hiddev%d", hdev->minor);
dev->hwversion = buf[2];
init_waitqueue_head(&dev->wait);
hid_device_io_start(hdev);
ret = i2c_add_adapter(&dev->adap);
hid_device_io_stop(hdev);
if (ret) {
hid_err(hdev, "error registering i2c adapter\n");
goto err_power_normal;
}
hid_dbg(hdev, "adapter registered\n");
dev->gc.label = "cp2112_gpio";
dev->gc.direction_input = cp2112_gpio_direction_input;
dev->gc.direction_output = cp2112_gpio_direction_output;
dev->gc.set = cp2112_gpio_set;
dev->gc.get = cp2112_gpio_get;
dev->gc.base = -1;
dev->gc.ngpio = 8;
dev->gc.can_sleep = 1;
dev->gc.parent = &hdev->dev;
ret = gpiochip_add_data(&dev->gc, dev);
if (ret < 0) {
hid_err(hdev, "error registering gpio chip\n");
goto err_free_i2c;
}
ret = sysfs_create_group(&hdev->dev.kobj, &cp2112_attr_group);
if (ret < 0) {
hid_err(hdev, "error creating sysfs attrs\n");
goto err_gpiochip_remove;
}
chmod_sysfs_attrs(hdev);
hid_hw_power(hdev, PM_HINT_NORMAL);
ret = gpiochip_irqchip_add(&dev->gc, &cp2112_gpio_irqchip, 0,
handle_simple_irq, IRQ_TYPE_NONE);
if (ret) {
dev_err(dev->gc.parent, "failed to add IRQ chip\n");
goto err_sysfs_remove;
}
return ret;
err_sysfs_remove:
sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group);
err_gpiochip_remove:
gpiochip_remove(&dev->gc);
err_free_i2c:
i2c_del_adapter(&dev->adap);
err_power_normal:
hid_hw_power(hdev, PM_HINT_NORMAL);
err_hid_close:
hid_hw_close(hdev);
err_hid_stop:
hid_hw_stop(hdev);
return ret;
}
static void cp2112_remove(struct hid_device *hdev)
{
struct cp2112_device *dev = hid_get_drvdata(hdev);
int i;
sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group);
i2c_del_adapter(&dev->adap);
if (dev->gpio_poll) {
dev->gpio_poll = false;
cancel_delayed_work_sync(&dev->gpio_poll_worker);
}
for (i = 0; i < ARRAY_SIZE(dev->desc); i++) {
gpiochip_unlock_as_irq(&dev->gc, i);
gpiochip_free_own_desc(dev->desc[i]);
}
gpiochip_remove(&dev->gc);
/* i2c_del_adapter has finished removing all i2c devices from our
* adapter. Well behaved devices should no longer call our cp2112_xfer
* and should have waited for any pending calls to finish. It has also
* waited for device_unregister(&adap->dev) to complete. Therefore we
* can safely free our struct cp2112_device.
*/
hid_hw_close(hdev);
hid_hw_stop(hdev);
}
static int cp2112_raw_event(struct hid_device *hdev, struct hid_report *report,
u8 *data, int size)
{
struct cp2112_device *dev = hid_get_drvdata(hdev);
struct cp2112_xfer_status_report *xfer = (void *)data;
switch (data[0]) {
case CP2112_TRANSFER_STATUS_RESPONSE:
hid_dbg(hdev, "xfer status: %02x %02x %04x %04x\n",
xfer->status0, xfer->status1,
be16_to_cpu(xfer->retries), be16_to_cpu(xfer->length));
switch (xfer->status0) {
case STATUS0_IDLE:
dev->xfer_status = -EAGAIN;
break;
case STATUS0_BUSY:
dev->xfer_status = -EBUSY;
break;
case STATUS0_COMPLETE:
dev->xfer_status = be16_to_cpu(xfer->length);
break;
case STATUS0_ERROR:
switch (xfer->status1) {
case STATUS1_TIMEOUT_NACK:
case STATUS1_TIMEOUT_BUS:
dev->xfer_status = -ETIMEDOUT;
break;
default:
dev->xfer_status = -EIO;
break;
}
break;
default:
dev->xfer_status = -EINVAL;
break;
}
atomic_set(&dev->xfer_avail, 1);
break;
case CP2112_DATA_READ_RESPONSE:
hid_dbg(hdev, "read response: %02x %02x\n", data[1], data[2]);
dev->read_length = data[2];
if (dev->read_length > sizeof(dev->read_data))
dev->read_length = sizeof(dev->read_data);
memcpy(dev->read_data, &data[3], dev->read_length);
atomic_set(&dev->read_avail, 1);
break;
default:
hid_err(hdev, "unknown report\n");
return 0;
}
wake_up_interruptible(&dev->wait);
return 1;
}
static struct hid_driver cp2112_driver = {
.name = "cp2112",
.id_table = cp2112_devices,
.probe = cp2112_probe,
.remove = cp2112_remove,
.raw_event = cp2112_raw_event,
};
module_hid_driver(cp2112_driver);
MODULE_DESCRIPTION("Silicon Labs HID USB to SMBus master bridge");
MODULE_AUTHOR("David Barksdale <dbarksdale@uplogix.com>");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-388/c/good_3321_0 |
crossvul-cpp_data_bad_3122_0 | /*
* Copyright © 2014 Broadcom
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/device.h>
#include <linux/io.h>
#include "uapi/drm/vc4_drm.h"
#include "vc4_drv.h"
#include "vc4_regs.h"
#include "vc4_trace.h"
static void
vc4_queue_hangcheck(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
mod_timer(&vc4->hangcheck.timer,
round_jiffies_up(jiffies + msecs_to_jiffies(100)));
}
struct vc4_hang_state {
struct drm_vc4_get_hang_state user_state;
u32 bo_count;
struct drm_gem_object **bo;
};
static void
vc4_free_hang_state(struct drm_device *dev, struct vc4_hang_state *state)
{
unsigned int i;
for (i = 0; i < state->user_state.bo_count; i++)
drm_gem_object_unreference_unlocked(state->bo[i]);
kfree(state);
}
int
vc4_get_hang_state_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vc4_get_hang_state *get_state = data;
struct drm_vc4_get_hang_state_bo *bo_state;
struct vc4_hang_state *kernel_state;
struct drm_vc4_get_hang_state *state;
struct vc4_dev *vc4 = to_vc4_dev(dev);
unsigned long irqflags;
u32 i;
int ret = 0;
spin_lock_irqsave(&vc4->job_lock, irqflags);
kernel_state = vc4->hang_state;
if (!kernel_state) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return -ENOENT;
}
state = &kernel_state->user_state;
/* If the user's array isn't big enough, just return the
* required array size.
*/
if (get_state->bo_count < state->bo_count) {
get_state->bo_count = state->bo_count;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return 0;
}
vc4->hang_state = NULL;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
/* Save the user's BO pointer, so we don't stomp it with the memcpy. */
state->bo = get_state->bo;
memcpy(get_state, state, sizeof(*state));
bo_state = kcalloc(state->bo_count, sizeof(*bo_state), GFP_KERNEL);
if (!bo_state) {
ret = -ENOMEM;
goto err_free;
}
for (i = 0; i < state->bo_count; i++) {
struct vc4_bo *vc4_bo = to_vc4_bo(kernel_state->bo[i]);
u32 handle;
ret = drm_gem_handle_create(file_priv, kernel_state->bo[i],
&handle);
if (ret) {
state->bo_count = i - 1;
goto err;
}
bo_state[i].handle = handle;
bo_state[i].paddr = vc4_bo->base.paddr;
bo_state[i].size = vc4_bo->base.base.size;
}
if (copy_to_user((void __user *)(uintptr_t)get_state->bo,
bo_state,
state->bo_count * sizeof(*bo_state)))
ret = -EFAULT;
kfree(bo_state);
err_free:
vc4_free_hang_state(dev, kernel_state);
err:
return ret;
}
static void
vc4_save_hang_state(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct drm_vc4_get_hang_state *state;
struct vc4_hang_state *kernel_state;
struct vc4_exec_info *exec[2];
struct vc4_bo *bo;
unsigned long irqflags;
unsigned int i, j, unref_list_count, prev_idx;
kernel_state = kcalloc(1, sizeof(*kernel_state), GFP_KERNEL);
if (!kernel_state)
return;
state = &kernel_state->user_state;
spin_lock_irqsave(&vc4->job_lock, irqflags);
exec[0] = vc4_first_bin_job(vc4);
exec[1] = vc4_first_render_job(vc4);
if (!exec[0] && !exec[1]) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return;
}
/* Get the bos from both binner and renderer into hang state. */
state->bo_count = 0;
for (i = 0; i < 2; i++) {
if (!exec[i])
continue;
unref_list_count = 0;
list_for_each_entry(bo, &exec[i]->unref_list, unref_head)
unref_list_count++;
state->bo_count += exec[i]->bo_count + unref_list_count;
}
kernel_state->bo = kcalloc(state->bo_count,
sizeof(*kernel_state->bo), GFP_ATOMIC);
if (!kernel_state->bo) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return;
}
prev_idx = 0;
for (i = 0; i < 2; i++) {
if (!exec[i])
continue;
for (j = 0; j < exec[i]->bo_count; j++) {
drm_gem_object_reference(&exec[i]->bo[j]->base);
kernel_state->bo[j + prev_idx] = &exec[i]->bo[j]->base;
}
list_for_each_entry(bo, &exec[i]->unref_list, unref_head) {
drm_gem_object_reference(&bo->base.base);
kernel_state->bo[j + prev_idx] = &bo->base.base;
j++;
}
prev_idx = j + 1;
}
if (exec[0])
state->start_bin = exec[0]->ct0ca;
if (exec[1])
state->start_render = exec[1]->ct1ca;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
state->ct0ca = V3D_READ(V3D_CTNCA(0));
state->ct0ea = V3D_READ(V3D_CTNEA(0));
state->ct1ca = V3D_READ(V3D_CTNCA(1));
state->ct1ea = V3D_READ(V3D_CTNEA(1));
state->ct0cs = V3D_READ(V3D_CTNCS(0));
state->ct1cs = V3D_READ(V3D_CTNCS(1));
state->ct0ra0 = V3D_READ(V3D_CT00RA0);
state->ct1ra0 = V3D_READ(V3D_CT01RA0);
state->bpca = V3D_READ(V3D_BPCA);
state->bpcs = V3D_READ(V3D_BPCS);
state->bpoa = V3D_READ(V3D_BPOA);
state->bpos = V3D_READ(V3D_BPOS);
state->vpmbase = V3D_READ(V3D_VPMBASE);
state->dbge = V3D_READ(V3D_DBGE);
state->fdbgo = V3D_READ(V3D_FDBGO);
state->fdbgb = V3D_READ(V3D_FDBGB);
state->fdbgr = V3D_READ(V3D_FDBGR);
state->fdbgs = V3D_READ(V3D_FDBGS);
state->errstat = V3D_READ(V3D_ERRSTAT);
spin_lock_irqsave(&vc4->job_lock, irqflags);
if (vc4->hang_state) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
vc4_free_hang_state(dev, kernel_state);
} else {
vc4->hang_state = kernel_state;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
}
}
static void
vc4_reset(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
DRM_INFO("Resetting GPU.\n");
mutex_lock(&vc4->power_lock);
if (vc4->power_refcount) {
/* Power the device off and back on the by dropping the
* reference on runtime PM.
*/
pm_runtime_put_sync_suspend(&vc4->v3d->pdev->dev);
pm_runtime_get_sync(&vc4->v3d->pdev->dev);
}
mutex_unlock(&vc4->power_lock);
vc4_irq_reset(dev);
/* Rearm the hangcheck -- another job might have been waiting
* for our hung one to get kicked off, and vc4_irq_reset()
* would have started it.
*/
vc4_queue_hangcheck(dev);
}
static void
vc4_reset_work(struct work_struct *work)
{
struct vc4_dev *vc4 =
container_of(work, struct vc4_dev, hangcheck.reset_work);
vc4_save_hang_state(vc4->dev);
vc4_reset(vc4->dev);
}
static void
vc4_hangcheck_elapsed(unsigned long data)
{
struct drm_device *dev = (struct drm_device *)data;
struct vc4_dev *vc4 = to_vc4_dev(dev);
uint32_t ct0ca, ct1ca;
unsigned long irqflags;
struct vc4_exec_info *bin_exec, *render_exec;
spin_lock_irqsave(&vc4->job_lock, irqflags);
bin_exec = vc4_first_bin_job(vc4);
render_exec = vc4_first_render_job(vc4);
/* If idle, we can stop watching for hangs. */
if (!bin_exec && !render_exec) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return;
}
ct0ca = V3D_READ(V3D_CTNCA(0));
ct1ca = V3D_READ(V3D_CTNCA(1));
/* If we've made any progress in execution, rearm the timer
* and wait.
*/
if ((bin_exec && ct0ca != bin_exec->last_ct0ca) ||
(render_exec && ct1ca != render_exec->last_ct1ca)) {
if (bin_exec)
bin_exec->last_ct0ca = ct0ca;
if (render_exec)
render_exec->last_ct1ca = ct1ca;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
vc4_queue_hangcheck(dev);
return;
}
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
/* We've gone too long with no progress, reset. This has to
* be done from a work struct, since resetting can sleep and
* this timer hook isn't allowed to.
*/
schedule_work(&vc4->hangcheck.reset_work);
}
static void
submit_cl(struct drm_device *dev, uint32_t thread, uint32_t start, uint32_t end)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
/* Set the current and end address of the control list.
* Writing the end register is what starts the job.
*/
V3D_WRITE(V3D_CTNCA(thread), start);
V3D_WRITE(V3D_CTNEA(thread), end);
}
int
vc4_wait_for_seqno(struct drm_device *dev, uint64_t seqno, uint64_t timeout_ns,
bool interruptible)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
int ret = 0;
unsigned long timeout_expire;
DEFINE_WAIT(wait);
if (vc4->finished_seqno >= seqno)
return 0;
if (timeout_ns == 0)
return -ETIME;
timeout_expire = jiffies + nsecs_to_jiffies(timeout_ns);
trace_vc4_wait_for_seqno_begin(dev, seqno, timeout_ns);
for (;;) {
prepare_to_wait(&vc4->job_wait_queue, &wait,
interruptible ? TASK_INTERRUPTIBLE :
TASK_UNINTERRUPTIBLE);
if (interruptible && signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
if (vc4->finished_seqno >= seqno)
break;
if (timeout_ns != ~0ull) {
if (time_after_eq(jiffies, timeout_expire)) {
ret = -ETIME;
break;
}
schedule_timeout(timeout_expire - jiffies);
} else {
schedule();
}
}
finish_wait(&vc4->job_wait_queue, &wait);
trace_vc4_wait_for_seqno_end(dev, seqno);
return ret;
}
static void
vc4_flush_caches(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
/* Flush the GPU L2 caches. These caches sit on top of system
* L3 (the 128kb or so shared with the CPU), and are
* non-allocating in the L3.
*/
V3D_WRITE(V3D_L2CACTL,
V3D_L2CACTL_L2CCLR);
V3D_WRITE(V3D_SLCACTL,
VC4_SET_FIELD(0xf, V3D_SLCACTL_T1CC) |
VC4_SET_FIELD(0xf, V3D_SLCACTL_T0CC) |
VC4_SET_FIELD(0xf, V3D_SLCACTL_UCC) |
VC4_SET_FIELD(0xf, V3D_SLCACTL_ICC));
}
/* Sets the registers for the next job to be actually be executed in
* the hardware.
*
* The job_lock should be held during this.
*/
void
vc4_submit_next_bin_job(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct vc4_exec_info *exec;
again:
exec = vc4_first_bin_job(vc4);
if (!exec)
return;
vc4_flush_caches(dev);
/* Either put the job in the binner if it uses the binner, or
* immediately move it to the to-be-rendered queue.
*/
if (exec->ct0ca != exec->ct0ea) {
submit_cl(dev, 0, exec->ct0ca, exec->ct0ea);
} else {
vc4_move_job_to_render(dev, exec);
goto again;
}
}
void
vc4_submit_next_render_job(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct vc4_exec_info *exec = vc4_first_render_job(vc4);
if (!exec)
return;
submit_cl(dev, 1, exec->ct1ca, exec->ct1ea);
}
void
vc4_move_job_to_render(struct drm_device *dev, struct vc4_exec_info *exec)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
bool was_empty = list_empty(&vc4->render_job_list);
list_move_tail(&exec->head, &vc4->render_job_list);
if (was_empty)
vc4_submit_next_render_job(dev);
}
static void
vc4_update_bo_seqnos(struct vc4_exec_info *exec, uint64_t seqno)
{
struct vc4_bo *bo;
unsigned i;
for (i = 0; i < exec->bo_count; i++) {
bo = to_vc4_bo(&exec->bo[i]->base);
bo->seqno = seqno;
}
list_for_each_entry(bo, &exec->unref_list, unref_head) {
bo->seqno = seqno;
}
for (i = 0; i < exec->rcl_write_bo_count; i++) {
bo = to_vc4_bo(&exec->rcl_write_bo[i]->base);
bo->write_seqno = seqno;
}
}
/* Queues a struct vc4_exec_info for execution. If no job is
* currently executing, then submits it.
*
* Unlike most GPUs, our hardware only handles one command list at a
* time. To queue multiple jobs at once, we'd need to edit the
* previous command list to have a jump to the new one at the end, and
* then bump the end address. That's a change for a later date,
* though.
*/
static void
vc4_queue_submit(struct drm_device *dev, struct vc4_exec_info *exec)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
uint64_t seqno;
unsigned long irqflags;
spin_lock_irqsave(&vc4->job_lock, irqflags);
seqno = ++vc4->emit_seqno;
exec->seqno = seqno;
vc4_update_bo_seqnos(exec, seqno);
list_add_tail(&exec->head, &vc4->bin_job_list);
/* If no job was executing, kick ours off. Otherwise, it'll
* get started when the previous job's flush done interrupt
* occurs.
*/
if (vc4_first_bin_job(vc4) == exec) {
vc4_submit_next_bin_job(dev);
vc4_queue_hangcheck(dev);
}
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
}
/**
* Looks up a bunch of GEM handles for BOs and stores the array for
* use in the command validator that actually writes relocated
* addresses pointing to them.
*/
static int
vc4_cl_lookup_bos(struct drm_device *dev,
struct drm_file *file_priv,
struct vc4_exec_info *exec)
{
struct drm_vc4_submit_cl *args = exec->args;
uint32_t *handles;
int ret = 0;
int i;
exec->bo_count = args->bo_handle_count;
if (!exec->bo_count) {
/* See comment on bo_index for why we have to check
* this.
*/
DRM_ERROR("Rendering requires BOs to validate\n");
return -EINVAL;
}
exec->bo = drm_calloc_large(exec->bo_count,
sizeof(struct drm_gem_cma_object *));
if (!exec->bo) {
DRM_ERROR("Failed to allocate validated BO pointers\n");
return -ENOMEM;
}
handles = drm_malloc_ab(exec->bo_count, sizeof(uint32_t));
if (!handles) {
ret = -ENOMEM;
DRM_ERROR("Failed to allocate incoming GEM handles\n");
goto fail;
}
if (copy_from_user(handles,
(void __user *)(uintptr_t)args->bo_handles,
exec->bo_count * sizeof(uint32_t))) {
ret = -EFAULT;
DRM_ERROR("Failed to copy in GEM handles\n");
goto fail;
}
spin_lock(&file_priv->table_lock);
for (i = 0; i < exec->bo_count; i++) {
struct drm_gem_object *bo = idr_find(&file_priv->object_idr,
handles[i]);
if (!bo) {
DRM_ERROR("Failed to look up GEM BO %d: %d\n",
i, handles[i]);
ret = -EINVAL;
spin_unlock(&file_priv->table_lock);
goto fail;
}
drm_gem_object_reference(bo);
exec->bo[i] = (struct drm_gem_cma_object *)bo;
}
spin_unlock(&file_priv->table_lock);
fail:
drm_free_large(handles);
return ret;
}
static int
vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec)
{
struct drm_vc4_submit_cl *args = exec->args;
void *temp = NULL;
void *bin;
int ret = 0;
uint32_t bin_offset = 0;
uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size,
16);
uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size;
uint32_t exec_size = uniforms_offset + args->uniforms_size;
uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) *
args->shader_rec_count);
struct vc4_bo *bo;
if (shader_rec_offset < args->bin_cl_size ||
uniforms_offset < shader_rec_offset ||
exec_size < uniforms_offset ||
args->shader_rec_count >= (UINT_MAX /
sizeof(struct vc4_shader_state)) ||
temp_size < exec_size) {
DRM_ERROR("overflow in exec arguments\n");
goto fail;
}
/* Allocate space where we'll store the copied in user command lists
* and shader records.
*
* We don't just copy directly into the BOs because we need to
* read the contents back for validation, and I think the
* bo->vaddr is uncached access.
*/
temp = drm_malloc_ab(temp_size, 1);
if (!temp) {
DRM_ERROR("Failed to allocate storage for copying "
"in bin/render CLs.\n");
ret = -ENOMEM;
goto fail;
}
bin = temp + bin_offset;
exec->shader_rec_u = temp + shader_rec_offset;
exec->uniforms_u = temp + uniforms_offset;
exec->shader_state = temp + exec_size;
exec->shader_state_size = args->shader_rec_count;
if (copy_from_user(bin,
(void __user *)(uintptr_t)args->bin_cl,
args->bin_cl_size)) {
ret = -EFAULT;
goto fail;
}
if (copy_from_user(exec->shader_rec_u,
(void __user *)(uintptr_t)args->shader_rec,
args->shader_rec_size)) {
ret = -EFAULT;
goto fail;
}
if (copy_from_user(exec->uniforms_u,
(void __user *)(uintptr_t)args->uniforms,
args->uniforms_size)) {
ret = -EFAULT;
goto fail;
}
bo = vc4_bo_create(dev, exec_size, true);
if (IS_ERR(bo)) {
DRM_ERROR("Couldn't allocate BO for binning\n");
ret = PTR_ERR(bo);
goto fail;
}
exec->exec_bo = &bo->base;
list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head,
&exec->unref_list);
exec->ct0ca = exec->exec_bo->paddr + bin_offset;
exec->bin_u = bin;
exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset;
exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset;
exec->shader_rec_size = args->shader_rec_size;
exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset;
exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset;
exec->uniforms_size = args->uniforms_size;
ret = vc4_validate_bin_cl(dev,
exec->exec_bo->vaddr + bin_offset,
bin,
exec);
if (ret)
goto fail;
ret = vc4_validate_shader_recs(dev, exec);
if (ret)
goto fail;
/* Block waiting on any previous rendering into the CS's VBO,
* IB, or textures, so that pixels are actually written by the
* time we try to read them.
*/
ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true);
fail:
drm_free_large(temp);
return ret;
}
static void
vc4_complete_exec(struct drm_device *dev, struct vc4_exec_info *exec)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
unsigned i;
if (exec->bo) {
for (i = 0; i < exec->bo_count; i++)
drm_gem_object_unreference_unlocked(&exec->bo[i]->base);
drm_free_large(exec->bo);
}
while (!list_empty(&exec->unref_list)) {
struct vc4_bo *bo = list_first_entry(&exec->unref_list,
struct vc4_bo, unref_head);
list_del(&bo->unref_head);
drm_gem_object_unreference_unlocked(&bo->base.base);
}
mutex_lock(&vc4->power_lock);
if (--vc4->power_refcount == 0) {
pm_runtime_mark_last_busy(&vc4->v3d->pdev->dev);
pm_runtime_put_autosuspend(&vc4->v3d->pdev->dev);
}
mutex_unlock(&vc4->power_lock);
kfree(exec);
}
void
vc4_job_handle_completed(struct vc4_dev *vc4)
{
unsigned long irqflags;
struct vc4_seqno_cb *cb, *cb_temp;
spin_lock_irqsave(&vc4->job_lock, irqflags);
while (!list_empty(&vc4->job_done_list)) {
struct vc4_exec_info *exec =
list_first_entry(&vc4->job_done_list,
struct vc4_exec_info, head);
list_del(&exec->head);
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
vc4_complete_exec(vc4->dev, exec);
spin_lock_irqsave(&vc4->job_lock, irqflags);
}
list_for_each_entry_safe(cb, cb_temp, &vc4->seqno_cb_list, work.entry) {
if (cb->seqno <= vc4->finished_seqno) {
list_del_init(&cb->work.entry);
schedule_work(&cb->work);
}
}
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
}
static void vc4_seqno_cb_work(struct work_struct *work)
{
struct vc4_seqno_cb *cb = container_of(work, struct vc4_seqno_cb, work);
cb->func(cb);
}
int vc4_queue_seqno_cb(struct drm_device *dev,
struct vc4_seqno_cb *cb, uint64_t seqno,
void (*func)(struct vc4_seqno_cb *cb))
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
int ret = 0;
unsigned long irqflags;
cb->func = func;
INIT_WORK(&cb->work, vc4_seqno_cb_work);
spin_lock_irqsave(&vc4->job_lock, irqflags);
if (seqno > vc4->finished_seqno) {
cb->seqno = seqno;
list_add_tail(&cb->work.entry, &vc4->seqno_cb_list);
} else {
schedule_work(&cb->work);
}
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return ret;
}
/* Scheduled when any job has been completed, this walks the list of
* jobs that had completed and unrefs their BOs and frees their exec
* structs.
*/
static void
vc4_job_done_work(struct work_struct *work)
{
struct vc4_dev *vc4 =
container_of(work, struct vc4_dev, job_done_work);
vc4_job_handle_completed(vc4);
}
static int
vc4_wait_for_seqno_ioctl_helper(struct drm_device *dev,
uint64_t seqno,
uint64_t *timeout_ns)
{
unsigned long start = jiffies;
int ret = vc4_wait_for_seqno(dev, seqno, *timeout_ns, true);
if ((ret == -EINTR || ret == -ERESTARTSYS) && *timeout_ns != ~0ull) {
uint64_t delta = jiffies_to_nsecs(jiffies - start);
if (*timeout_ns >= delta)
*timeout_ns -= delta;
}
return ret;
}
int
vc4_wait_seqno_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vc4_wait_seqno *args = data;
return vc4_wait_for_seqno_ioctl_helper(dev, args->seqno,
&args->timeout_ns);
}
int
vc4_wait_bo_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
int ret;
struct drm_vc4_wait_bo *args = data;
struct drm_gem_object *gem_obj;
struct vc4_bo *bo;
if (args->pad != 0)
return -EINVAL;
gem_obj = drm_gem_object_lookup(file_priv, args->handle);
if (!gem_obj) {
DRM_ERROR("Failed to look up GEM BO %d\n", args->handle);
return -EINVAL;
}
bo = to_vc4_bo(gem_obj);
ret = vc4_wait_for_seqno_ioctl_helper(dev, bo->seqno,
&args->timeout_ns);
drm_gem_object_unreference_unlocked(gem_obj);
return ret;
}
/**
* Submits a command list to the VC4.
*
* This is what is called batchbuffer emitting on other hardware.
*/
int
vc4_submit_cl_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct drm_vc4_submit_cl *args = data;
struct vc4_exec_info *exec;
int ret = 0;
if ((args->flags & ~VC4_SUBMIT_CL_USE_CLEAR_COLOR) != 0) {
DRM_ERROR("Unknown flags: 0x%02x\n", args->flags);
return -EINVAL;
}
exec = kcalloc(1, sizeof(*exec), GFP_KERNEL);
if (!exec) {
DRM_ERROR("malloc failure on exec struct\n");
return -ENOMEM;
}
mutex_lock(&vc4->power_lock);
if (vc4->power_refcount++ == 0)
ret = pm_runtime_get_sync(&vc4->v3d->pdev->dev);
mutex_unlock(&vc4->power_lock);
if (ret < 0) {
kfree(exec);
return ret;
}
exec->args = args;
INIT_LIST_HEAD(&exec->unref_list);
ret = vc4_cl_lookup_bos(dev, file_priv, exec);
if (ret)
goto fail;
if (exec->args->bin_cl_size != 0) {
ret = vc4_get_bcl(dev, exec);
if (ret)
goto fail;
} else {
exec->ct0ca = 0;
exec->ct0ea = 0;
}
ret = vc4_get_rcl(dev, exec);
if (ret)
goto fail;
/* Clear this out of the struct we'll be putting in the queue,
* since it's part of our stack.
*/
exec->args = NULL;
vc4_queue_submit(dev, exec);
/* Return the seqno for our job. */
args->seqno = vc4->emit_seqno;
return 0;
fail:
vc4_complete_exec(vc4->dev, exec);
return ret;
}
void
vc4_gem_init(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
INIT_LIST_HEAD(&vc4->bin_job_list);
INIT_LIST_HEAD(&vc4->render_job_list);
INIT_LIST_HEAD(&vc4->job_done_list);
INIT_LIST_HEAD(&vc4->seqno_cb_list);
spin_lock_init(&vc4->job_lock);
INIT_WORK(&vc4->hangcheck.reset_work, vc4_reset_work);
setup_timer(&vc4->hangcheck.timer,
vc4_hangcheck_elapsed,
(unsigned long)dev);
INIT_WORK(&vc4->job_done_work, vc4_job_done_work);
mutex_init(&vc4->power_lock);
}
void
vc4_gem_destroy(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
/* Waiting for exec to finish would need to be done before
* unregistering V3D.
*/
WARN_ON(vc4->emit_seqno != vc4->finished_seqno);
/* V3D should already have disabled its interrupt and cleared
* the overflow allocation registers. Now free the object.
*/
if (vc4->overflow_mem) {
drm_gem_object_unreference_unlocked(&vc4->overflow_mem->base.base);
vc4->overflow_mem = NULL;
}
if (vc4->hang_state)
vc4_free_hang_state(dev, vc4->hang_state);
vc4_bo_cache_destroy(dev);
}
| ./CrossVul/dataset_final_sorted/CWE-388/c/bad_3122_0 |
crossvul-cpp_data_good_5494_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 "irq.h"
#include "mmu.h"
#include "cpuid.h"
#include "lapic.h"
#include <linux/kvm_host.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/sched.h>
#include <linux/moduleparam.h>
#include <linux/mod_devicetable.h>
#include <linux/trace_events.h>
#include <linux/slab.h>
#include <linux/tboot.h>
#include <linux/hrtimer.h>
#include "kvm_cache_regs.h"
#include "x86.h"
#include <asm/cpu.h>
#include <asm/io.h>
#include <asm/desc.h>
#include <asm/vmx.h>
#include <asm/virtext.h>
#include <asm/mce.h>
#include <asm/fpu/internal.h>
#include <asm/perf_event.h>
#include <asm/debugreg.h>
#include <asm/kexec.h>
#include <asm/apic.h>
#include <asm/irq_remapping.h>
#include "trace.h"
#include "pmu.h"
#define __ex(x) __kvm_handle_fault_on_reboot(x)
#define __ex_clear(x, reg) \
____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
MODULE_AUTHOR("Qumranet");
MODULE_LICENSE("GPL");
static const struct x86_cpu_id vmx_cpu_id[] = {
X86_FEATURE_MATCH(X86_FEATURE_VMX),
{}
};
MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
static bool __read_mostly enable_vpid = 1;
module_param_named(vpid, enable_vpid, bool, 0444);
static bool __read_mostly flexpriority_enabled = 1;
module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
static bool __read_mostly enable_ept = 1;
module_param_named(ept, enable_ept, bool, S_IRUGO);
static bool __read_mostly enable_unrestricted_guest = 1;
module_param_named(unrestricted_guest,
enable_unrestricted_guest, bool, S_IRUGO);
static bool __read_mostly enable_ept_ad_bits = 1;
module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
static bool __read_mostly emulate_invalid_guest_state = true;
module_param(emulate_invalid_guest_state, bool, S_IRUGO);
static bool __read_mostly vmm_exclusive = 1;
module_param(vmm_exclusive, bool, S_IRUGO);
static bool __read_mostly fasteoi = 1;
module_param(fasteoi, bool, S_IRUGO);
static bool __read_mostly enable_apicv = 1;
module_param(enable_apicv, bool, S_IRUGO);
static bool __read_mostly enable_shadow_vmcs = 1;
module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
/*
* If nested=1, nested virtualization is supported, i.e., guests may use
* VMX and be a hypervisor for its own guests. If nested=0, guests may not
* use VMX instructions.
*/
static bool __read_mostly nested = 0;
module_param(nested, bool, S_IRUGO);
static u64 __read_mostly host_xss;
static bool __read_mostly enable_pml = 1;
module_param_named(pml, enable_pml, bool, S_IRUGO);
#define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
/* Guest_tsc -> host_tsc conversion requires 64-bit division. */
static int __read_mostly cpu_preemption_timer_multi;
static bool __read_mostly enable_preemption_timer = 1;
#ifdef CONFIG_X86_64
module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
#endif
#define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
#define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
#define KVM_VM_CR0_ALWAYS_ON \
(KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
#define KVM_CR4_GUEST_OWNED_BITS \
(X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
| X86_CR4_OSXMMEXCPT | X86_CR4_TSD)
#define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
#define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
#define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
#define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
#define VMX_VPID_EXTENT_SUPPORTED_MASK \
(VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
/*
* Hyper-V requires all of these, so mark them as supported even though
* they are just treated the same as all-context.
*/
#define VMX_VPID_EXTENT_SUPPORTED_MASK \
(VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
/*
* These 2 parameters are used to config the controls for Pause-Loop Exiting:
* ple_gap: upper bound on the amount of time between two successive
* executions of PAUSE in a loop. Also indicate if ple enabled.
* According to test, this time is usually smaller than 128 cycles.
* ple_window: upper bound on the amount of time a guest is allowed to execute
* in a PAUSE loop. Tests indicate that most spinlocks are held for
* less than 2^12 cycles
* Time is measured based on a counter that runs at the same rate as the TSC,
* refer SDM volume 3b section 21.6.13 & 22.1.3.
*/
#define KVM_VMX_DEFAULT_PLE_GAP 128
#define KVM_VMX_DEFAULT_PLE_WINDOW 4096
#define KVM_VMX_DEFAULT_PLE_WINDOW_GROW 2
#define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
#define KVM_VMX_DEFAULT_PLE_WINDOW_MAX \
INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
module_param(ple_gap, int, S_IRUGO);
static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
module_param(ple_window, int, S_IRUGO);
/* Default doubles per-vcpu window every exit. */
static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
module_param(ple_window_grow, int, S_IRUGO);
/* Default resets per-vcpu window every exit to ple_window. */
static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
module_param(ple_window_shrink, int, S_IRUGO);
/* Default is to compute the maximum so we can never overflow. */
static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
static int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
module_param(ple_window_max, int, S_IRUGO);
extern const ulong vmx_return;
#define NR_AUTOLOAD_MSRS 8
#define VMCS02_POOL_SIZE 1
struct vmcs {
u32 revision_id;
u32 abort;
char data[0];
};
/*
* Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
* remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
* loaded on this CPU (so we can clear them if the CPU goes down).
*/
struct loaded_vmcs {
struct vmcs *vmcs;
struct vmcs *shadow_vmcs;
int cpu;
int launched;
struct list_head loaded_vmcss_on_cpu_link;
};
struct shared_msr_entry {
unsigned index;
u64 data;
u64 mask;
};
/*
* struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
* single nested guest (L2), hence the name vmcs12. Any VMX implementation has
* a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
* stored in guest memory specified by VMPTRLD, but is opaque to the guest,
* which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
* More than one of these structures may exist, if L1 runs multiple L2 guests.
* nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
* underlying hardware which will be used to run L2.
* This structure is packed to ensure that its layout is identical across
* machines (necessary for live migration).
* If there are changes in this struct, VMCS12_REVISION must be changed.
*/
typedef u64 natural_width;
struct __packed vmcs12 {
/* According to the Intel spec, a VMCS region must start with the
* following two fields. Then follow implementation-specific data.
*/
u32 revision_id;
u32 abort;
u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
u32 padding[7]; /* room for future expansion */
u64 io_bitmap_a;
u64 io_bitmap_b;
u64 msr_bitmap;
u64 vm_exit_msr_store_addr;
u64 vm_exit_msr_load_addr;
u64 vm_entry_msr_load_addr;
u64 tsc_offset;
u64 virtual_apic_page_addr;
u64 apic_access_addr;
u64 posted_intr_desc_addr;
u64 ept_pointer;
u64 eoi_exit_bitmap0;
u64 eoi_exit_bitmap1;
u64 eoi_exit_bitmap2;
u64 eoi_exit_bitmap3;
u64 xss_exit_bitmap;
u64 guest_physical_address;
u64 vmcs_link_pointer;
u64 guest_ia32_debugctl;
u64 guest_ia32_pat;
u64 guest_ia32_efer;
u64 guest_ia32_perf_global_ctrl;
u64 guest_pdptr0;
u64 guest_pdptr1;
u64 guest_pdptr2;
u64 guest_pdptr3;
u64 guest_bndcfgs;
u64 host_ia32_pat;
u64 host_ia32_efer;
u64 host_ia32_perf_global_ctrl;
u64 padding64[8]; /* room for future expansion */
/*
* To allow migration of L1 (complete with its L2 guests) between
* machines of different natural widths (32 or 64 bit), we cannot have
* unsigned long fields with no explict size. We use u64 (aliased
* natural_width) instead. Luckily, x86 is little-endian.
*/
natural_width cr0_guest_host_mask;
natural_width cr4_guest_host_mask;
natural_width cr0_read_shadow;
natural_width cr4_read_shadow;
natural_width cr3_target_value0;
natural_width cr3_target_value1;
natural_width cr3_target_value2;
natural_width cr3_target_value3;
natural_width exit_qualification;
natural_width guest_linear_address;
natural_width guest_cr0;
natural_width guest_cr3;
natural_width guest_cr4;
natural_width guest_es_base;
natural_width guest_cs_base;
natural_width guest_ss_base;
natural_width guest_ds_base;
natural_width guest_fs_base;
natural_width guest_gs_base;
natural_width guest_ldtr_base;
natural_width guest_tr_base;
natural_width guest_gdtr_base;
natural_width guest_idtr_base;
natural_width guest_dr7;
natural_width guest_rsp;
natural_width guest_rip;
natural_width guest_rflags;
natural_width guest_pending_dbg_exceptions;
natural_width guest_sysenter_esp;
natural_width guest_sysenter_eip;
natural_width host_cr0;
natural_width host_cr3;
natural_width host_cr4;
natural_width host_fs_base;
natural_width host_gs_base;
natural_width host_tr_base;
natural_width host_gdtr_base;
natural_width host_idtr_base;
natural_width host_ia32_sysenter_esp;
natural_width host_ia32_sysenter_eip;
natural_width host_rsp;
natural_width host_rip;
natural_width paddingl[8]; /* room for future expansion */
u32 pin_based_vm_exec_control;
u32 cpu_based_vm_exec_control;
u32 exception_bitmap;
u32 page_fault_error_code_mask;
u32 page_fault_error_code_match;
u32 cr3_target_count;
u32 vm_exit_controls;
u32 vm_exit_msr_store_count;
u32 vm_exit_msr_load_count;
u32 vm_entry_controls;
u32 vm_entry_msr_load_count;
u32 vm_entry_intr_info_field;
u32 vm_entry_exception_error_code;
u32 vm_entry_instruction_len;
u32 tpr_threshold;
u32 secondary_vm_exec_control;
u32 vm_instruction_error;
u32 vm_exit_reason;
u32 vm_exit_intr_info;
u32 vm_exit_intr_error_code;
u32 idt_vectoring_info_field;
u32 idt_vectoring_error_code;
u32 vm_exit_instruction_len;
u32 vmx_instruction_info;
u32 guest_es_limit;
u32 guest_cs_limit;
u32 guest_ss_limit;
u32 guest_ds_limit;
u32 guest_fs_limit;
u32 guest_gs_limit;
u32 guest_ldtr_limit;
u32 guest_tr_limit;
u32 guest_gdtr_limit;
u32 guest_idtr_limit;
u32 guest_es_ar_bytes;
u32 guest_cs_ar_bytes;
u32 guest_ss_ar_bytes;
u32 guest_ds_ar_bytes;
u32 guest_fs_ar_bytes;
u32 guest_gs_ar_bytes;
u32 guest_ldtr_ar_bytes;
u32 guest_tr_ar_bytes;
u32 guest_interruptibility_info;
u32 guest_activity_state;
u32 guest_sysenter_cs;
u32 host_ia32_sysenter_cs;
u32 vmx_preemption_timer_value;
u32 padding32[7]; /* room for future expansion */
u16 virtual_processor_id;
u16 posted_intr_nv;
u16 guest_es_selector;
u16 guest_cs_selector;
u16 guest_ss_selector;
u16 guest_ds_selector;
u16 guest_fs_selector;
u16 guest_gs_selector;
u16 guest_ldtr_selector;
u16 guest_tr_selector;
u16 guest_intr_status;
u16 host_es_selector;
u16 host_cs_selector;
u16 host_ss_selector;
u16 host_ds_selector;
u16 host_fs_selector;
u16 host_gs_selector;
u16 host_tr_selector;
};
/*
* VMCS12_REVISION is an arbitrary id that should be changed if the content or
* layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
* VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
*/
#define VMCS12_REVISION 0x11e57ed0
/*
* VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
* and any VMCS region. Although only sizeof(struct vmcs12) are used by the
* current implementation, 4K are reserved to avoid future complications.
*/
#define VMCS12_SIZE 0x1000
/* Used to remember the last vmcs02 used for some recently used vmcs12s */
struct vmcs02_list {
struct list_head list;
gpa_t vmptr;
struct loaded_vmcs vmcs02;
};
/*
* The nested_vmx structure is part of vcpu_vmx, and holds information we need
* for correct emulation of VMX (i.e., nested VMX) on this vcpu.
*/
struct nested_vmx {
/* Has the level1 guest done vmxon? */
bool vmxon;
gpa_t vmxon_ptr;
/* The guest-physical address of the current VMCS L1 keeps for L2 */
gpa_t current_vmptr;
/* The host-usable pointer to the above */
struct page *current_vmcs12_page;
struct vmcs12 *current_vmcs12;
/*
* Cache of the guest's VMCS, existing outside of guest memory.
* Loaded from guest memory during VMPTRLD. Flushed to guest
* memory during VMXOFF, VMCLEAR, VMPTRLD.
*/
struct vmcs12 *cached_vmcs12;
/*
* Indicates if the shadow vmcs must be updated with the
* data hold by vmcs12
*/
bool sync_shadow_vmcs;
/* vmcs02_list cache of VMCSs recently used to run L2 guests */
struct list_head vmcs02_pool;
int vmcs02_num;
bool change_vmcs01_virtual_x2apic_mode;
/* L2 must run next, and mustn't decide to exit to L1. */
bool nested_run_pending;
/*
* Guest pages referred to in vmcs02 with host-physical pointers, so
* we must keep them pinned while L2 runs.
*/
struct page *apic_access_page;
struct page *virtual_apic_page;
struct page *pi_desc_page;
struct pi_desc *pi_desc;
bool pi_pending;
u16 posted_intr_nv;
unsigned long *msr_bitmap;
struct hrtimer preemption_timer;
bool preemption_timer_expired;
/* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
u64 vmcs01_debugctl;
u16 vpid02;
u16 last_vpid;
/*
* We only store the "true" versions of the VMX capability MSRs. We
* generate the "non-true" versions by setting the must-be-1 bits
* according to the SDM.
*/
u32 nested_vmx_procbased_ctls_low;
u32 nested_vmx_procbased_ctls_high;
u32 nested_vmx_secondary_ctls_low;
u32 nested_vmx_secondary_ctls_high;
u32 nested_vmx_pinbased_ctls_low;
u32 nested_vmx_pinbased_ctls_high;
u32 nested_vmx_exit_ctls_low;
u32 nested_vmx_exit_ctls_high;
u32 nested_vmx_entry_ctls_low;
u32 nested_vmx_entry_ctls_high;
u32 nested_vmx_misc_low;
u32 nested_vmx_misc_high;
u32 nested_vmx_ept_caps;
u32 nested_vmx_vpid_caps;
u64 nested_vmx_basic;
u64 nested_vmx_cr0_fixed0;
u64 nested_vmx_cr0_fixed1;
u64 nested_vmx_cr4_fixed0;
u64 nested_vmx_cr4_fixed1;
u64 nested_vmx_vmcs_enum;
};
#define POSTED_INTR_ON 0
#define POSTED_INTR_SN 1
/* Posted-Interrupt Descriptor */
struct pi_desc {
u32 pir[8]; /* Posted interrupt requested */
union {
struct {
/* bit 256 - Outstanding Notification */
u16 on : 1,
/* bit 257 - Suppress Notification */
sn : 1,
/* bit 271:258 - Reserved */
rsvd_1 : 14;
/* bit 279:272 - Notification Vector */
u8 nv;
/* bit 287:280 - Reserved */
u8 rsvd_2;
/* bit 319:288 - Notification Destination */
u32 ndst;
};
u64 control;
};
u32 rsvd[6];
} __aligned(64);
static bool pi_test_and_set_on(struct pi_desc *pi_desc)
{
return test_and_set_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
{
return test_and_clear_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
{
return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
}
static inline void pi_clear_sn(struct pi_desc *pi_desc)
{
return clear_bit(POSTED_INTR_SN,
(unsigned long *)&pi_desc->control);
}
static inline void pi_set_sn(struct pi_desc *pi_desc)
{
return set_bit(POSTED_INTR_SN,
(unsigned long *)&pi_desc->control);
}
static inline void pi_clear_on(struct pi_desc *pi_desc)
{
clear_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static inline int pi_test_on(struct pi_desc *pi_desc)
{
return test_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static inline int pi_test_sn(struct pi_desc *pi_desc)
{
return test_bit(POSTED_INTR_SN,
(unsigned long *)&pi_desc->control);
}
struct vcpu_vmx {
struct kvm_vcpu vcpu;
unsigned long host_rsp;
u8 fail;
bool nmi_known_unmasked;
u32 exit_intr_info;
u32 idt_vectoring_info;
ulong rflags;
struct shared_msr_entry *guest_msrs;
int nmsrs;
int save_nmsrs;
unsigned long host_idt_base;
#ifdef CONFIG_X86_64
u64 msr_host_kernel_gs_base;
u64 msr_guest_kernel_gs_base;
#endif
u32 vm_entry_controls_shadow;
u32 vm_exit_controls_shadow;
/*
* loaded_vmcs points to the VMCS currently used in this vcpu. For a
* non-nested (L1) guest, it always points to vmcs01. For a nested
* guest (L2), it points to a different VMCS.
*/
struct loaded_vmcs vmcs01;
struct loaded_vmcs *loaded_vmcs;
bool __launched; /* temporary, used in vmx_vcpu_run */
struct msr_autoload {
unsigned nr;
struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
} msr_autoload;
struct {
int loaded;
u16 fs_sel, gs_sel, ldt_sel;
#ifdef CONFIG_X86_64
u16 ds_sel, es_sel;
#endif
int gs_ldt_reload_needed;
int fs_reload_needed;
u64 msr_host_bndcfgs;
unsigned long vmcs_host_cr4; /* May not match real cr4 */
} host_state;
struct {
int vm86_active;
ulong save_rflags;
struct kvm_segment segs[8];
} rmode;
struct {
u32 bitmask; /* 4 bits per segment (1 bit per field) */
struct kvm_save_segment {
u16 selector;
unsigned long base;
u32 limit;
u32 ar;
} seg[8];
} segment_cache;
int vpid;
bool emulation_required;
/* Support for vnmi-less CPUs */
int soft_vnmi_blocked;
ktime_t entry_time;
s64 vnmi_blocked_time;
u32 exit_reason;
/* Posted interrupt descriptor */
struct pi_desc pi_desc;
/* Support for a guest hypervisor (nested VMX) */
struct nested_vmx nested;
/* Dynamic PLE window. */
int ple_window;
bool ple_window_dirty;
/* Support for PML */
#define PML_ENTITY_NUM 512
struct page *pml_pg;
/* apic deadline value in host tsc */
u64 hv_deadline_tsc;
u64 current_tsc_ratio;
bool guest_pkru_valid;
u32 guest_pkru;
u32 host_pkru;
/*
* Only bits masked by msr_ia32_feature_control_valid_bits can be set in
* msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
* in msr_ia32_feature_control_valid_bits.
*/
u64 msr_ia32_feature_control;
u64 msr_ia32_feature_control_valid_bits;
};
enum segment_cache_field {
SEG_FIELD_SEL = 0,
SEG_FIELD_BASE = 1,
SEG_FIELD_LIMIT = 2,
SEG_FIELD_AR = 3,
SEG_FIELD_NR = 4
};
static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
{
return container_of(vcpu, struct vcpu_vmx, vcpu);
}
static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
{
return &(to_vmx(vcpu)->pi_desc);
}
#define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
#define FIELD(number, name) [number] = VMCS12_OFFSET(name)
#define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \
[number##_HIGH] = VMCS12_OFFSET(name)+4
static unsigned long shadow_read_only_fields[] = {
/*
* We do NOT shadow fields that are modified when L0
* traps and emulates any vmx instruction (e.g. VMPTRLD,
* VMXON...) executed by L1.
* For example, VM_INSTRUCTION_ERROR is read
* by L1 if a vmx instruction fails (part of the error path).
* Note the code assumes this logic. If for some reason
* we start shadowing these fields then we need to
* force a shadow sync when L0 emulates vmx instructions
* (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
* by nested_vmx_failValid)
*/
VM_EXIT_REASON,
VM_EXIT_INTR_INFO,
VM_EXIT_INSTRUCTION_LEN,
IDT_VECTORING_INFO_FIELD,
IDT_VECTORING_ERROR_CODE,
VM_EXIT_INTR_ERROR_CODE,
EXIT_QUALIFICATION,
GUEST_LINEAR_ADDRESS,
GUEST_PHYSICAL_ADDRESS
};
static int max_shadow_read_only_fields =
ARRAY_SIZE(shadow_read_only_fields);
static unsigned long shadow_read_write_fields[] = {
TPR_THRESHOLD,
GUEST_RIP,
GUEST_RSP,
GUEST_CR0,
GUEST_CR3,
GUEST_CR4,
GUEST_INTERRUPTIBILITY_INFO,
GUEST_RFLAGS,
GUEST_CS_SELECTOR,
GUEST_CS_AR_BYTES,
GUEST_CS_LIMIT,
GUEST_CS_BASE,
GUEST_ES_BASE,
GUEST_BNDCFGS,
CR0_GUEST_HOST_MASK,
CR0_READ_SHADOW,
CR4_READ_SHADOW,
TSC_OFFSET,
EXCEPTION_BITMAP,
CPU_BASED_VM_EXEC_CONTROL,
VM_ENTRY_EXCEPTION_ERROR_CODE,
VM_ENTRY_INTR_INFO_FIELD,
VM_ENTRY_INSTRUCTION_LEN,
VM_ENTRY_EXCEPTION_ERROR_CODE,
HOST_FS_BASE,
HOST_GS_BASE,
HOST_FS_SELECTOR,
HOST_GS_SELECTOR
};
static int max_shadow_read_write_fields =
ARRAY_SIZE(shadow_read_write_fields);
static const unsigned short vmcs_field_to_offset_table[] = {
FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
FIELD(POSTED_INTR_NV, posted_intr_nv),
FIELD(GUEST_ES_SELECTOR, guest_es_selector),
FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
FIELD(GUEST_INTR_STATUS, guest_intr_status),
FIELD(HOST_ES_SELECTOR, host_es_selector),
FIELD(HOST_CS_SELECTOR, host_cs_selector),
FIELD(HOST_SS_SELECTOR, host_ss_selector),
FIELD(HOST_DS_SELECTOR, host_ds_selector),
FIELD(HOST_FS_SELECTOR, host_fs_selector),
FIELD(HOST_GS_SELECTOR, host_gs_selector),
FIELD(HOST_TR_SELECTOR, host_tr_selector),
FIELD64(IO_BITMAP_A, io_bitmap_a),
FIELD64(IO_BITMAP_B, io_bitmap_b),
FIELD64(MSR_BITMAP, msr_bitmap),
FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
FIELD64(TSC_OFFSET, tsc_offset),
FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
FIELD64(EPT_POINTER, ept_pointer),
FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
FIELD64(GUEST_PDPTR0, guest_pdptr0),
FIELD64(GUEST_PDPTR1, guest_pdptr1),
FIELD64(GUEST_PDPTR2, guest_pdptr2),
FIELD64(GUEST_PDPTR3, guest_pdptr3),
FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
FIELD64(HOST_IA32_PAT, host_ia32_pat),
FIELD64(HOST_IA32_EFER, host_ia32_efer),
FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
FIELD(EXCEPTION_BITMAP, exception_bitmap),
FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
FIELD(CR3_TARGET_COUNT, cr3_target_count),
FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
FIELD(TPR_THRESHOLD, tpr_threshold),
FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
FIELD(VM_EXIT_REASON, vm_exit_reason),
FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
FIELD(GUEST_ES_LIMIT, guest_es_limit),
FIELD(GUEST_CS_LIMIT, guest_cs_limit),
FIELD(GUEST_SS_LIMIT, guest_ss_limit),
FIELD(GUEST_DS_LIMIT, guest_ds_limit),
FIELD(GUEST_FS_LIMIT, guest_fs_limit),
FIELD(GUEST_GS_LIMIT, guest_gs_limit),
FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
FIELD(GUEST_TR_LIMIT, guest_tr_limit),
FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
FIELD(CR0_READ_SHADOW, cr0_read_shadow),
FIELD(CR4_READ_SHADOW, cr4_read_shadow),
FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
FIELD(EXIT_QUALIFICATION, exit_qualification),
FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
FIELD(GUEST_CR0, guest_cr0),
FIELD(GUEST_CR3, guest_cr3),
FIELD(GUEST_CR4, guest_cr4),
FIELD(GUEST_ES_BASE, guest_es_base),
FIELD(GUEST_CS_BASE, guest_cs_base),
FIELD(GUEST_SS_BASE, guest_ss_base),
FIELD(GUEST_DS_BASE, guest_ds_base),
FIELD(GUEST_FS_BASE, guest_fs_base),
FIELD(GUEST_GS_BASE, guest_gs_base),
FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
FIELD(GUEST_TR_BASE, guest_tr_base),
FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
FIELD(GUEST_IDTR_BASE, guest_idtr_base),
FIELD(GUEST_DR7, guest_dr7),
FIELD(GUEST_RSP, guest_rsp),
FIELD(GUEST_RIP, guest_rip),
FIELD(GUEST_RFLAGS, guest_rflags),
FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
FIELD(HOST_CR0, host_cr0),
FIELD(HOST_CR3, host_cr3),
FIELD(HOST_CR4, host_cr4),
FIELD(HOST_FS_BASE, host_fs_base),
FIELD(HOST_GS_BASE, host_gs_base),
FIELD(HOST_TR_BASE, host_tr_base),
FIELD(HOST_GDTR_BASE, host_gdtr_base),
FIELD(HOST_IDTR_BASE, host_idtr_base),
FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
FIELD(HOST_RSP, host_rsp),
FIELD(HOST_RIP, host_rip),
};
static inline short vmcs_field_to_offset(unsigned long field)
{
BUILD_BUG_ON(ARRAY_SIZE(vmcs_field_to_offset_table) > SHRT_MAX);
if (field >= ARRAY_SIZE(vmcs_field_to_offset_table) ||
vmcs_field_to_offset_table[field] == 0)
return -ENOENT;
return vmcs_field_to_offset_table[field];
}
static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
{
return to_vmx(vcpu)->nested.cached_vmcs12;
}
static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
{
struct page *page = kvm_vcpu_gfn_to_page(vcpu, addr >> PAGE_SHIFT);
if (is_error_page(page))
return NULL;
return page;
}
static void nested_release_page(struct page *page)
{
kvm_release_page_dirty(page);
}
static void nested_release_page_clean(struct page *page)
{
kvm_release_page_clean(page);
}
static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
static u64 construct_eptp(unsigned long root_hpa);
static void kvm_cpu_vmxon(u64 addr);
static void kvm_cpu_vmxoff(void);
static bool vmx_xsaves_supported(void);
static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
static void vmx_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg);
static void vmx_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg);
static bool guest_state_valid(struct kvm_vcpu *vcpu);
static u32 vmx_segment_access_rights(struct kvm_segment *var);
static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
static int alloc_identity_pagetable(struct kvm *kvm);
static DEFINE_PER_CPU(struct vmcs *, vmxarea);
static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
/*
* We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
* when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
*/
static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
/*
* We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
* can find which vCPU should be waken up.
*/
static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
enum {
VMX_IO_BITMAP_A,
VMX_IO_BITMAP_B,
VMX_MSR_BITMAP_LEGACY,
VMX_MSR_BITMAP_LONGMODE,
VMX_MSR_BITMAP_LEGACY_X2APIC_APICV,
VMX_MSR_BITMAP_LONGMODE_X2APIC_APICV,
VMX_MSR_BITMAP_LEGACY_X2APIC,
VMX_MSR_BITMAP_LONGMODE_X2APIC,
VMX_VMREAD_BITMAP,
VMX_VMWRITE_BITMAP,
VMX_BITMAP_NR
};
static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
#define vmx_io_bitmap_a (vmx_bitmap[VMX_IO_BITMAP_A])
#define vmx_io_bitmap_b (vmx_bitmap[VMX_IO_BITMAP_B])
#define vmx_msr_bitmap_legacy (vmx_bitmap[VMX_MSR_BITMAP_LEGACY])
#define vmx_msr_bitmap_longmode (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE])
#define vmx_msr_bitmap_legacy_x2apic_apicv (vmx_bitmap[VMX_MSR_BITMAP_LEGACY_X2APIC_APICV])
#define vmx_msr_bitmap_longmode_x2apic_apicv (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE_X2APIC_APICV])
#define vmx_msr_bitmap_legacy_x2apic (vmx_bitmap[VMX_MSR_BITMAP_LEGACY_X2APIC])
#define vmx_msr_bitmap_longmode_x2apic (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE_X2APIC])
#define vmx_vmread_bitmap (vmx_bitmap[VMX_VMREAD_BITMAP])
#define vmx_vmwrite_bitmap (vmx_bitmap[VMX_VMWRITE_BITMAP])
static bool cpu_has_load_ia32_efer;
static bool cpu_has_load_perf_global_ctrl;
static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
static DEFINE_SPINLOCK(vmx_vpid_lock);
static struct vmcs_config {
int size;
int order;
u32 basic_cap;
u32 revision_id;
u32 pin_based_exec_ctrl;
u32 cpu_based_exec_ctrl;
u32 cpu_based_2nd_exec_ctrl;
u32 vmexit_ctrl;
u32 vmentry_ctrl;
} vmcs_config;
static struct vmx_capability {
u32 ept;
u32 vpid;
} vmx_capability;
#define VMX_SEGMENT_FIELD(seg) \
[VCPU_SREG_##seg] = { \
.selector = GUEST_##seg##_SELECTOR, \
.base = GUEST_##seg##_BASE, \
.limit = GUEST_##seg##_LIMIT, \
.ar_bytes = GUEST_##seg##_AR_BYTES, \
}
static const struct kvm_vmx_segment_field {
unsigned selector;
unsigned base;
unsigned limit;
unsigned ar_bytes;
} kvm_vmx_segment_fields[] = {
VMX_SEGMENT_FIELD(CS),
VMX_SEGMENT_FIELD(DS),
VMX_SEGMENT_FIELD(ES),
VMX_SEGMENT_FIELD(FS),
VMX_SEGMENT_FIELD(GS),
VMX_SEGMENT_FIELD(SS),
VMX_SEGMENT_FIELD(TR),
VMX_SEGMENT_FIELD(LDTR),
};
static u64 host_efer;
static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
/*
* Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
* away by decrementing the array size.
*/
static const u32 vmx_msr_index[] = {
#ifdef CONFIG_X86_64
MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
#endif
MSR_EFER, MSR_TSC_AUX, MSR_STAR,
};
static inline bool is_exception_n(u32 intr_info, u8 vector)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
INTR_INFO_VALID_MASK)) ==
(INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
}
static inline bool is_debug(u32 intr_info)
{
return is_exception_n(intr_info, DB_VECTOR);
}
static inline bool is_breakpoint(u32 intr_info)
{
return is_exception_n(intr_info, BP_VECTOR);
}
static inline bool is_page_fault(u32 intr_info)
{
return is_exception_n(intr_info, PF_VECTOR);
}
static inline bool is_no_device(u32 intr_info)
{
return is_exception_n(intr_info, NM_VECTOR);
}
static inline bool is_invalid_opcode(u32 intr_info)
{
return is_exception_n(intr_info, UD_VECTOR);
}
static inline bool is_external_interrupt(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
== (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
}
static inline bool is_machine_check(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
INTR_INFO_VALID_MASK)) ==
(INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
}
static inline bool cpu_has_vmx_msr_bitmap(void)
{
return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
}
static inline bool cpu_has_vmx_tpr_shadow(void)
{
return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
}
static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
{
return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
}
static inline bool cpu_has_secondary_exec_ctrls(void)
{
return vmcs_config.cpu_based_exec_ctrl &
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
}
static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
}
static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
}
static inline bool cpu_has_vmx_apic_register_virt(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_APIC_REGISTER_VIRT;
}
static inline bool cpu_has_vmx_virtual_intr_delivery(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
}
/*
* Comment's format: document - errata name - stepping - processor name.
* Refer from
* https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
*/
static u32 vmx_preemption_cpu_tfms[] = {
/* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
0x000206E6,
/* 323056.pdf - AAX65 - C2 - Xeon L3406 */
/* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
/* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
0x00020652,
/* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
0x00020655,
/* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
/* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
/*
* 320767.pdf - AAP86 - B1 -
* i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
*/
0x000106E5,
/* 321333.pdf - AAM126 - C0 - Xeon 3500 */
0x000106A0,
/* 321333.pdf - AAM126 - C1 - Xeon 3500 */
0x000106A1,
/* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
0x000106A4,
/* 321333.pdf - AAM126 - D0 - Xeon 3500 */
/* 321324.pdf - AAK139 - D0 - Xeon 5500 */
/* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
0x000106A5,
};
static inline bool cpu_has_broken_vmx_preemption_timer(void)
{
u32 eax = cpuid_eax(0x00000001), i;
/* Clear the reserved bits */
eax &= ~(0x3U << 14 | 0xfU << 28);
for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
if (eax == vmx_preemption_cpu_tfms[i])
return true;
return false;
}
static inline bool cpu_has_vmx_preemption_timer(void)
{
return vmcs_config.pin_based_exec_ctrl &
PIN_BASED_VMX_PREEMPTION_TIMER;
}
static inline bool cpu_has_vmx_posted_intr(void)
{
return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
}
static inline bool cpu_has_vmx_apicv(void)
{
return cpu_has_vmx_apic_register_virt() &&
cpu_has_vmx_virtual_intr_delivery() &&
cpu_has_vmx_posted_intr();
}
static inline bool cpu_has_vmx_flexpriority(void)
{
return cpu_has_vmx_tpr_shadow() &&
cpu_has_vmx_virtualize_apic_accesses();
}
static inline bool cpu_has_vmx_ept_execute_only(void)
{
return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
}
static inline bool cpu_has_vmx_ept_2m_page(void)
{
return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
}
static inline bool cpu_has_vmx_ept_1g_page(void)
{
return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
}
static inline bool cpu_has_vmx_ept_4levels(void)
{
return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
}
static inline bool cpu_has_vmx_ept_ad_bits(void)
{
return vmx_capability.ept & VMX_EPT_AD_BIT;
}
static inline bool cpu_has_vmx_invept_context(void)
{
return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
}
static inline bool cpu_has_vmx_invept_global(void)
{
return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
}
static inline bool cpu_has_vmx_invvpid_single(void)
{
return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
}
static inline bool cpu_has_vmx_invvpid_global(void)
{
return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
}
static inline bool cpu_has_vmx_ept(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_ENABLE_EPT;
}
static inline bool cpu_has_vmx_unrestricted_guest(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_UNRESTRICTED_GUEST;
}
static inline bool cpu_has_vmx_ple(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_PAUSE_LOOP_EXITING;
}
static inline bool cpu_has_vmx_basic_inout(void)
{
return (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
}
static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
{
return flexpriority_enabled && lapic_in_kernel(vcpu);
}
static inline bool cpu_has_vmx_vpid(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_ENABLE_VPID;
}
static inline bool cpu_has_vmx_rdtscp(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_RDTSCP;
}
static inline bool cpu_has_vmx_invpcid(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_ENABLE_INVPCID;
}
static inline bool cpu_has_virtual_nmis(void)
{
return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
}
static inline bool cpu_has_vmx_wbinvd_exit(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_WBINVD_EXITING;
}
static inline bool cpu_has_vmx_shadow_vmcs(void)
{
u64 vmx_msr;
rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
/* check if the cpu supports writing r/o exit information fields */
if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
return false;
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_SHADOW_VMCS;
}
static inline bool cpu_has_vmx_pml(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
}
static inline bool cpu_has_vmx_tsc_scaling(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_TSC_SCALING;
}
static inline bool report_flexpriority(void)
{
return flexpriority_enabled;
}
static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
{
return vmcs12->cpu_based_vm_exec_control & bit;
}
static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
{
return (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
(vmcs12->secondary_vm_exec_control & bit);
}
static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
{
return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
}
static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
{
return vmcs12->pin_based_vm_exec_control &
PIN_BASED_VMX_PREEMPTION_TIMER;
}
static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
}
static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES) &&
vmx_xsaves_supported();
}
static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
}
static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
}
static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
}
static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
}
static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
{
return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
}
static inline bool is_nmi(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
== (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
}
static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
u32 exit_intr_info,
unsigned long exit_qualification);
static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12,
u32 reason, unsigned long qualification);
static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
{
int i;
for (i = 0; i < vmx->nmsrs; ++i)
if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
return i;
return -1;
}
static inline void __invvpid(int ext, u16 vpid, gva_t gva)
{
struct {
u64 vpid : 16;
u64 rsvd : 48;
u64 gva;
} operand = { vpid, 0, gva };
asm volatile (__ex(ASM_VMX_INVVPID)
/* CF==1 or ZF==1 --> rc = -1 */
"; ja 1f ; ud2 ; 1:"
: : "a"(&operand), "c"(ext) : "cc", "memory");
}
static inline void __invept(int ext, u64 eptp, gpa_t gpa)
{
struct {
u64 eptp, gpa;
} operand = {eptp, gpa};
asm volatile (__ex(ASM_VMX_INVEPT)
/* CF==1 or ZF==1 --> rc = -1 */
"; ja 1f ; ud2 ; 1:\n"
: : "a" (&operand), "c" (ext) : "cc", "memory");
}
static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
{
int i;
i = __find_msr_index(vmx, msr);
if (i >= 0)
return &vmx->guest_msrs[i];
return NULL;
}
static void vmcs_clear(struct vmcs *vmcs)
{
u64 phys_addr = __pa(vmcs);
u8 error;
asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
: "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
: "cc", "memory");
if (error)
printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
vmcs, phys_addr);
}
static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
{
vmcs_clear(loaded_vmcs->vmcs);
if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
vmcs_clear(loaded_vmcs->shadow_vmcs);
loaded_vmcs->cpu = -1;
loaded_vmcs->launched = 0;
}
static void vmcs_load(struct vmcs *vmcs)
{
u64 phys_addr = __pa(vmcs);
u8 error;
asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
: "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
: "cc", "memory");
if (error)
printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
vmcs, phys_addr);
}
#ifdef CONFIG_KEXEC_CORE
/*
* This bitmap is used to indicate whether the vmclear
* operation is enabled on all cpus. All disabled by
* default.
*/
static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
static inline void crash_enable_local_vmclear(int cpu)
{
cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
}
static inline void crash_disable_local_vmclear(int cpu)
{
cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
}
static inline int crash_local_vmclear_enabled(int cpu)
{
return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
}
static void crash_vmclear_local_loaded_vmcss(void)
{
int cpu = raw_smp_processor_id();
struct loaded_vmcs *v;
if (!crash_local_vmclear_enabled(cpu))
return;
list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
loaded_vmcss_on_cpu_link)
vmcs_clear(v->vmcs);
}
#else
static inline void crash_enable_local_vmclear(int cpu) { }
static inline void crash_disable_local_vmclear(int cpu) { }
#endif /* CONFIG_KEXEC_CORE */
static void __loaded_vmcs_clear(void *arg)
{
struct loaded_vmcs *loaded_vmcs = arg;
int cpu = raw_smp_processor_id();
if (loaded_vmcs->cpu != cpu)
return; /* vcpu migration can race with cpu offline */
if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
per_cpu(current_vmcs, cpu) = NULL;
crash_disable_local_vmclear(cpu);
list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
/*
* we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
* is before setting loaded_vmcs->vcpu to -1 which is done in
* loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
* then adds the vmcs into percpu list before it is deleted.
*/
smp_wmb();
loaded_vmcs_init(loaded_vmcs);
crash_enable_local_vmclear(cpu);
}
static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
{
int cpu = loaded_vmcs->cpu;
if (cpu != -1)
smp_call_function_single(cpu,
__loaded_vmcs_clear, loaded_vmcs, 1);
}
static inline void vpid_sync_vcpu_single(int vpid)
{
if (vpid == 0)
return;
if (cpu_has_vmx_invvpid_single())
__invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
}
static inline void vpid_sync_vcpu_global(void)
{
if (cpu_has_vmx_invvpid_global())
__invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
}
static inline void vpid_sync_context(int vpid)
{
if (cpu_has_vmx_invvpid_single())
vpid_sync_vcpu_single(vpid);
else
vpid_sync_vcpu_global();
}
static inline void ept_sync_global(void)
{
if (cpu_has_vmx_invept_global())
__invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
}
static inline void ept_sync_context(u64 eptp)
{
if (enable_ept) {
if (cpu_has_vmx_invept_context())
__invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
else
ept_sync_global();
}
}
static __always_inline void vmcs_check16(unsigned long field)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
"16-bit accessor invalid for 64-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
"16-bit accessor invalid for 64-bit high field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
"16-bit accessor invalid for 32-bit high field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
"16-bit accessor invalid for natural width field");
}
static __always_inline void vmcs_check32(unsigned long field)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
"32-bit accessor invalid for 16-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
"32-bit accessor invalid for natural width field");
}
static __always_inline void vmcs_check64(unsigned long field)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
"64-bit accessor invalid for 16-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
"64-bit accessor invalid for 64-bit high field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
"64-bit accessor invalid for 32-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
"64-bit accessor invalid for natural width field");
}
static __always_inline void vmcs_checkl(unsigned long field)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
"Natural width accessor invalid for 16-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
"Natural width accessor invalid for 64-bit field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
"Natural width accessor invalid for 64-bit high field");
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
"Natural width accessor invalid for 32-bit field");
}
static __always_inline unsigned long __vmcs_readl(unsigned long field)
{
unsigned long value;
asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
: "=a"(value) : "d"(field) : "cc");
return value;
}
static __always_inline u16 vmcs_read16(unsigned long field)
{
vmcs_check16(field);
return __vmcs_readl(field);
}
static __always_inline u32 vmcs_read32(unsigned long field)
{
vmcs_check32(field);
return __vmcs_readl(field);
}
static __always_inline u64 vmcs_read64(unsigned long field)
{
vmcs_check64(field);
#ifdef CONFIG_X86_64
return __vmcs_readl(field);
#else
return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
#endif
}
static __always_inline unsigned long vmcs_readl(unsigned long field)
{
vmcs_checkl(field);
return __vmcs_readl(field);
}
static noinline void vmwrite_error(unsigned long field, unsigned long value)
{
printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
dump_stack();
}
static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
{
u8 error;
asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
: "=q"(error) : "a"(value), "d"(field) : "cc");
if (unlikely(error))
vmwrite_error(field, value);
}
static __always_inline void vmcs_write16(unsigned long field, u16 value)
{
vmcs_check16(field);
__vmcs_writel(field, value);
}
static __always_inline void vmcs_write32(unsigned long field, u32 value)
{
vmcs_check32(field);
__vmcs_writel(field, value);
}
static __always_inline void vmcs_write64(unsigned long field, u64 value)
{
vmcs_check64(field);
__vmcs_writel(field, value);
#ifndef CONFIG_X86_64
asm volatile ("");
__vmcs_writel(field+1, value >> 32);
#endif
}
static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
{
vmcs_checkl(field);
__vmcs_writel(field, value);
}
static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
"vmcs_clear_bits does not support 64-bit fields");
__vmcs_writel(field, __vmcs_readl(field) & ~mask);
}
static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
{
BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
"vmcs_set_bits does not support 64-bit fields");
__vmcs_writel(field, __vmcs_readl(field) | mask);
}
static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
{
vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
}
static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
{
vmcs_write32(VM_ENTRY_CONTROLS, val);
vmx->vm_entry_controls_shadow = val;
}
static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
{
if (vmx->vm_entry_controls_shadow != val)
vm_entry_controls_init(vmx, val);
}
static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
{
return vmx->vm_entry_controls_shadow;
}
static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
{
vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
}
static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
{
vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
}
static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
{
vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
}
static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
{
vmcs_write32(VM_EXIT_CONTROLS, val);
vmx->vm_exit_controls_shadow = val;
}
static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
{
if (vmx->vm_exit_controls_shadow != val)
vm_exit_controls_init(vmx, val);
}
static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
{
return vmx->vm_exit_controls_shadow;
}
static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
{
vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
}
static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
{
vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
}
static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
{
vmx->segment_cache.bitmask = 0;
}
static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
unsigned field)
{
bool ret;
u32 mask = 1 << (seg * SEG_FIELD_NR + field);
if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
vmx->segment_cache.bitmask = 0;
}
ret = vmx->segment_cache.bitmask & mask;
vmx->segment_cache.bitmask |= mask;
return ret;
}
static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
{
u16 *p = &vmx->segment_cache.seg[seg].selector;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
*p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
return *p;
}
static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
{
ulong *p = &vmx->segment_cache.seg[seg].base;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
*p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
return *p;
}
static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
{
u32 *p = &vmx->segment_cache.seg[seg].limit;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
*p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
return *p;
}
static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
{
u32 *p = &vmx->segment_cache.seg[seg].ar;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
*p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
return *p;
}
static void update_exception_bitmap(struct kvm_vcpu *vcpu)
{
u32 eb;
eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
(1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR);
if ((vcpu->guest_debug &
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
eb |= 1u << BP_VECTOR;
if (to_vmx(vcpu)->rmode.vm86_active)
eb = ~0;
if (enable_ept)
eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
if (vcpu->fpu_active)
eb &= ~(1u << NM_VECTOR);
/* When we are running a nested L2 guest and L1 specified for it a
* certain exception bitmap, we must trap the same exceptions and pass
* them to L1. When running L2, we will only handle the exceptions
* specified above if L1 did not want them.
*/
if (is_guest_mode(vcpu))
eb |= get_vmcs12(vcpu)->exception_bitmap;
vmcs_write32(EXCEPTION_BITMAP, eb);
}
static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
unsigned long entry, unsigned long exit)
{
vm_entry_controls_clearbit(vmx, entry);
vm_exit_controls_clearbit(vmx, exit);
}
static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
{
unsigned i;
struct msr_autoload *m = &vmx->msr_autoload;
switch (msr) {
case MSR_EFER:
if (cpu_has_load_ia32_efer) {
clear_atomic_switch_msr_special(vmx,
VM_ENTRY_LOAD_IA32_EFER,
VM_EXIT_LOAD_IA32_EFER);
return;
}
break;
case MSR_CORE_PERF_GLOBAL_CTRL:
if (cpu_has_load_perf_global_ctrl) {
clear_atomic_switch_msr_special(vmx,
VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
return;
}
break;
}
for (i = 0; i < m->nr; ++i)
if (m->guest[i].index == msr)
break;
if (i == m->nr)
return;
--m->nr;
m->guest[i] = m->guest[m->nr];
m->host[i] = m->host[m->nr];
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
}
static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
unsigned long entry, unsigned long exit,
unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
u64 guest_val, u64 host_val)
{
vmcs_write64(guest_val_vmcs, guest_val);
vmcs_write64(host_val_vmcs, host_val);
vm_entry_controls_setbit(vmx, entry);
vm_exit_controls_setbit(vmx, exit);
}
static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
u64 guest_val, u64 host_val)
{
unsigned i;
struct msr_autoload *m = &vmx->msr_autoload;
switch (msr) {
case MSR_EFER:
if (cpu_has_load_ia32_efer) {
add_atomic_switch_msr_special(vmx,
VM_ENTRY_LOAD_IA32_EFER,
VM_EXIT_LOAD_IA32_EFER,
GUEST_IA32_EFER,
HOST_IA32_EFER,
guest_val, host_val);
return;
}
break;
case MSR_CORE_PERF_GLOBAL_CTRL:
if (cpu_has_load_perf_global_ctrl) {
add_atomic_switch_msr_special(vmx,
VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
GUEST_IA32_PERF_GLOBAL_CTRL,
HOST_IA32_PERF_GLOBAL_CTRL,
guest_val, host_val);
return;
}
break;
case MSR_IA32_PEBS_ENABLE:
/* PEBS needs a quiescent period after being disabled (to write
* a record). Disabling PEBS through VMX MSR swapping doesn't
* provide that period, so a CPU could write host's record into
* guest's memory.
*/
wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
}
for (i = 0; i < m->nr; ++i)
if (m->guest[i].index == msr)
break;
if (i == NR_AUTOLOAD_MSRS) {
printk_once(KERN_WARNING "Not enough msr switch entries. "
"Can't add msr %x\n", msr);
return;
} else if (i == m->nr) {
++m->nr;
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
}
m->guest[i].index = msr;
m->guest[i].value = guest_val;
m->host[i].index = msr;
m->host[i].value = host_val;
}
static void reload_tss(void)
{
/*
* VT restores TR but not its size. Useless.
*/
struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
struct desc_struct *descs;
descs = (void *)gdt->address;
descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
load_TR_desc();
}
static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
{
u64 guest_efer = vmx->vcpu.arch.efer;
u64 ignore_bits = 0;
if (!enable_ept) {
/*
* NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
* host CPUID is more efficient than testing guest CPUID
* or CR4. Host SMEP is anyway a requirement for guest SMEP.
*/
if (boot_cpu_has(X86_FEATURE_SMEP))
guest_efer |= EFER_NX;
else if (!(guest_efer & EFER_NX))
ignore_bits |= EFER_NX;
}
/*
* LMA and LME handled by hardware; SCE meaningless outside long mode.
*/
ignore_bits |= EFER_SCE;
#ifdef CONFIG_X86_64
ignore_bits |= EFER_LMA | EFER_LME;
/* SCE is meaningful only in long mode on Intel */
if (guest_efer & EFER_LMA)
ignore_bits &= ~(u64)EFER_SCE;
#endif
clear_atomic_switch_msr(vmx, MSR_EFER);
/*
* On EPT, we can't emulate NX, so we must switch EFER atomically.
* On CPUs that support "load IA32_EFER", always switch EFER
* atomically, since it's faster than switching it manually.
*/
if (cpu_has_load_ia32_efer ||
(enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
if (!(guest_efer & EFER_LMA))
guest_efer &= ~EFER_LME;
if (guest_efer != host_efer)
add_atomic_switch_msr(vmx, MSR_EFER,
guest_efer, host_efer);
return false;
} else {
guest_efer &= ~ignore_bits;
guest_efer |= host_efer & ignore_bits;
vmx->guest_msrs[efer_offset].data = guest_efer;
vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
return true;
}
}
static unsigned long segment_base(u16 selector)
{
struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
struct desc_struct *d;
unsigned long table_base;
unsigned long v;
if (!(selector & ~3))
return 0;
table_base = gdt->address;
if (selector & 4) { /* from ldt */
u16 ldt_selector = kvm_read_ldt();
if (!(ldt_selector & ~3))
return 0;
table_base = segment_base(ldt_selector);
}
d = (struct desc_struct *)(table_base + (selector & ~7));
v = get_desc_base(d);
#ifdef CONFIG_X86_64
if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
#endif
return v;
}
static inline unsigned long kvm_read_tr_base(void)
{
u16 tr;
asm("str %0" : "=g"(tr));
return segment_base(tr);
}
static void vmx_save_host_state(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int i;
if (vmx->host_state.loaded)
return;
vmx->host_state.loaded = 1;
/*
* Set host fs and gs selectors. Unfortunately, 22.2.3 does not
* allow segment selectors with cpl > 0 or ti == 1.
*/
vmx->host_state.ldt_sel = kvm_read_ldt();
vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
savesegment(fs, vmx->host_state.fs_sel);
if (!(vmx->host_state.fs_sel & 7)) {
vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
vmx->host_state.fs_reload_needed = 0;
} else {
vmcs_write16(HOST_FS_SELECTOR, 0);
vmx->host_state.fs_reload_needed = 1;
}
savesegment(gs, vmx->host_state.gs_sel);
if (!(vmx->host_state.gs_sel & 7))
vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
else {
vmcs_write16(HOST_GS_SELECTOR, 0);
vmx->host_state.gs_ldt_reload_needed = 1;
}
#ifdef CONFIG_X86_64
savesegment(ds, vmx->host_state.ds_sel);
savesegment(es, vmx->host_state.es_sel);
#endif
#ifdef CONFIG_X86_64
vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
#else
vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
#endif
#ifdef CONFIG_X86_64
rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
if (is_long_mode(&vmx->vcpu))
wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
#endif
if (boot_cpu_has(X86_FEATURE_MPX))
rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
for (i = 0; i < vmx->save_nmsrs; ++i)
kvm_set_shared_msr(vmx->guest_msrs[i].index,
vmx->guest_msrs[i].data,
vmx->guest_msrs[i].mask);
}
static void __vmx_load_host_state(struct vcpu_vmx *vmx)
{
if (!vmx->host_state.loaded)
return;
++vmx->vcpu.stat.host_state_reload;
vmx->host_state.loaded = 0;
#ifdef CONFIG_X86_64
if (is_long_mode(&vmx->vcpu))
rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
#endif
if (vmx->host_state.gs_ldt_reload_needed) {
kvm_load_ldt(vmx->host_state.ldt_sel);
#ifdef CONFIG_X86_64
load_gs_index(vmx->host_state.gs_sel);
#else
loadsegment(gs, vmx->host_state.gs_sel);
#endif
}
if (vmx->host_state.fs_reload_needed)
loadsegment(fs, vmx->host_state.fs_sel);
#ifdef CONFIG_X86_64
if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
loadsegment(ds, vmx->host_state.ds_sel);
loadsegment(es, vmx->host_state.es_sel);
}
#endif
reload_tss();
#ifdef CONFIG_X86_64
wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
#endif
if (vmx->host_state.msr_host_bndcfgs)
wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
load_gdt(this_cpu_ptr(&host_gdt));
}
static void vmx_load_host_state(struct vcpu_vmx *vmx)
{
preempt_disable();
__vmx_load_host_state(vmx);
preempt_enable();
}
static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
{
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
struct pi_desc old, new;
unsigned int dest;
if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(vcpu))
return;
do {
old.control = new.control = pi_desc->control;
/*
* If 'nv' field is POSTED_INTR_WAKEUP_VECTOR, there
* are two possible cases:
* 1. After running 'pre_block', context switch
* happened. For this case, 'sn' was set in
* vmx_vcpu_put(), so we need to clear it here.
* 2. After running 'pre_block', we were blocked,
* and woken up by some other guy. For this case,
* we don't need to do anything, 'pi_post_block'
* will do everything for us. However, we cannot
* check whether it is case #1 or case #2 here
* (maybe, not needed), so we also clear sn here,
* I think it is not a big deal.
*/
if (pi_desc->nv != POSTED_INTR_WAKEUP_VECTOR) {
if (vcpu->cpu != cpu) {
dest = cpu_physical_id(cpu);
if (x2apic_enabled())
new.ndst = dest;
else
new.ndst = (dest << 8) & 0xFF00;
}
/* set 'NV' to 'notification vector' */
new.nv = POSTED_INTR_VECTOR;
}
/* Allow posting non-urgent interrupts */
new.sn = 0;
} while (cmpxchg(&pi_desc->control, old.control,
new.control) != old.control);
}
static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
{
vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
}
/*
* Switches to specified vcpu, until a matching vcpu_put(), but assumes
* vcpu mutex is already taken.
*/
static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
if (!vmm_exclusive)
kvm_cpu_vmxon(phys_addr);
else if (!already_loaded)
loaded_vmcs_clear(vmx->loaded_vmcs);
if (!already_loaded) {
local_irq_disable();
crash_disable_local_vmclear(cpu);
/*
* Read loaded_vmcs->cpu should be before fetching
* loaded_vmcs->loaded_vmcss_on_cpu_link.
* See the comments in __loaded_vmcs_clear().
*/
smp_rmb();
list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
&per_cpu(loaded_vmcss_on_cpu, cpu));
crash_enable_local_vmclear(cpu);
local_irq_enable();
}
if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
vmcs_load(vmx->loaded_vmcs->vmcs);
}
if (!already_loaded) {
struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
unsigned long sysenter_esp;
kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
/*
* Linux uses per-cpu TSS and GDT, so set these when switching
* processors.
*/
vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
vmcs_writel(HOST_GDTR_BASE, gdt->address); /* 22.2.4 */
rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
vmx->loaded_vmcs->cpu = cpu;
}
/* Setup TSC multiplier */
if (kvm_has_tsc_control &&
vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
decache_tsc_multiplier(vmx);
vmx_vcpu_pi_load(vcpu, cpu);
vmx->host_pkru = read_pkru();
}
static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
{
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(vcpu))
return;
/* Set SN when the vCPU is preempted */
if (vcpu->preempted)
pi_set_sn(pi_desc);
}
static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
{
vmx_vcpu_pi_put(vcpu);
__vmx_load_host_state(to_vmx(vcpu));
if (!vmm_exclusive) {
__loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
vcpu->cpu = -1;
kvm_cpu_vmxoff();
}
}
static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
{
ulong cr0;
if (vcpu->fpu_active)
return;
vcpu->fpu_active = 1;
cr0 = vmcs_readl(GUEST_CR0);
cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
vmcs_writel(GUEST_CR0, cr0);
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
if (is_guest_mode(vcpu))
vcpu->arch.cr0_guest_owned_bits &=
~get_vmcs12(vcpu)->cr0_guest_host_mask;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
}
static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
/*
* Return the cr0 value that a nested guest would read. This is a combination
* of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
* its hypervisor (cr0_read_shadow).
*/
static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
{
return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
(fields->cr0_read_shadow & fields->cr0_guest_host_mask);
}
static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
{
return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
(fields->cr4_read_shadow & fields->cr4_guest_host_mask);
}
static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
{
/* Note that there is no vcpu->fpu_active = 0 here. The caller must
* set this *before* calling this function.
*/
vmx_decache_cr0_guest_bits(vcpu);
vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits = 0;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
if (is_guest_mode(vcpu)) {
/*
* L1's specified read shadow might not contain the TS bit,
* so now that we turned on shadowing of this bit, we need to
* set this bit of the shadow. Like in nested_vmx_run we need
* nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
* up-to-date here because we just decached cr0.TS (and we'll
* only update vmcs12->guest_cr0 on nested exit).
*/
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
(vcpu->arch.cr0 & X86_CR0_TS);
vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
} else
vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
}
static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
{
unsigned long rflags, save_rflags;
if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
rflags = vmcs_readl(GUEST_RFLAGS);
if (to_vmx(vcpu)->rmode.vm86_active) {
rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
save_rflags = to_vmx(vcpu)->rmode.save_rflags;
rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
}
to_vmx(vcpu)->rflags = rflags;
}
return to_vmx(vcpu)->rflags;
}
static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
{
__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
to_vmx(vcpu)->rflags = rflags;
if (to_vmx(vcpu)->rmode.vm86_active) {
to_vmx(vcpu)->rmode.save_rflags = rflags;
rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
}
vmcs_writel(GUEST_RFLAGS, rflags);
}
static u32 vmx_get_pkru(struct kvm_vcpu *vcpu)
{
return to_vmx(vcpu)->guest_pkru;
}
static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
{
u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
int ret = 0;
if (interruptibility & GUEST_INTR_STATE_STI)
ret |= KVM_X86_SHADOW_INT_STI;
if (interruptibility & GUEST_INTR_STATE_MOV_SS)
ret |= KVM_X86_SHADOW_INT_MOV_SS;
return ret;
}
static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
{
u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
u32 interruptibility = interruptibility_old;
interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
if (mask & KVM_X86_SHADOW_INT_MOV_SS)
interruptibility |= GUEST_INTR_STATE_MOV_SS;
else if (mask & KVM_X86_SHADOW_INT_STI)
interruptibility |= GUEST_INTR_STATE_STI;
if ((interruptibility != interruptibility_old))
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
}
static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
{
unsigned long rip;
rip = kvm_rip_read(vcpu);
rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_rip_write(vcpu, rip);
/* skipping an emulated instruction also counts */
vmx_set_interrupt_shadow(vcpu, 0);
}
/*
* KVM wants to inject page-faults which it got to the guest. This function
* checks whether in a nested guest, we need to inject them to L1 or L2.
*/
static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned nr)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
if (!(vmcs12->exception_bitmap & (1u << nr)))
return 0;
nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
vmcs_read32(VM_EXIT_INTR_INFO),
vmcs_readl(EXIT_QUALIFICATION));
return 1;
}
static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
bool has_error_code, u32 error_code,
bool reinject)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 intr_info = nr | INTR_INFO_VALID_MASK;
if (!reinject && is_guest_mode(vcpu) &&
nested_vmx_check_exception(vcpu, nr))
return;
if (has_error_code) {
vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
intr_info |= INTR_INFO_DELIVER_CODE_MASK;
}
if (vmx->rmode.vm86_active) {
int inc_eip = 0;
if (kvm_exception_is_soft(nr))
inc_eip = vcpu->arch.event_exit_inst_len;
if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
if (kvm_exception_is_soft(nr)) {
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmx->vcpu.arch.event_exit_inst_len);
intr_info |= INTR_TYPE_SOFT_EXCEPTION;
} else
intr_info |= INTR_TYPE_HARD_EXCEPTION;
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
}
static bool vmx_rdtscp_supported(void)
{
return cpu_has_vmx_rdtscp();
}
static bool vmx_invpcid_supported(void)
{
return cpu_has_vmx_invpcid() && enable_ept;
}
/*
* Swap MSR entry in host/guest MSR entry array.
*/
static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
{
struct shared_msr_entry tmp;
tmp = vmx->guest_msrs[to];
vmx->guest_msrs[to] = vmx->guest_msrs[from];
vmx->guest_msrs[from] = tmp;
}
static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
{
unsigned long *msr_bitmap;
if (is_guest_mode(vcpu))
msr_bitmap = to_vmx(vcpu)->nested.msr_bitmap;
else if (cpu_has_secondary_exec_ctrls() &&
(vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
if (enable_apicv && kvm_vcpu_apicv_active(vcpu)) {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode_x2apic_apicv;
else
msr_bitmap = vmx_msr_bitmap_legacy_x2apic_apicv;
} else {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
else
msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
}
} else {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode;
else
msr_bitmap = vmx_msr_bitmap_legacy;
}
vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
}
/*
* Set up the vmcs to automatically save and restore system
* msrs. Don't touch the 64-bit msrs if the guest is in legacy
* mode, as fiddling with msrs is very expensive.
*/
static void setup_msrs(struct vcpu_vmx *vmx)
{
int save_nmsrs, index;
save_nmsrs = 0;
#ifdef CONFIG_X86_64
if (is_long_mode(&vmx->vcpu)) {
index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
if (index >= 0)
move_msr_up(vmx, index, save_nmsrs++);
index = __find_msr_index(vmx, MSR_LSTAR);
if (index >= 0)
move_msr_up(vmx, index, save_nmsrs++);
index = __find_msr_index(vmx, MSR_CSTAR);
if (index >= 0)
move_msr_up(vmx, index, save_nmsrs++);
index = __find_msr_index(vmx, MSR_TSC_AUX);
if (index >= 0 && guest_cpuid_has_rdtscp(&vmx->vcpu))
move_msr_up(vmx, index, save_nmsrs++);
/*
* MSR_STAR is only needed on long mode guests, and only
* if efer.sce is enabled.
*/
index = __find_msr_index(vmx, MSR_STAR);
if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
move_msr_up(vmx, index, save_nmsrs++);
}
#endif
index = __find_msr_index(vmx, MSR_EFER);
if (index >= 0 && update_transition_efer(vmx, index))
move_msr_up(vmx, index, save_nmsrs++);
vmx->save_nmsrs = save_nmsrs;
if (cpu_has_vmx_msr_bitmap())
vmx_set_msr_bitmap(&vmx->vcpu);
}
/*
* reads and returns guest's timestamp counter "register"
* guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
* -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
*/
static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
{
u64 host_tsc, tsc_offset;
host_tsc = rdtsc();
tsc_offset = vmcs_read64(TSC_OFFSET);
return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
}
/*
* writes 'offset' into guest's timestamp counter offset register
*/
static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
{
if (is_guest_mode(vcpu)) {
/*
* We're here if L1 chose not to trap WRMSR to TSC. According
* to the spec, this should set L1's TSC; The offset that L1
* set for L2 remains unchanged, and still needs to be added
* to the newly set TSC to get L2's TSC.
*/
struct vmcs12 *vmcs12;
/* recalculate vmcs02.TSC_OFFSET: */
vmcs12 = get_vmcs12(vcpu);
vmcs_write64(TSC_OFFSET, offset +
(nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
vmcs12->tsc_offset : 0));
} else {
trace_kvm_write_tsc_offset(vcpu->vcpu_id,
vmcs_read64(TSC_OFFSET), offset);
vmcs_write64(TSC_OFFSET, offset);
}
}
static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
{
struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
}
/*
* nested_vmx_allowed() checks whether a guest should be allowed to use VMX
* instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
* all guests if the "nested" module option is off, and can also be disabled
* for a single guest by disabling its VMX cpuid bit.
*/
static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
{
return nested && guest_cpuid_has_vmx(vcpu);
}
/*
* nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
* returned for the various VMX controls MSRs when nested VMX is enabled.
* The same values should also be used to verify that vmcs12 control fields are
* valid during nested entry from L1 to L2.
* Each of these control msrs has a low and high 32-bit half: A low bit is on
* if the corresponding bit in the (32-bit) control field *must* be on, and a
* bit in the high half is on if the corresponding bit in the control field
* may be on. See also vmx_control_verify().
*/
static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
{
/*
* Note that as a general rule, the high half of the MSRs (bits in
* the control fields which may be 1) should be initialized by the
* intersection of the underlying hardware's MSR (i.e., features which
* can be supported) and the list of features we want to expose -
* because they are known to be properly supported in our code.
* Also, usually, the low half of the MSRs (bits which must be 1) can
* be set to 0, meaning that L1 may turn off any of these bits. The
* reason is that if one of these bits is necessary, it will appear
* in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
* fields of vmcs01 and vmcs02, will turn these bits off - and
* nested_vmx_exit_handled() will not pass related exits to L1.
* These rules have exceptions below.
*/
/* pin-based controls */
rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
vmx->nested.nested_vmx_pinbased_ctls_low,
vmx->nested.nested_vmx_pinbased_ctls_high);
vmx->nested.nested_vmx_pinbased_ctls_low |=
PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
vmx->nested.nested_vmx_pinbased_ctls_high &=
PIN_BASED_EXT_INTR_MASK |
PIN_BASED_NMI_EXITING |
PIN_BASED_VIRTUAL_NMIS;
vmx->nested.nested_vmx_pinbased_ctls_high |=
PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
PIN_BASED_VMX_PREEMPTION_TIMER;
if (kvm_vcpu_apicv_active(&vmx->vcpu))
vmx->nested.nested_vmx_pinbased_ctls_high |=
PIN_BASED_POSTED_INTR;
/* exit controls */
rdmsr(MSR_IA32_VMX_EXIT_CTLS,
vmx->nested.nested_vmx_exit_ctls_low,
vmx->nested.nested_vmx_exit_ctls_high);
vmx->nested.nested_vmx_exit_ctls_low =
VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
vmx->nested.nested_vmx_exit_ctls_high &=
#ifdef CONFIG_X86_64
VM_EXIT_HOST_ADDR_SPACE_SIZE |
#endif
VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
vmx->nested.nested_vmx_exit_ctls_high |=
VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
if (kvm_mpx_supported())
vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
/* We support free control of debug control saving. */
vmx->nested.nested_vmx_exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
/* entry controls */
rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
vmx->nested.nested_vmx_entry_ctls_low,
vmx->nested.nested_vmx_entry_ctls_high);
vmx->nested.nested_vmx_entry_ctls_low =
VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
vmx->nested.nested_vmx_entry_ctls_high &=
#ifdef CONFIG_X86_64
VM_ENTRY_IA32E_MODE |
#endif
VM_ENTRY_LOAD_IA32_PAT;
vmx->nested.nested_vmx_entry_ctls_high |=
(VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
if (kvm_mpx_supported())
vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
/* We support free control of debug control loading. */
vmx->nested.nested_vmx_entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
/* cpu-based controls */
rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
vmx->nested.nested_vmx_procbased_ctls_low,
vmx->nested.nested_vmx_procbased_ctls_high);
vmx->nested.nested_vmx_procbased_ctls_low =
CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
vmx->nested.nested_vmx_procbased_ctls_high &=
CPU_BASED_VIRTUAL_INTR_PENDING |
CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING |
#ifdef CONFIG_X86_64
CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
#endif
CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
/*
* We can allow some features even when not supported by the
* hardware. For example, L1 can specify an MSR bitmap - and we
* can use it to avoid exits to L1 - even when L0 runs L2
* without MSR bitmaps.
*/
vmx->nested.nested_vmx_procbased_ctls_high |=
CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
CPU_BASED_USE_MSR_BITMAPS;
/* We support free control of CR3 access interception. */
vmx->nested.nested_vmx_procbased_ctls_low &=
~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
/* secondary cpu-based controls */
rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
vmx->nested.nested_vmx_secondary_ctls_low,
vmx->nested.nested_vmx_secondary_ctls_high);
vmx->nested.nested_vmx_secondary_ctls_low = 0;
vmx->nested.nested_vmx_secondary_ctls_high &=
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
SECONDARY_EXEC_RDTSCP |
SECONDARY_EXEC_DESC |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_ENABLE_VPID |
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
SECONDARY_EXEC_WBINVD_EXITING |
SECONDARY_EXEC_XSAVES;
if (enable_ept) {
/* nested EPT: emulate EPT also to L1 */
vmx->nested.nested_vmx_secondary_ctls_high |=
SECONDARY_EXEC_ENABLE_EPT;
vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
VMX_EPTP_WB_BIT | VMX_EPT_2MB_PAGE_BIT |
VMX_EPT_INVEPT_BIT;
if (cpu_has_vmx_ept_execute_only())
vmx->nested.nested_vmx_ept_caps |=
VMX_EPT_EXECUTE_ONLY_BIT;
vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
VMX_EPT_EXTENT_CONTEXT_BIT;
} else
vmx->nested.nested_vmx_ept_caps = 0;
/*
* Old versions of KVM use the single-context version without
* checking for support, so declare that it is supported even
* though it is treated as global context. The alternative is
* not failing the single-context invvpid, and it is worse.
*/
if (enable_vpid)
vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
VMX_VPID_EXTENT_SUPPORTED_MASK;
else
vmx->nested.nested_vmx_vpid_caps = 0;
if (enable_unrestricted_guest)
vmx->nested.nested_vmx_secondary_ctls_high |=
SECONDARY_EXEC_UNRESTRICTED_GUEST;
/* miscellaneous data */
rdmsr(MSR_IA32_VMX_MISC,
vmx->nested.nested_vmx_misc_low,
vmx->nested.nested_vmx_misc_high);
vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
vmx->nested.nested_vmx_misc_low |=
VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
VMX_MISC_ACTIVITY_HLT;
vmx->nested.nested_vmx_misc_high = 0;
/*
* This MSR reports some information about VMX support. We
* should return information about the VMX we emulate for the
* guest, and the VMCS structure we give it - not about the
* VMX support of the underlying hardware.
*/
vmx->nested.nested_vmx_basic =
VMCS12_REVISION |
VMX_BASIC_TRUE_CTLS |
((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
(VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
if (cpu_has_vmx_basic_inout())
vmx->nested.nested_vmx_basic |= VMX_BASIC_INOUT;
/*
* These MSRs specify bits which the guest must keep fixed on
* while L1 is in VMXON mode (in L1's root mode, or running an L2).
* We picked the standard core2 setting.
*/
#define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
#define VMXON_CR4_ALWAYSON X86_CR4_VMXE
vmx->nested.nested_vmx_cr0_fixed0 = VMXON_CR0_ALWAYSON;
vmx->nested.nested_vmx_cr4_fixed0 = VMXON_CR4_ALWAYSON;
/* These MSRs specify bits which the guest must keep fixed off. */
rdmsrl(MSR_IA32_VMX_CR0_FIXED1, vmx->nested.nested_vmx_cr0_fixed1);
rdmsrl(MSR_IA32_VMX_CR4_FIXED1, vmx->nested.nested_vmx_cr4_fixed1);
/* highest index: VMX_PREEMPTION_TIMER_VALUE */
vmx->nested.nested_vmx_vmcs_enum = 0x2e;
}
/*
* if fixed0[i] == 1: val[i] must be 1
* if fixed1[i] == 0: val[i] must be 0
*/
static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
{
return ((val & fixed1) | fixed0) == val;
}
static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
{
return fixed_bits_valid(control, low, high);
}
static inline u64 vmx_control_msr(u32 low, u32 high)
{
return low | ((u64)high << 32);
}
static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
{
superset &= mask;
subset &= mask;
return (superset | subset) == superset;
}
static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
{
const u64 feature_and_reserved =
/* feature (except bit 48; see below) */
BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
/* reserved */
BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
u64 vmx_basic = vmx->nested.nested_vmx_basic;
if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
return -EINVAL;
/*
* KVM does not emulate a version of VMX that constrains physical
* addresses of VMX structures (e.g. VMCS) to 32-bits.
*/
if (data & BIT_ULL(48))
return -EINVAL;
if (vmx_basic_vmcs_revision_id(vmx_basic) !=
vmx_basic_vmcs_revision_id(data))
return -EINVAL;
if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
return -EINVAL;
vmx->nested.nested_vmx_basic = data;
return 0;
}
static int
vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
{
u64 supported;
u32 *lowp, *highp;
switch (msr_index) {
case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
lowp = &vmx->nested.nested_vmx_pinbased_ctls_low;
highp = &vmx->nested.nested_vmx_pinbased_ctls_high;
break;
case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
lowp = &vmx->nested.nested_vmx_procbased_ctls_low;
highp = &vmx->nested.nested_vmx_procbased_ctls_high;
break;
case MSR_IA32_VMX_TRUE_EXIT_CTLS:
lowp = &vmx->nested.nested_vmx_exit_ctls_low;
highp = &vmx->nested.nested_vmx_exit_ctls_high;
break;
case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
lowp = &vmx->nested.nested_vmx_entry_ctls_low;
highp = &vmx->nested.nested_vmx_entry_ctls_high;
break;
case MSR_IA32_VMX_PROCBASED_CTLS2:
lowp = &vmx->nested.nested_vmx_secondary_ctls_low;
highp = &vmx->nested.nested_vmx_secondary_ctls_high;
break;
default:
BUG();
}
supported = vmx_control_msr(*lowp, *highp);
/* Check must-be-1 bits are still 1. */
if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
return -EINVAL;
/* Check must-be-0 bits are still 0. */
if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
return -EINVAL;
*lowp = data;
*highp = data >> 32;
return 0;
}
static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
{
const u64 feature_and_reserved_bits =
/* feature */
BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
/* reserved */
GENMASK_ULL(13, 9) | BIT_ULL(31);
u64 vmx_misc;
vmx_misc = vmx_control_msr(vmx->nested.nested_vmx_misc_low,
vmx->nested.nested_vmx_misc_high);
if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
return -EINVAL;
if ((vmx->nested.nested_vmx_pinbased_ctls_high &
PIN_BASED_VMX_PREEMPTION_TIMER) &&
vmx_misc_preemption_timer_rate(data) !=
vmx_misc_preemption_timer_rate(vmx_misc))
return -EINVAL;
if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
return -EINVAL;
if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
return -EINVAL;
if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
return -EINVAL;
vmx->nested.nested_vmx_misc_low = data;
vmx->nested.nested_vmx_misc_high = data >> 32;
return 0;
}
static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
{
u64 vmx_ept_vpid_cap;
vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.nested_vmx_ept_caps,
vmx->nested.nested_vmx_vpid_caps);
/* Every bit is either reserved or a feature bit. */
if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
return -EINVAL;
vmx->nested.nested_vmx_ept_caps = data;
vmx->nested.nested_vmx_vpid_caps = data >> 32;
return 0;
}
static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
{
u64 *msr;
switch (msr_index) {
case MSR_IA32_VMX_CR0_FIXED0:
msr = &vmx->nested.nested_vmx_cr0_fixed0;
break;
case MSR_IA32_VMX_CR4_FIXED0:
msr = &vmx->nested.nested_vmx_cr4_fixed0;
break;
default:
BUG();
}
/*
* 1 bits (which indicates bits which "must-be-1" during VMX operation)
* must be 1 in the restored value.
*/
if (!is_bitwise_subset(data, *msr, -1ULL))
return -EINVAL;
*msr = data;
return 0;
}
/*
* Called when userspace is restoring VMX MSRs.
*
* Returns 0 on success, non-0 otherwise.
*/
static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
switch (msr_index) {
case MSR_IA32_VMX_BASIC:
return vmx_restore_vmx_basic(vmx, data);
case MSR_IA32_VMX_PINBASED_CTLS:
case MSR_IA32_VMX_PROCBASED_CTLS:
case MSR_IA32_VMX_EXIT_CTLS:
case MSR_IA32_VMX_ENTRY_CTLS:
/*
* The "non-true" VMX capability MSRs are generated from the
* "true" MSRs, so we do not support restoring them directly.
*
* If userspace wants to emulate VMX_BASIC[55]=0, userspace
* should restore the "true" MSRs with the must-be-1 bits
* set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
* DEFAULT SETTINGS".
*/
return -EINVAL;
case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
case MSR_IA32_VMX_TRUE_EXIT_CTLS:
case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
case MSR_IA32_VMX_PROCBASED_CTLS2:
return vmx_restore_control_msr(vmx, msr_index, data);
case MSR_IA32_VMX_MISC:
return vmx_restore_vmx_misc(vmx, data);
case MSR_IA32_VMX_CR0_FIXED0:
case MSR_IA32_VMX_CR4_FIXED0:
return vmx_restore_fixed0_msr(vmx, msr_index, data);
case MSR_IA32_VMX_CR0_FIXED1:
case MSR_IA32_VMX_CR4_FIXED1:
/*
* These MSRs are generated based on the vCPU's CPUID, so we
* do not support restoring them directly.
*/
return -EINVAL;
case MSR_IA32_VMX_EPT_VPID_CAP:
return vmx_restore_vmx_ept_vpid_cap(vmx, data);
case MSR_IA32_VMX_VMCS_ENUM:
vmx->nested.nested_vmx_vmcs_enum = data;
return 0;
default:
/*
* The rest of the VMX capability MSRs do not support restore.
*/
return -EINVAL;
}
}
/* Returns 0 on success, non-0 otherwise. */
static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
switch (msr_index) {
case MSR_IA32_VMX_BASIC:
*pdata = vmx->nested.nested_vmx_basic;
break;
case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
case MSR_IA32_VMX_PINBASED_CTLS:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_pinbased_ctls_low,
vmx->nested.nested_vmx_pinbased_ctls_high);
if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
*pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
break;
case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
case MSR_IA32_VMX_PROCBASED_CTLS:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_procbased_ctls_low,
vmx->nested.nested_vmx_procbased_ctls_high);
if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
*pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
break;
case MSR_IA32_VMX_TRUE_EXIT_CTLS:
case MSR_IA32_VMX_EXIT_CTLS:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_exit_ctls_low,
vmx->nested.nested_vmx_exit_ctls_high);
if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
*pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
break;
case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
case MSR_IA32_VMX_ENTRY_CTLS:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_entry_ctls_low,
vmx->nested.nested_vmx_entry_ctls_high);
if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
*pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
break;
case MSR_IA32_VMX_MISC:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_misc_low,
vmx->nested.nested_vmx_misc_high);
break;
case MSR_IA32_VMX_CR0_FIXED0:
*pdata = vmx->nested.nested_vmx_cr0_fixed0;
break;
case MSR_IA32_VMX_CR0_FIXED1:
*pdata = vmx->nested.nested_vmx_cr0_fixed1;
break;
case MSR_IA32_VMX_CR4_FIXED0:
*pdata = vmx->nested.nested_vmx_cr4_fixed0;
break;
case MSR_IA32_VMX_CR4_FIXED1:
*pdata = vmx->nested.nested_vmx_cr4_fixed1;
break;
case MSR_IA32_VMX_VMCS_ENUM:
*pdata = vmx->nested.nested_vmx_vmcs_enum;
break;
case MSR_IA32_VMX_PROCBASED_CTLS2:
*pdata = vmx_control_msr(
vmx->nested.nested_vmx_secondary_ctls_low,
vmx->nested.nested_vmx_secondary_ctls_high);
break;
case MSR_IA32_VMX_EPT_VPID_CAP:
*pdata = vmx->nested.nested_vmx_ept_caps |
((u64)vmx->nested.nested_vmx_vpid_caps << 32);
break;
default:
return 1;
}
return 0;
}
static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
uint64_t val)
{
uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
return !(val & ~valid_bits);
}
/*
* Reads an msr value (of 'msr_index') into 'pdata'.
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
struct shared_msr_entry *msr;
switch (msr_info->index) {
#ifdef CONFIG_X86_64
case MSR_FS_BASE:
msr_info->data = vmcs_readl(GUEST_FS_BASE);
break;
case MSR_GS_BASE:
msr_info->data = vmcs_readl(GUEST_GS_BASE);
break;
case MSR_KERNEL_GS_BASE:
vmx_load_host_state(to_vmx(vcpu));
msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
break;
#endif
case MSR_EFER:
return kvm_get_msr_common(vcpu, msr_info);
case MSR_IA32_TSC:
msr_info->data = guest_read_tsc(vcpu);
break;
case MSR_IA32_SYSENTER_CS:
msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
break;
case MSR_IA32_SYSENTER_EIP:
msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
break;
case MSR_IA32_SYSENTER_ESP:
msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
break;
case MSR_IA32_BNDCFGS:
if (!kvm_mpx_supported())
return 1;
msr_info->data = vmcs_read64(GUEST_BNDCFGS);
break;
case MSR_IA32_MCG_EXT_CTL:
if (!msr_info->host_initiated &&
!(to_vmx(vcpu)->msr_ia32_feature_control &
FEATURE_CONTROL_LMCE))
return 1;
msr_info->data = vcpu->arch.mcg_ext_ctl;
break;
case MSR_IA32_FEATURE_CONTROL:
msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
break;
case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
if (!nested_vmx_allowed(vcpu))
return 1;
return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
case MSR_IA32_XSS:
if (!vmx_xsaves_supported())
return 1;
msr_info->data = vcpu->arch.ia32_xss;
break;
case MSR_TSC_AUX:
if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
return 1;
/* Otherwise falls through */
default:
msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
if (msr) {
msr_info->data = msr->data;
break;
}
return kvm_get_msr_common(vcpu, msr_info);
}
return 0;
}
static void vmx_leave_nested(struct kvm_vcpu *vcpu);
/*
* Writes msr value into into the appropriate "register".
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct shared_msr_entry *msr;
int ret = 0;
u32 msr_index = msr_info->index;
u64 data = msr_info->data;
switch (msr_index) {
case MSR_EFER:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
#ifdef CONFIG_X86_64
case MSR_FS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_FS_BASE, data);
break;
case MSR_GS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_GS_BASE, data);
break;
case MSR_KERNEL_GS_BASE:
vmx_load_host_state(vmx);
vmx->msr_guest_kernel_gs_base = data;
break;
#endif
case MSR_IA32_SYSENTER_CS:
vmcs_write32(GUEST_SYSENTER_CS, data);
break;
case MSR_IA32_SYSENTER_EIP:
vmcs_writel(GUEST_SYSENTER_EIP, data);
break;
case MSR_IA32_SYSENTER_ESP:
vmcs_writel(GUEST_SYSENTER_ESP, data);
break;
case MSR_IA32_BNDCFGS:
if (!kvm_mpx_supported())
return 1;
vmcs_write64(GUEST_BNDCFGS, data);
break;
case MSR_IA32_TSC:
kvm_write_tsc(vcpu, msr_info);
break;
case MSR_IA32_CR_PAT:
if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
return 1;
vmcs_write64(GUEST_IA32_PAT, data);
vcpu->arch.pat = data;
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_IA32_TSC_ADJUST:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_IA32_MCG_EXT_CTL:
if ((!msr_info->host_initiated &&
!(to_vmx(vcpu)->msr_ia32_feature_control &
FEATURE_CONTROL_LMCE)) ||
(data & ~MCG_EXT_CTL_LMCE_EN))
return 1;
vcpu->arch.mcg_ext_ctl = data;
break;
case MSR_IA32_FEATURE_CONTROL:
if (!vmx_feature_control_msr_valid(vcpu, data) ||
(to_vmx(vcpu)->msr_ia32_feature_control &
FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
return 1;
vmx->msr_ia32_feature_control = data;
if (msr_info->host_initiated && data == 0)
vmx_leave_nested(vcpu);
break;
case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
if (!msr_info->host_initiated)
return 1; /* they are read-only */
if (!nested_vmx_allowed(vcpu))
return 1;
return vmx_set_vmx_msr(vcpu, msr_index, data);
case MSR_IA32_XSS:
if (!vmx_xsaves_supported())
return 1;
/*
* The only supported bit as of Skylake is bit 8, but
* it is not supported on KVM.
*/
if (data != 0)
return 1;
vcpu->arch.ia32_xss = data;
if (vcpu->arch.ia32_xss != host_xss)
add_atomic_switch_msr(vmx, MSR_IA32_XSS,
vcpu->arch.ia32_xss, host_xss);
else
clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
break;
case MSR_TSC_AUX:
if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
return 1;
/* Check reserved bit, higher 32 bits should be zero */
if ((data >> 32) != 0)
return 1;
/* Otherwise falls through */
default:
msr = find_msr_entry(vmx, msr_index);
if (msr) {
u64 old_msr_data = msr->data;
msr->data = data;
if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
preempt_disable();
ret = kvm_set_shared_msr(msr->index, msr->data,
msr->mask);
preempt_enable();
if (ret)
msr->data = old_msr_data;
}
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
}
return ret;
}
static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
{
__set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
switch (reg) {
case VCPU_REGS_RSP:
vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
break;
case VCPU_REGS_RIP:
vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
break;
case VCPU_EXREG_PDPTR:
if (enable_ept)
ept_save_pdptrs(vcpu);
break;
default:
break;
}
}
static __init int cpu_has_kvm_support(void)
{
return cpu_has_vmx();
}
static __init int vmx_disabled_by_bios(void)
{
u64 msr;
rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
if (msr & FEATURE_CONTROL_LOCKED) {
/* launched w/ TXT and VMX disabled */
if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
&& tboot_enabled())
return 1;
/* launched w/o TXT and VMX only enabled w/ TXT */
if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
&& (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
&& !tboot_enabled()) {
printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
"activate TXT before enabling KVM\n");
return 1;
}
/* launched w/o TXT and VMX disabled */
if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
&& !tboot_enabled())
return 1;
}
return 0;
}
static void kvm_cpu_vmxon(u64 addr)
{
intel_pt_handle_vmx(1);
asm volatile (ASM_VMX_VMXON_RAX
: : "a"(&addr), "m"(addr)
: "memory", "cc");
}
static int hardware_enable(void)
{
int cpu = raw_smp_processor_id();
u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
u64 old, test_bits;
if (cr4_read_shadow() & X86_CR4_VMXE)
return -EBUSY;
INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
/*
* Now we can enable the vmclear operation in kdump
* since the loaded_vmcss_on_cpu list on this cpu
* has been initialized.
*
* Though the cpu is not in VMX operation now, there
* is no problem to enable the vmclear operation
* for the loaded_vmcss_on_cpu list is empty!
*/
crash_enable_local_vmclear(cpu);
rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
test_bits = FEATURE_CONTROL_LOCKED;
test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
if (tboot_enabled())
test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
if ((old & test_bits) != test_bits) {
/* enable and lock */
wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
}
cr4_set_bits(X86_CR4_VMXE);
if (vmm_exclusive) {
kvm_cpu_vmxon(phys_addr);
ept_sync_global();
}
native_store_gdt(this_cpu_ptr(&host_gdt));
return 0;
}
static void vmclear_local_loaded_vmcss(void)
{
int cpu = raw_smp_processor_id();
struct loaded_vmcs *v, *n;
list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
loaded_vmcss_on_cpu_link)
__loaded_vmcs_clear(v);
}
/* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
* tricks.
*/
static void kvm_cpu_vmxoff(void)
{
asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
intel_pt_handle_vmx(0);
}
static void hardware_disable(void)
{
if (vmm_exclusive) {
vmclear_local_loaded_vmcss();
kvm_cpu_vmxoff();
}
cr4_clear_bits(X86_CR4_VMXE);
}
static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
u32 msr, u32 *result)
{
u32 vmx_msr_low, vmx_msr_high;
u32 ctl = ctl_min | ctl_opt;
rdmsr(msr, vmx_msr_low, vmx_msr_high);
ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
/* Ensure minimum (required) set of control bits are supported. */
if (ctl_min & ~ctl)
return -EIO;
*result = ctl;
return 0;
}
static __init bool allow_1_setting(u32 msr, u32 ctl)
{
u32 vmx_msr_low, vmx_msr_high;
rdmsr(msr, vmx_msr_low, vmx_msr_high);
return vmx_msr_high & ctl;
}
static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
{
u32 vmx_msr_low, vmx_msr_high;
u32 min, opt, min2, opt2;
u32 _pin_based_exec_control = 0;
u32 _cpu_based_exec_control = 0;
u32 _cpu_based_2nd_exec_control = 0;
u32 _vmexit_control = 0;
u32 _vmentry_control = 0;
min = CPU_BASED_HLT_EXITING |
#ifdef CONFIG_X86_64
CPU_BASED_CR8_LOAD_EXITING |
CPU_BASED_CR8_STORE_EXITING |
#endif
CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING |
CPU_BASED_USE_IO_BITMAPS |
CPU_BASED_MOV_DR_EXITING |
CPU_BASED_USE_TSC_OFFSETING |
CPU_BASED_MWAIT_EXITING |
CPU_BASED_MONITOR_EXITING |
CPU_BASED_INVLPG_EXITING |
CPU_BASED_RDPMC_EXITING;
opt = CPU_BASED_TPR_SHADOW |
CPU_BASED_USE_MSR_BITMAPS |
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
&_cpu_based_exec_control) < 0)
return -EIO;
#ifdef CONFIG_X86_64
if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
_cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
~CPU_BASED_CR8_STORE_EXITING;
#endif
if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
min2 = 0;
opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_WBINVD_EXITING |
SECONDARY_EXEC_ENABLE_VPID |
SECONDARY_EXEC_ENABLE_EPT |
SECONDARY_EXEC_UNRESTRICTED_GUEST |
SECONDARY_EXEC_PAUSE_LOOP_EXITING |
SECONDARY_EXEC_RDTSCP |
SECONDARY_EXEC_ENABLE_INVPCID |
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
SECONDARY_EXEC_SHADOW_VMCS |
SECONDARY_EXEC_XSAVES |
SECONDARY_EXEC_ENABLE_PML |
SECONDARY_EXEC_TSC_SCALING;
if (adjust_vmx_controls(min2, opt2,
MSR_IA32_VMX_PROCBASED_CTLS2,
&_cpu_based_2nd_exec_control) < 0)
return -EIO;
}
#ifndef CONFIG_X86_64
if (!(_cpu_based_2nd_exec_control &
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
_cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
#endif
if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
_cpu_based_2nd_exec_control &= ~(
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
/* CR3 accesses and invlpg don't need to cause VM Exits when EPT
enabled */
_cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING |
CPU_BASED_INVLPG_EXITING);
rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
vmx_capability.ept, vmx_capability.vpid);
}
min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
#ifdef CONFIG_X86_64
min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
#endif
opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
VM_EXIT_CLEAR_BNDCFGS;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
&_vmexit_control) < 0)
return -EIO;
min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
PIN_BASED_VMX_PREEMPTION_TIMER;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
&_pin_based_exec_control) < 0)
return -EIO;
if (cpu_has_broken_vmx_preemption_timer())
_pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
if (!(_cpu_based_2nd_exec_control &
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
_pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
&_vmentry_control) < 0)
return -EIO;
rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
/* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
return -EIO;
#ifdef CONFIG_X86_64
/* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
if (vmx_msr_high & (1u<<16))
return -EIO;
#endif
/* Require Write-Back (WB) memory type for VMCS accesses. */
if (((vmx_msr_high >> 18) & 15) != 6)
return -EIO;
vmcs_conf->size = vmx_msr_high & 0x1fff;
vmcs_conf->order = get_order(vmcs_conf->size);
vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
vmcs_conf->revision_id = vmx_msr_low;
vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
vmcs_conf->vmexit_ctrl = _vmexit_control;
vmcs_conf->vmentry_ctrl = _vmentry_control;
cpu_has_load_ia32_efer =
allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
VM_ENTRY_LOAD_IA32_EFER)
&& allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
VM_EXIT_LOAD_IA32_EFER);
cpu_has_load_perf_global_ctrl =
allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
&& allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
/*
* Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
* but due to errata below it can't be used. Workaround is to use
* msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
*
* VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
*
* AAK155 (model 26)
* AAP115 (model 30)
* AAT100 (model 37)
* BC86,AAY89,BD102 (model 44)
* BA97 (model 46)
*
*/
if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
switch (boot_cpu_data.x86_model) {
case 26:
case 30:
case 37:
case 44:
case 46:
cpu_has_load_perf_global_ctrl = false;
printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
"does not work properly. Using workaround\n");
break;
default:
break;
}
}
if (boot_cpu_has(X86_FEATURE_XSAVES))
rdmsrl(MSR_IA32_XSS, host_xss);
return 0;
}
static struct vmcs *alloc_vmcs_cpu(int cpu)
{
int node = cpu_to_node(cpu);
struct page *pages;
struct vmcs *vmcs;
pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
if (!pages)
return NULL;
vmcs = page_address(pages);
memset(vmcs, 0, vmcs_config.size);
vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
return vmcs;
}
static struct vmcs *alloc_vmcs(void)
{
return alloc_vmcs_cpu(raw_smp_processor_id());
}
static void free_vmcs(struct vmcs *vmcs)
{
free_pages((unsigned long)vmcs, vmcs_config.order);
}
/*
* Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
*/
static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
{
if (!loaded_vmcs->vmcs)
return;
loaded_vmcs_clear(loaded_vmcs);
free_vmcs(loaded_vmcs->vmcs);
loaded_vmcs->vmcs = NULL;
WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
}
static void free_kvm_area(void)
{
int cpu;
for_each_possible_cpu(cpu) {
free_vmcs(per_cpu(vmxarea, cpu));
per_cpu(vmxarea, cpu) = NULL;
}
}
static void init_vmcs_shadow_fields(void)
{
int i, j;
/* No checks for read only fields yet */
for (i = j = 0; i < max_shadow_read_write_fields; i++) {
switch (shadow_read_write_fields[i]) {
case GUEST_BNDCFGS:
if (!kvm_mpx_supported())
continue;
break;
default:
break;
}
if (j < i)
shadow_read_write_fields[j] =
shadow_read_write_fields[i];
j++;
}
max_shadow_read_write_fields = j;
/* shadowed fields guest access without vmexit */
for (i = 0; i < max_shadow_read_write_fields; i++) {
clear_bit(shadow_read_write_fields[i],
vmx_vmwrite_bitmap);
clear_bit(shadow_read_write_fields[i],
vmx_vmread_bitmap);
}
for (i = 0; i < max_shadow_read_only_fields; i++)
clear_bit(shadow_read_only_fields[i],
vmx_vmread_bitmap);
}
static __init int alloc_kvm_area(void)
{
int cpu;
for_each_possible_cpu(cpu) {
struct vmcs *vmcs;
vmcs = alloc_vmcs_cpu(cpu);
if (!vmcs) {
free_kvm_area();
return -ENOMEM;
}
per_cpu(vmxarea, cpu) = vmcs;
}
return 0;
}
static bool emulation_required(struct kvm_vcpu *vcpu)
{
return emulate_invalid_guest_state && !guest_state_valid(vcpu);
}
static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
struct kvm_segment *save)
{
if (!emulate_invalid_guest_state) {
/*
* CS and SS RPL should be equal during guest entry according
* to VMX spec, but in reality it is not always so. Since vcpu
* is in the middle of the transition from real mode to
* protected mode it is safe to assume that RPL 0 is a good
* default value.
*/
if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
save->selector &= ~SEGMENT_RPL_MASK;
save->dpl = save->selector & SEGMENT_RPL_MASK;
save->s = 1;
}
vmx_set_segment(vcpu, save, seg);
}
static void enter_pmode(struct kvm_vcpu *vcpu)
{
unsigned long flags;
struct vcpu_vmx *vmx = to_vmx(vcpu);
/*
* Update real mode segment cache. It may be not up-to-date if sement
* register was written while vcpu was in a guest mode.
*/
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
vmx->rmode.vm86_active = 0;
vmx_segment_cache_clear(vmx);
vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
flags = vmcs_readl(GUEST_RFLAGS);
flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
vmcs_writel(GUEST_RFLAGS, flags);
vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
(vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
update_exception_bitmap(vcpu);
fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
}
static void fix_rmode_seg(int seg, struct kvm_segment *save)
{
const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
struct kvm_segment var = *save;
var.dpl = 0x3;
if (seg == VCPU_SREG_CS)
var.type = 0x3;
if (!emulate_invalid_guest_state) {
var.selector = var.base >> 4;
var.base = var.base & 0xffff0;
var.limit = 0xffff;
var.g = 0;
var.db = 0;
var.present = 1;
var.s = 1;
var.l = 0;
var.unusable = 0;
var.type = 0x3;
var.avl = 0;
if (save->base & 0xf)
printk_once(KERN_WARNING "kvm: segment base is not "
"paragraph aligned when entering "
"protected mode (seg=%d)", seg);
}
vmcs_write16(sf->selector, var.selector);
vmcs_write32(sf->base, var.base);
vmcs_write32(sf->limit, var.limit);
vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
}
static void enter_rmode(struct kvm_vcpu *vcpu)
{
unsigned long flags;
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
vmx->rmode.vm86_active = 1;
/*
* Very old userspace does not call KVM_SET_TSS_ADDR before entering
* vcpu. Warn the user that an update is overdue.
*/
if (!vcpu->kvm->arch.tss_addr)
printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
"called before entering vcpu\n");
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
flags = vmcs_readl(GUEST_RFLAGS);
vmx->rmode.save_rflags = flags;
flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
vmcs_writel(GUEST_RFLAGS, flags);
vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
update_exception_bitmap(vcpu);
fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
kvm_mmu_reset_context(vcpu);
}
static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
if (!msr)
return;
/*
* Force kernel_gs_base reloading before EFER changes, as control
* of this msr depends on is_long_mode().
*/
vmx_load_host_state(to_vmx(vcpu));
vcpu->arch.efer = efer;
if (efer & EFER_LMA) {
vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
msr->data = efer;
} else {
vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
msr->data = efer & ~EFER_LME;
}
setup_msrs(vmx);
}
#ifdef CONFIG_X86_64
static void enter_lmode(struct kvm_vcpu *vcpu)
{
u32 guest_tr_ar;
vmx_segment_cache_clear(to_vmx(vcpu));
guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
pr_debug_ratelimited("%s: tss fixup for long mode. \n",
__func__);
vmcs_write32(GUEST_TR_AR_BYTES,
(guest_tr_ar & ~VMX_AR_TYPE_MASK)
| VMX_AR_TYPE_BUSY_64_TSS);
}
vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
}
static void exit_lmode(struct kvm_vcpu *vcpu)
{
vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
}
#endif
static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid)
{
vpid_sync_context(vpid);
if (enable_ept) {
if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
return;
ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
}
}
static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
{
__vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid);
}
static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
{
ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
}
static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
{
if (enable_ept && is_paging(vcpu))
vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
}
static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
{
ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
}
static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
{
struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
if (!test_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_dirty))
return;
if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
}
}
static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
{
struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
}
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_avail);
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_dirty);
}
static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
{
u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
SECONDARY_EXEC_UNRESTRICTED_GUEST &&
nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
return fixed_bits_valid(val, fixed0, fixed1);
}
static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
{
u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
return fixed_bits_valid(val, fixed0, fixed1);
}
static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
{
u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed0;
u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed1;
return fixed_bits_valid(val, fixed0, fixed1);
}
/* No difference in the restrictions on guest and host CR4 in VMX operation. */
#define nested_guest_cr4_valid nested_cr4_valid
#define nested_host_cr4_valid nested_cr4_valid
static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
unsigned long cr0,
struct kvm_vcpu *vcpu)
{
if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
vmx_decache_cr3(vcpu);
if (!(cr0 & X86_CR0_PG)) {
/* From paging/starting to nonpaging */
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
(CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING));
vcpu->arch.cr0 = cr0;
vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
} else if (!is_paging(vcpu)) {
/* From nonpaging to paging */
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
~(CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING));
vcpu->arch.cr0 = cr0;
vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
}
if (!(cr0 & X86_CR0_WP))
*hw_cr0 &= ~X86_CR0_WP;
}
static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long hw_cr0;
hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
if (enable_unrestricted_guest)
hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
else {
hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
enter_pmode(vcpu);
if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
enter_rmode(vcpu);
}
#ifdef CONFIG_X86_64
if (vcpu->arch.efer & EFER_LME) {
if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
enter_lmode(vcpu);
if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
exit_lmode(vcpu);
}
#endif
if (enable_ept)
ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
if (!vcpu->fpu_active)
hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
vmcs_writel(CR0_READ_SHADOW, cr0);
vmcs_writel(GUEST_CR0, hw_cr0);
vcpu->arch.cr0 = cr0;
/* depends on vcpu->arch.cr0 to be set to a new value */
vmx->emulation_required = emulation_required(vcpu);
}
static u64 construct_eptp(unsigned long root_hpa)
{
u64 eptp;
/* TODO write the value reading from MSR */
eptp = VMX_EPT_DEFAULT_MT |
VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
if (enable_ept_ad_bits)
eptp |= VMX_EPT_AD_ENABLE_BIT;
eptp |= (root_hpa & PAGE_MASK);
return eptp;
}
static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
{
unsigned long guest_cr3;
u64 eptp;
guest_cr3 = cr3;
if (enable_ept) {
eptp = construct_eptp(cr3);
vmcs_write64(EPT_POINTER, eptp);
if (is_paging(vcpu) || is_guest_mode(vcpu))
guest_cr3 = kvm_read_cr3(vcpu);
else
guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
ept_load_pdptrs(vcpu);
}
vmx_flush_tlb(vcpu);
vmcs_writel(GUEST_CR3, guest_cr3);
}
static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
{
/*
* Pass through host's Machine Check Enable value to hw_cr4, which
* is in force while we are in guest mode. Do not let guests control
* this bit, even if host CR4.MCE == 0.
*/
unsigned long hw_cr4 =
(cr4_read_shadow() & X86_CR4_MCE) |
(cr4 & ~X86_CR4_MCE) |
(to_vmx(vcpu)->rmode.vm86_active ?
KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
if (cr4 & X86_CR4_VMXE) {
/*
* To use VMXON (and later other VMX instructions), a guest
* must first be able to turn on cr4.VMXE (see handle_vmon()).
* So basically the check on whether to allow nested VMX
* is here.
*/
if (!nested_vmx_allowed(vcpu))
return 1;
}
if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
return 1;
vcpu->arch.cr4 = cr4;
if (enable_ept) {
if (!is_paging(vcpu)) {
hw_cr4 &= ~X86_CR4_PAE;
hw_cr4 |= X86_CR4_PSE;
} else if (!(cr4 & X86_CR4_PAE)) {
hw_cr4 &= ~X86_CR4_PAE;
}
}
if (!enable_unrestricted_guest && !is_paging(vcpu))
/*
* SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
* hardware. To emulate this behavior, SMEP/SMAP/PKU needs
* to be manually disabled when guest switches to non-paging
* mode.
*
* If !enable_unrestricted_guest, the CPU is always running
* with CR0.PG=1 and CR4 needs to be modified.
* If enable_unrestricted_guest, the CPU automatically
* disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
*/
hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
vmcs_writel(CR4_READ_SHADOW, cr4);
vmcs_writel(GUEST_CR4, hw_cr4);
return 0;
}
static void vmx_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 ar;
if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
*var = vmx->rmode.segs[seg];
if (seg == VCPU_SREG_TR
|| var->selector == vmx_read_guest_seg_selector(vmx, seg))
return;
var->base = vmx_read_guest_seg_base(vmx, seg);
var->selector = vmx_read_guest_seg_selector(vmx, seg);
return;
}
var->base = vmx_read_guest_seg_base(vmx, seg);
var->limit = vmx_read_guest_seg_limit(vmx, seg);
var->selector = vmx_read_guest_seg_selector(vmx, seg);
ar = vmx_read_guest_seg_ar(vmx, seg);
var->unusable = (ar >> 16) & 1;
var->type = ar & 15;
var->s = (ar >> 4) & 1;
var->dpl = (ar >> 5) & 3;
/*
* Some userspaces do not preserve unusable property. Since usable
* segment has to be present according to VMX spec we can use present
* property to amend userspace bug by making unusable segment always
* nonpresent. vmx_segment_access_rights() already marks nonpresent
* segment as unusable.
*/
var->present = !var->unusable;
var->avl = (ar >> 12) & 1;
var->l = (ar >> 13) & 1;
var->db = (ar >> 14) & 1;
var->g = (ar >> 15) & 1;
}
static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
{
struct kvm_segment s;
if (to_vmx(vcpu)->rmode.vm86_active) {
vmx_get_segment(vcpu, &s, seg);
return s.base;
}
return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
}
static int vmx_get_cpl(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (unlikely(vmx->rmode.vm86_active))
return 0;
else {
int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
return VMX_AR_DPL(ar);
}
}
static u32 vmx_segment_access_rights(struct kvm_segment *var)
{
u32 ar;
if (var->unusable || !var->present)
ar = 1 << 16;
else {
ar = var->type & 15;
ar |= (var->s & 1) << 4;
ar |= (var->dpl & 3) << 5;
ar |= (var->present & 1) << 7;
ar |= (var->avl & 1) << 12;
ar |= (var->l & 1) << 13;
ar |= (var->db & 1) << 14;
ar |= (var->g & 1) << 15;
}
return ar;
}
static void vmx_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
vmx_segment_cache_clear(vmx);
if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
vmx->rmode.segs[seg] = *var;
if (seg == VCPU_SREG_TR)
vmcs_write16(sf->selector, var->selector);
else if (var->s)
fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
goto out;
}
vmcs_writel(sf->base, var->base);
vmcs_write32(sf->limit, var->limit);
vmcs_write16(sf->selector, var->selector);
/*
* Fix the "Accessed" bit in AR field of segment registers for older
* qemu binaries.
* IA32 arch specifies that at the time of processor reset the
* "Accessed" bit in the AR field of segment registers is 1. And qemu
* is setting it to 0 in the userland code. This causes invalid guest
* state vmexit when "unrestricted guest" mode is turned on.
* Fix for this setup issue in cpu_reset is being pushed in the qemu
* tree. Newer qemu binaries with that qemu fix would not need this
* kvm hack.
*/
if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
var->type |= 0x1; /* Accessed */
vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
out:
vmx->emulation_required = emulation_required(vcpu);
}
static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
{
u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
*db = (ar >> 14) & 1;
*l = (ar >> 13) & 1;
}
static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
dt->address = vmcs_readl(GUEST_IDTR_BASE);
}
static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
vmcs_writel(GUEST_IDTR_BASE, dt->address);
}
static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
dt->address = vmcs_readl(GUEST_GDTR_BASE);
}
static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
vmcs_writel(GUEST_GDTR_BASE, dt->address);
}
static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
{
struct kvm_segment var;
u32 ar;
vmx_get_segment(vcpu, &var, seg);
var.dpl = 0x3;
if (seg == VCPU_SREG_CS)
var.type = 0x3;
ar = vmx_segment_access_rights(&var);
if (var.base != (var.selector << 4))
return false;
if (var.limit != 0xffff)
return false;
if (ar != 0xf3)
return false;
return true;
}
static bool code_segment_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs;
unsigned int cs_rpl;
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
cs_rpl = cs.selector & SEGMENT_RPL_MASK;
if (cs.unusable)
return false;
if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
return false;
if (!cs.s)
return false;
if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
if (cs.dpl > cs_rpl)
return false;
} else {
if (cs.dpl != cs_rpl)
return false;
}
if (!cs.present)
return false;
/* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
return true;
}
static bool stack_segment_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment ss;
unsigned int ss_rpl;
vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
ss_rpl = ss.selector & SEGMENT_RPL_MASK;
if (ss.unusable)
return true;
if (ss.type != 3 && ss.type != 7)
return false;
if (!ss.s)
return false;
if (ss.dpl != ss_rpl) /* DPL != RPL */
return false;
if (!ss.present)
return false;
return true;
}
static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
{
struct kvm_segment var;
unsigned int rpl;
vmx_get_segment(vcpu, &var, seg);
rpl = var.selector & SEGMENT_RPL_MASK;
if (var.unusable)
return true;
if (!var.s)
return false;
if (!var.present)
return false;
if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
if (var.dpl < rpl) /* DPL < RPL */
return false;
}
/* TODO: Add other members to kvm_segment_field to allow checking for other access
* rights flags
*/
return true;
}
static bool tr_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment tr;
vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
if (tr.unusable)
return false;
if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
return false;
if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
return false;
if (!tr.present)
return false;
return true;
}
static bool ldtr_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment ldtr;
vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
if (ldtr.unusable)
return true;
if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
return false;
if (ldtr.type != 2)
return false;
if (!ldtr.present)
return false;
return true;
}
static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs, ss;
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
return ((cs.selector & SEGMENT_RPL_MASK) ==
(ss.selector & SEGMENT_RPL_MASK));
}
/*
* Check if guest state is valid. Returns true if valid, false if
* not.
* We assume that registers are always usable
*/
static bool guest_state_valid(struct kvm_vcpu *vcpu)
{
if (enable_unrestricted_guest)
return true;
/* real mode guest state checks */
if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
return false;
} else {
/* protected mode guest state checks */
if (!cs_ss_rpl_check(vcpu))
return false;
if (!code_segment_valid(vcpu))
return false;
if (!stack_segment_valid(vcpu))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_DS))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_ES))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_FS))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_GS))
return false;
if (!tr_valid(vcpu))
return false;
if (!ldtr_valid(vcpu))
return false;
}
/* TODO:
* - Add checks on RIP
* - Add checks on RFLAGS
*/
return true;
}
static int init_rmode_tss(struct kvm *kvm)
{
gfn_t fn;
u16 data = 0;
int idx, r;
idx = srcu_read_lock(&kvm->srcu);
fn = kvm->arch.tss_addr >> PAGE_SHIFT;
r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
if (r < 0)
goto out;
data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
r = kvm_write_guest_page(kvm, fn++, &data,
TSS_IOPB_BASE_OFFSET, sizeof(u16));
if (r < 0)
goto out;
r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
if (r < 0)
goto out;
r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
if (r < 0)
goto out;
data = ~0;
r = kvm_write_guest_page(kvm, fn, &data,
RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
sizeof(u8));
out:
srcu_read_unlock(&kvm->srcu, idx);
return r;
}
static int init_rmode_identity_map(struct kvm *kvm)
{
int i, idx, r = 0;
kvm_pfn_t identity_map_pfn;
u32 tmp;
if (!enable_ept)
return 0;
/* Protect kvm->arch.ept_identity_pagetable_done. */
mutex_lock(&kvm->slots_lock);
if (likely(kvm->arch.ept_identity_pagetable_done))
goto out2;
identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
r = alloc_identity_pagetable(kvm);
if (r < 0)
goto out2;
idx = srcu_read_lock(&kvm->srcu);
r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
if (r < 0)
goto out;
/* Set up identity-mapping pagetable for EPT in real mode */
for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
_PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
r = kvm_write_guest_page(kvm, identity_map_pfn,
&tmp, i * sizeof(tmp), sizeof(tmp));
if (r < 0)
goto out;
}
kvm->arch.ept_identity_pagetable_done = true;
out:
srcu_read_unlock(&kvm->srcu, idx);
out2:
mutex_unlock(&kvm->slots_lock);
return r;
}
static void seg_setup(int seg)
{
const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
unsigned int ar;
vmcs_write16(sf->selector, 0);
vmcs_writel(sf->base, 0);
vmcs_write32(sf->limit, 0xffff);
ar = 0x93;
if (seg == VCPU_SREG_CS)
ar |= 0x08; /* code segment */
vmcs_write32(sf->ar_bytes, ar);
}
static int alloc_apic_access_page(struct kvm *kvm)
{
struct page *page;
int r = 0;
mutex_lock(&kvm->slots_lock);
if (kvm->arch.apic_access_page_done)
goto out;
r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
if (r)
goto out;
page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
if (is_error_page(page)) {
r = -EFAULT;
goto out;
}
/*
* Do not pin the page in memory, so that memory hot-unplug
* is able to migrate it.
*/
put_page(page);
kvm->arch.apic_access_page_done = true;
out:
mutex_unlock(&kvm->slots_lock);
return r;
}
static int alloc_identity_pagetable(struct kvm *kvm)
{
/* Called with kvm->slots_lock held. */
int r = 0;
BUG_ON(kvm->arch.ept_identity_pagetable_done);
r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
kvm->arch.ept_identity_map_addr, PAGE_SIZE);
return r;
}
static int allocate_vpid(void)
{
int vpid;
if (!enable_vpid)
return 0;
spin_lock(&vmx_vpid_lock);
vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
if (vpid < VMX_NR_VPIDS)
__set_bit(vpid, vmx_vpid_bitmap);
else
vpid = 0;
spin_unlock(&vmx_vpid_lock);
return vpid;
}
static void free_vpid(int vpid)
{
if (!enable_vpid || vpid == 0)
return;
spin_lock(&vmx_vpid_lock);
__clear_bit(vpid, vmx_vpid_bitmap);
spin_unlock(&vmx_vpid_lock);
}
#define MSR_TYPE_R 1
#define MSR_TYPE_W 2
static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
u32 msr, int type)
{
int f = sizeof(unsigned long);
if (!cpu_has_vmx_msr_bitmap())
return;
/*
* See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
* have the write-low and read-high bitmap offsets the wrong way round.
* We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
*/
if (msr <= 0x1fff) {
if (type & MSR_TYPE_R)
/* read-low */
__clear_bit(msr, msr_bitmap + 0x000 / f);
if (type & MSR_TYPE_W)
/* write-low */
__clear_bit(msr, msr_bitmap + 0x800 / f);
} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
msr &= 0x1fff;
if (type & MSR_TYPE_R)
/* read-high */
__clear_bit(msr, msr_bitmap + 0x400 / f);
if (type & MSR_TYPE_W)
/* write-high */
__clear_bit(msr, msr_bitmap + 0xc00 / f);
}
}
/*
* If a msr is allowed by L0, we should check whether it is allowed by L1.
* The corresponding bit will be cleared unless both of L0 and L1 allow it.
*/
static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
unsigned long *msr_bitmap_nested,
u32 msr, int type)
{
int f = sizeof(unsigned long);
if (!cpu_has_vmx_msr_bitmap()) {
WARN_ON(1);
return;
}
/*
* See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
* have the write-low and read-high bitmap offsets the wrong way round.
* We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
*/
if (msr <= 0x1fff) {
if (type & MSR_TYPE_R &&
!test_bit(msr, msr_bitmap_l1 + 0x000 / f))
/* read-low */
__clear_bit(msr, msr_bitmap_nested + 0x000 / f);
if (type & MSR_TYPE_W &&
!test_bit(msr, msr_bitmap_l1 + 0x800 / f))
/* write-low */
__clear_bit(msr, msr_bitmap_nested + 0x800 / f);
} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
msr &= 0x1fff;
if (type & MSR_TYPE_R &&
!test_bit(msr, msr_bitmap_l1 + 0x400 / f))
/* read-high */
__clear_bit(msr, msr_bitmap_nested + 0x400 / f);
if (type & MSR_TYPE_W &&
!test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
/* write-high */
__clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
}
}
static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
{
if (!longmode_only)
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
msr, MSR_TYPE_R | MSR_TYPE_W);
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
msr, MSR_TYPE_R | MSR_TYPE_W);
}
static void vmx_disable_intercept_msr_x2apic(u32 msr, int type, bool apicv_active)
{
if (apicv_active) {
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic_apicv,
msr, type);
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic_apicv,
msr, type);
} else {
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
msr, type);
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
msr, type);
}
}
static bool vmx_get_enable_apicv(void)
{
return enable_apicv;
}
static int vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int max_irr;
void *vapic_page;
u16 status;
if (vmx->nested.pi_desc &&
vmx->nested.pi_pending) {
vmx->nested.pi_pending = false;
if (!pi_test_and_clear_on(vmx->nested.pi_desc))
return 0;
max_irr = find_last_bit(
(unsigned long *)vmx->nested.pi_desc->pir, 256);
if (max_irr == 256)
return 0;
vapic_page = kmap(vmx->nested.virtual_apic_page);
if (!vapic_page) {
WARN_ON(1);
return -ENOMEM;
}
__kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
kunmap(vmx->nested.virtual_apic_page);
status = vmcs_read16(GUEST_INTR_STATUS);
if ((u8)max_irr > ((u8)status & 0xff)) {
status &= ~0xff;
status |= (u8)max_irr;
vmcs_write16(GUEST_INTR_STATUS, status);
}
}
return 0;
}
static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu)
{
#ifdef CONFIG_SMP
if (vcpu->mode == IN_GUEST_MODE) {
struct vcpu_vmx *vmx = to_vmx(vcpu);
/*
* Currently, we don't support urgent interrupt,
* all interrupts are recognized as non-urgent
* interrupt, so we cannot post interrupts when
* 'SN' is set.
*
* If the vcpu is in guest mode, it means it is
* running instead of being scheduled out and
* waiting in the run queue, and that's the only
* case when 'SN' is set currently, warning if
* 'SN' is set.
*/
WARN_ON_ONCE(pi_test_sn(&vmx->pi_desc));
apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
POSTED_INTR_VECTOR);
return true;
}
#endif
return false;
}
static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
int vector)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (is_guest_mode(vcpu) &&
vector == vmx->nested.posted_intr_nv) {
/* the PIR and ON have been set by L1. */
kvm_vcpu_trigger_posted_interrupt(vcpu);
/*
* If a posted intr is not recognized by hardware,
* we will accomplish it in the next vmentry.
*/
vmx->nested.pi_pending = true;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
return -1;
}
/*
* Send interrupt to vcpu via posted interrupt way.
* 1. If target vcpu is running(non-root mode), send posted interrupt
* notification to vcpu and hardware will sync PIR to vIRR atomically.
* 2. If target vcpu isn't running(root mode), kick it to pick up the
* interrupt from PIR in next vmentry.
*/
static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int r;
r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
if (!r)
return;
if (pi_test_and_set_pir(vector, &vmx->pi_desc))
return;
r = pi_test_and_set_on(&vmx->pi_desc);
kvm_make_request(KVM_REQ_EVENT, vcpu);
if (r || !kvm_vcpu_trigger_posted_interrupt(vcpu))
kvm_vcpu_kick(vcpu);
}
static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!pi_test_on(&vmx->pi_desc))
return;
pi_clear_on(&vmx->pi_desc);
/*
* IOMMU can write to PIR.ON, so the barrier matters even on UP.
* But on x86 this is just a compiler barrier anyway.
*/
smp_mb__after_atomic();
kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
}
/*
* Set up the vmcs's constant host-state fields, i.e., host-state fields that
* will not change in the lifetime of the guest.
* Note that host-state that does change is set elsewhere. E.g., host-state
* that is set differently for each CPU is set in vmx_vcpu_load(), not here.
*/
static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
{
u32 low32, high32;
unsigned long tmpl;
struct desc_ptr dt;
unsigned long cr0, cr4;
cr0 = read_cr0();
WARN_ON(cr0 & X86_CR0_TS);
vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
/* Save the most likely value for this task's CR4 in the VMCS. */
cr4 = cr4_read_shadow();
vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
vmx->host_state.vmcs_host_cr4 = cr4;
vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
#ifdef CONFIG_X86_64
/*
* Load null selectors, so we can avoid reloading them in
* __vmx_load_host_state(), in case userspace uses the null selectors
* too (the expected case).
*/
vmcs_write16(HOST_DS_SELECTOR, 0);
vmcs_write16(HOST_ES_SELECTOR, 0);
#else
vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
#endif
vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
native_store_idt(&dt);
vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
vmx->host_idt_base = dt.address;
vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
rdmsr(MSR_IA32_CR_PAT, low32, high32);
vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
}
}
static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
{
vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
if (enable_ept)
vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
if (is_guest_mode(&vmx->vcpu))
vmx->vcpu.arch.cr4_guest_owned_bits &=
~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
}
static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
{
u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
if (!kvm_vcpu_apicv_active(&vmx->vcpu))
pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
/* Enable the preemption timer dynamically */
pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
return pin_based_exec_ctrl;
}
static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
if (cpu_has_secondary_exec_ctrls()) {
if (kvm_vcpu_apicv_active(vcpu))
vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
else
vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
}
if (cpu_has_vmx_msr_bitmap())
vmx_set_msr_bitmap(vcpu);
}
static u32 vmx_exec_control(struct vcpu_vmx *vmx)
{
u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
exec_control &= ~CPU_BASED_MOV_DR_EXITING;
if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
exec_control &= ~CPU_BASED_TPR_SHADOW;
#ifdef CONFIG_X86_64
exec_control |= CPU_BASED_CR8_STORE_EXITING |
CPU_BASED_CR8_LOAD_EXITING;
#endif
}
if (!enable_ept)
exec_control |= CPU_BASED_CR3_STORE_EXITING |
CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_INVLPG_EXITING;
return exec_control;
}
static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
{
u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
if (!cpu_need_virtualize_apic_accesses(&vmx->vcpu))
exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
if (vmx->vpid == 0)
exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
if (!enable_ept) {
exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
enable_unrestricted_guest = 0;
/* Enable INVPCID for non-ept guests may cause performance regression. */
exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
}
if (!enable_unrestricted_guest)
exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
if (!ple_gap)
exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
if (!kvm_vcpu_apicv_active(&vmx->vcpu))
exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
/* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
(handle_vmptrld).
We can NOT enable shadow_vmcs here because we don't have yet
a current VMCS12
*/
exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
if (!enable_pml)
exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
return exec_control;
}
static void ept_set_mmio_spte_mask(void)
{
/*
* EPT Misconfigurations can be generated if the value of bits 2:0
* of an EPT paging-structure entry is 110b (write/execute).
* Also, magic bits (0x3ull << 62) is set to quickly identify mmio
* spte.
*/
kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull);
}
#define VMX_XSS_EXIT_BITMAP 0
/*
* Sets up the vmcs for emulated real mode.
*/
static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
{
#ifdef CONFIG_X86_64
unsigned long a;
#endif
int i;
/* I/O */
vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
if (enable_shadow_vmcs) {
vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
}
if (cpu_has_vmx_msr_bitmap())
vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
/* Control */
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
vmx->hv_deadline_tsc = -1;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
if (cpu_has_secondary_exec_ctrls()) {
vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
vmx_secondary_exec_control(vmx));
}
if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
vmcs_write64(EOI_EXIT_BITMAP0, 0);
vmcs_write64(EOI_EXIT_BITMAP1, 0);
vmcs_write64(EOI_EXIT_BITMAP2, 0);
vmcs_write64(EOI_EXIT_BITMAP3, 0);
vmcs_write16(GUEST_INTR_STATUS, 0);
vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
}
if (ple_gap) {
vmcs_write32(PLE_GAP, ple_gap);
vmx->ple_window = ple_window;
vmx->ple_window_dirty = true;
}
vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
vmx_set_constant_host_state(vmx);
#ifdef CONFIG_X86_64
rdmsrl(MSR_FS_BASE, a);
vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
rdmsrl(MSR_GS_BASE, a);
vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
#else
vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
#endif
vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
u32 index = vmx_msr_index[i];
u32 data_low, data_high;
int j = vmx->nmsrs;
if (rdmsr_safe(index, &data_low, &data_high) < 0)
continue;
if (wrmsr_safe(index, data_low, data_high) < 0)
continue;
vmx->guest_msrs[j].index = i;
vmx->guest_msrs[j].data = 0;
vmx->guest_msrs[j].mask = -1ull;
++vmx->nmsrs;
}
vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
/* 22.2.1, 20.8.1 */
vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
set_cr4_guest_host_mask(vmx);
if (vmx_xsaves_supported())
vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
if (enable_pml) {
ASSERT(vmx->pml_pg);
vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
}
return 0;
}
static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct msr_data apic_base_msr;
u64 cr0;
vmx->rmode.vm86_active = 0;
vmx->soft_vnmi_blocked = 0;
vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
kvm_set_cr8(vcpu, 0);
if (!init_event) {
apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
MSR_IA32_APICBASE_ENABLE;
if (kvm_vcpu_is_reset_bsp(vcpu))
apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
apic_base_msr.host_initiated = true;
kvm_set_apic_base(vcpu, &apic_base_msr);
}
vmx_segment_cache_clear(vmx);
seg_setup(VCPU_SREG_CS);
vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
seg_setup(VCPU_SREG_DS);
seg_setup(VCPU_SREG_ES);
seg_setup(VCPU_SREG_FS);
seg_setup(VCPU_SREG_GS);
seg_setup(VCPU_SREG_SS);
vmcs_write16(GUEST_TR_SELECTOR, 0);
vmcs_writel(GUEST_TR_BASE, 0);
vmcs_write32(GUEST_TR_LIMIT, 0xffff);
vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
vmcs_write16(GUEST_LDTR_SELECTOR, 0);
vmcs_writel(GUEST_LDTR_BASE, 0);
vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
if (!init_event) {
vmcs_write32(GUEST_SYSENTER_CS, 0);
vmcs_writel(GUEST_SYSENTER_ESP, 0);
vmcs_writel(GUEST_SYSENTER_EIP, 0);
vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
}
vmcs_writel(GUEST_RFLAGS, 0x02);
kvm_rip_write(vcpu, 0xfff0);
vmcs_writel(GUEST_GDTR_BASE, 0);
vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
vmcs_writel(GUEST_IDTR_BASE, 0);
vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
setup_msrs(vmx);
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
if (cpu_has_vmx_tpr_shadow() && !init_event) {
vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
if (cpu_need_tpr_shadow(vcpu))
vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
__pa(vcpu->arch.apic->regs));
vmcs_write32(TPR_THRESHOLD, 0);
}
kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
if (kvm_vcpu_apicv_active(vcpu))
memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
if (vmx->vpid != 0)
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
vmx->vcpu.arch.cr0 = cr0;
vmx_set_cr0(vcpu, cr0); /* enter rmode */
vmx_set_cr4(vcpu, 0);
vmx_set_efer(vcpu, 0);
vmx_fpu_activate(vcpu);
update_exception_bitmap(vcpu);
vpid_sync_context(vmx->vpid);
}
/*
* In nested virtualization, check if L1 asked to exit on external interrupts.
* For most existing hypervisors, this will always return true.
*/
static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
{
return get_vmcs12(vcpu)->pin_based_vm_exec_control &
PIN_BASED_EXT_INTR_MASK;
}
/*
* In nested virtualization, check if L1 has set
* VM_EXIT_ACK_INTR_ON_EXIT
*/
static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
{
return get_vmcs12(vcpu)->vm_exit_controls &
VM_EXIT_ACK_INTR_ON_EXIT;
}
static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
{
return get_vmcs12(vcpu)->pin_based_vm_exec_control &
PIN_BASED_NMI_EXITING;
}
static void enable_irq_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
}
static void enable_nmi_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
if (!cpu_has_virtual_nmis() ||
vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
enable_irq_window(vcpu);
return;
}
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
}
static void vmx_inject_irq(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
uint32_t intr;
int irq = vcpu->arch.interrupt.nr;
trace_kvm_inj_virq(irq);
++vcpu->stat.irq_injections;
if (vmx->rmode.vm86_active) {
int inc_eip = 0;
if (vcpu->arch.interrupt.soft)
inc_eip = vcpu->arch.event_exit_inst_len;
if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
intr = irq | INTR_INFO_VALID_MASK;
if (vcpu->arch.interrupt.soft) {
intr |= INTR_TYPE_SOFT_INTR;
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmx->vcpu.arch.event_exit_inst_len);
} else
intr |= INTR_TYPE_EXT_INTR;
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
}
static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!is_guest_mode(vcpu)) {
if (!cpu_has_virtual_nmis()) {
/*
* Tracking the NMI-blocked state in software is built upon
* finding the next open IRQ window. This, in turn, depends on
* well-behaving guests: They have to keep IRQs disabled at
* least as long as the NMI handler runs. Otherwise we may
* cause NMI nesting, maybe breaking the guest. But as this is
* highly unlikely, we can live with the residual risk.
*/
vmx->soft_vnmi_blocked = 1;
vmx->vnmi_blocked_time = 0;
}
++vcpu->stat.nmi_injections;
vmx->nmi_known_unmasked = false;
}
if (vmx->rmode.vm86_active) {
if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
}
static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
{
if (!cpu_has_virtual_nmis())
return to_vmx(vcpu)->soft_vnmi_blocked;
if (to_vmx(vcpu)->nmi_known_unmasked)
return false;
return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
}
static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!cpu_has_virtual_nmis()) {
if (vmx->soft_vnmi_blocked != masked) {
vmx->soft_vnmi_blocked = masked;
vmx->vnmi_blocked_time = 0;
}
} else {
vmx->nmi_known_unmasked = !masked;
if (masked)
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
else
vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
}
}
static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
{
if (to_vmx(vcpu)->nested.nested_run_pending)
return 0;
if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
return 0;
return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
(GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
| GUEST_INTR_STATE_NMI));
}
static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
{
return (!to_vmx(vcpu)->nested.nested_run_pending &&
vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
}
static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
{
int ret;
ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
PAGE_SIZE * 3);
if (ret)
return ret;
kvm->arch.tss_addr = addr;
return init_rmode_tss(kvm);
}
static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
{
switch (vec) {
case BP_VECTOR:
/*
* Update instruction length as we may reinject the exception
* from user space while in guest debugging mode.
*/
to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
return false;
/* fall through */
case DB_VECTOR:
if (vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
return false;
/* fall through */
case DE_VECTOR:
case OF_VECTOR:
case BR_VECTOR:
case UD_VECTOR:
case DF_VECTOR:
case SS_VECTOR:
case GP_VECTOR:
case MF_VECTOR:
return true;
break;
}
return false;
}
static int handle_rmode_exception(struct kvm_vcpu *vcpu,
int vec, u32 err_code)
{
/*
* Instruction with address size override prefix opcode 0x67
* Cause the #SS fault with 0 error code in VM86 mode.
*/
if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
if (vcpu->arch.halt_request) {
vcpu->arch.halt_request = 0;
return kvm_vcpu_halt(vcpu);
}
return 1;
}
return 0;
}
/*
* Forward all other exceptions that are valid in real mode.
* FIXME: Breaks guest debugging in real mode, needs to be fixed with
* the required debugging infrastructure rework.
*/
kvm_queue_exception(vcpu, vec);
return 1;
}
/*
* Trigger machine check on the host. We assume all the MSRs are already set up
* by the CPU and that we still run on the same CPU as the MCE occurred on.
* We pass a fake environment to the machine check handler because we want
* the guest to be always treated like user space, no matter what context
* it used internally.
*/
static void kvm_machine_check(void)
{
#if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
struct pt_regs regs = {
.cs = 3, /* Fake ring 3 no matter what the guest ran on */
.flags = X86_EFLAGS_IF,
};
do_machine_check(®s, 0);
#endif
}
static int handle_machine_check(struct kvm_vcpu *vcpu)
{
/* already handled by vcpu_run */
return 1;
}
static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if (is_nmi(intr_info))
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case AC_VECTOR:
kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
return 1;
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
static int handle_external_interrupt(struct kvm_vcpu *vcpu)
{
++vcpu->stat.irq_exits;
return 1;
}
static int handle_triple_fault(struct kvm_vcpu *vcpu)
{
vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
return 0;
}
static int handle_io(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
int size, in, string, ret;
unsigned port;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
string = (exit_qualification & 16) != 0;
in = (exit_qualification & 8) != 0;
++vcpu->stat.io_exits;
if (string || in)
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
port = exit_qualification >> 16;
size = (exit_qualification & 7) + 1;
ret = kvm_skip_emulated_instruction(vcpu);
/*
* TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
* KVM_EXIT_DEBUG here.
*/
return kvm_fast_pio_out(vcpu, size, port) && ret;
}
static void
vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
{
/*
* Patch in the VMCALL instruction:
*/
hypercall[0] = 0x0f;
hypercall[1] = 0x01;
hypercall[2] = 0xc1;
}
/* called to set cr0 as appropriate for a mov-to-cr0 exit. */
static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
{
if (is_guest_mode(vcpu)) {
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
unsigned long orig_val = val;
/*
* We get here when L2 changed cr0 in a way that did not change
* any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
* but did change L0 shadowed bits. So we first calculate the
* effective cr0 value that L1 would like to write into the
* hardware. It consists of the L2-owned bits from the new
* value combined with the L1-owned bits from L1's guest_cr0.
*/
val = (val & ~vmcs12->cr0_guest_host_mask) |
(vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
if (!nested_guest_cr0_valid(vcpu, val))
return 1;
if (kvm_set_cr0(vcpu, val))
return 1;
vmcs_writel(CR0_READ_SHADOW, orig_val);
return 0;
} else {
if (to_vmx(vcpu)->nested.vmxon &&
!nested_host_cr0_valid(vcpu, val))
return 1;
return kvm_set_cr0(vcpu, val);
}
}
static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
{
if (is_guest_mode(vcpu)) {
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
unsigned long orig_val = val;
/* analogously to handle_set_cr0 */
val = (val & ~vmcs12->cr4_guest_host_mask) |
(vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
if (kvm_set_cr4(vcpu, val))
return 1;
vmcs_writel(CR4_READ_SHADOW, orig_val);
return 0;
} else
return kvm_set_cr4(vcpu, val);
}
/* called to set cr0 as appropriate for clts instruction exit. */
static void handle_clts(struct kvm_vcpu *vcpu)
{
if (is_guest_mode(vcpu)) {
/*
* We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
* but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
* just pretend it's off (also in arch.cr0 for fpu_activate).
*/
vmcs_writel(CR0_READ_SHADOW,
vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
vcpu->arch.cr0 &= ~X86_CR0_TS;
} else
vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
}
static int handle_cr(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification, val;
int cr;
int reg;
int err;
int ret;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
cr = exit_qualification & 15;
reg = (exit_qualification >> 8) & 15;
switch ((exit_qualification >> 4) & 3) {
case 0: /* mov to cr */
val = kvm_register_readl(vcpu, reg);
trace_kvm_cr_write(cr, val);
switch (cr) {
case 0:
err = handle_set_cr0(vcpu, val);
return kvm_complete_insn_gp(vcpu, err);
case 3:
err = kvm_set_cr3(vcpu, val);
return kvm_complete_insn_gp(vcpu, err);
case 4:
err = handle_set_cr4(vcpu, val);
return kvm_complete_insn_gp(vcpu, err);
case 8: {
u8 cr8_prev = kvm_get_cr8(vcpu);
u8 cr8 = (u8)val;
err = kvm_set_cr8(vcpu, cr8);
ret = kvm_complete_insn_gp(vcpu, err);
if (lapic_in_kernel(vcpu))
return ret;
if (cr8_prev <= cr8)
return ret;
/*
* TODO: we might be squashing a
* KVM_GUESTDBG_SINGLESTEP-triggered
* KVM_EXIT_DEBUG here.
*/
vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
return 0;
}
}
break;
case 2: /* clts */
handle_clts(vcpu);
trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
vmx_fpu_activate(vcpu);
return kvm_skip_emulated_instruction(vcpu);
case 1: /*mov from cr*/
switch (cr) {
case 3:
val = kvm_read_cr3(vcpu);
kvm_register_write(vcpu, reg, val);
trace_kvm_cr_read(cr, val);
return kvm_skip_emulated_instruction(vcpu);
case 8:
val = kvm_get_cr8(vcpu);
kvm_register_write(vcpu, reg, val);
trace_kvm_cr_read(cr, val);
return kvm_skip_emulated_instruction(vcpu);
}
break;
case 3: /* lmsw */
val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
kvm_lmsw(vcpu, val);
return kvm_skip_emulated_instruction(vcpu);
default:
break;
}
vcpu->run->exit_reason = 0;
vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
(int)(exit_qualification >> 4) & 3, cr);
return 0;
}
static int handle_dr(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
int dr, dr7, reg;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
/* First, if DR does not exist, trigger UD */
if (!kvm_require_dr(vcpu, dr))
return 1;
/* Do not handle if the CPL > 0, will trigger GP on re-entry */
if (!kvm_require_cpl(vcpu, 0))
return 1;
dr7 = vmcs_readl(GUEST_DR7);
if (dr7 & DR7_GD) {
/*
* As the vm-exit takes precedence over the debug trap, we
* need to emulate the latter, either for the host or the
* guest debugging itself.
*/
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
vcpu->run->debug.arch.dr7 = dr7;
vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
vcpu->run->debug.arch.exception = DB_VECTOR;
vcpu->run->exit_reason = KVM_EXIT_DEBUG;
return 0;
} else {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
}
if (vcpu->guest_debug == 0) {
vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
CPU_BASED_MOV_DR_EXITING);
/*
* No more DR vmexits; force a reload of the debug registers
* and reenter on this instruction. The next vmexit will
* retrieve the full state of the debug registers.
*/
vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
return 1;
}
reg = DEBUG_REG_ACCESS_REG(exit_qualification);
if (exit_qualification & TYPE_MOV_FROM_DR) {
unsigned long val;
if (kvm_get_dr(vcpu, dr, &val))
return 1;
kvm_register_write(vcpu, reg, val);
} else
if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
return 1;
return kvm_skip_emulated_instruction(vcpu);
}
static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
{
return vcpu->arch.dr6;
}
static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
{
}
static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
{
get_debugreg(vcpu->arch.db[0], 0);
get_debugreg(vcpu->arch.db[1], 1);
get_debugreg(vcpu->arch.db[2], 2);
get_debugreg(vcpu->arch.db[3], 3);
get_debugreg(vcpu->arch.dr6, 6);
vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
}
static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
{
vmcs_writel(GUEST_DR7, val);
}
static int handle_cpuid(struct kvm_vcpu *vcpu)
{
return kvm_emulate_cpuid(vcpu);
}
static int handle_rdmsr(struct kvm_vcpu *vcpu)
{
u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
struct msr_data msr_info;
msr_info.index = ecx;
msr_info.host_initiated = false;
if (vmx_get_msr(vcpu, &msr_info)) {
trace_kvm_msr_read_ex(ecx);
kvm_inject_gp(vcpu, 0);
return 1;
}
trace_kvm_msr_read(ecx, msr_info.data);
/* FIXME: handling of bits 32:63 of rax, rdx */
vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_wrmsr(struct kvm_vcpu *vcpu)
{
struct msr_data msr;
u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
msr.data = data;
msr.index = ecx;
msr.host_initiated = false;
if (kvm_set_msr(vcpu, &msr) != 0) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(vcpu, 0);
return 1;
}
trace_kvm_msr_write(ecx, data);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
{
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 1;
}
static int handle_interrupt_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
/* clear pending irq */
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
kvm_make_request(KVM_REQ_EVENT, vcpu);
++vcpu->stat.irq_window_exits;
return 1;
}
static int handle_halt(struct kvm_vcpu *vcpu)
{
return kvm_emulate_halt(vcpu);
}
static int handle_vmcall(struct kvm_vcpu *vcpu)
{
return kvm_emulate_hypercall(vcpu);
}
static int handle_invd(struct kvm_vcpu *vcpu)
{
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
}
static int handle_invlpg(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
kvm_mmu_invlpg(vcpu, exit_qualification);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_rdpmc(struct kvm_vcpu *vcpu)
{
int err;
err = kvm_rdpmc(vcpu);
return kvm_complete_insn_gp(vcpu, err);
}
static int handle_wbinvd(struct kvm_vcpu *vcpu)
{
return kvm_emulate_wbinvd(vcpu);
}
static int handle_xsetbv(struct kvm_vcpu *vcpu)
{
u64 new_bv = kvm_read_edx_eax(vcpu);
u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
if (kvm_set_xcr(vcpu, index, new_bv) == 0)
return kvm_skip_emulated_instruction(vcpu);
return 1;
}
static int handle_xsaves(struct kvm_vcpu *vcpu)
{
kvm_skip_emulated_instruction(vcpu);
WARN(1, "this should never happen\n");
return 1;
}
static int handle_xrstors(struct kvm_vcpu *vcpu)
{
kvm_skip_emulated_instruction(vcpu);
WARN(1, "this should never happen\n");
return 1;
}
static int handle_apic_access(struct kvm_vcpu *vcpu)
{
if (likely(fasteoi)) {
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
int access_type, offset;
access_type = exit_qualification & APIC_ACCESS_TYPE;
offset = exit_qualification & APIC_ACCESS_OFFSET;
/*
* Sane guest uses MOV to write EOI, with written value
* not cared. So make a short-circuit here by avoiding
* heavy instruction emulation.
*/
if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
(offset == APIC_EOI)) {
kvm_lapic_set_eoi(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
}
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
}
static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
int vector = exit_qualification & 0xff;
/* EOI-induced VM exit is trap-like and thus no need to adjust IP */
kvm_apic_set_eoi_accelerated(vcpu, vector);
return 1;
}
static int handle_apic_write(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 offset = exit_qualification & 0xfff;
/* APIC-write VM exit is trap-like and thus no need to adjust IP */
kvm_apic_write_nodecode(vcpu, offset);
return 1;
}
static int handle_task_switch(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long exit_qualification;
bool has_error_code = false;
u32 error_code = 0;
u16 tss_selector;
int reason, type, idt_v, idt_index;
idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
reason = (u32)exit_qualification >> 30;
if (reason == TASK_SWITCH_GATE && idt_v) {
switch (type) {
case INTR_TYPE_NMI_INTR:
vcpu->arch.nmi_injected = false;
vmx_set_nmi_mask(vcpu, true);
break;
case INTR_TYPE_EXT_INTR:
case INTR_TYPE_SOFT_INTR:
kvm_clear_interrupt_queue(vcpu);
break;
case INTR_TYPE_HARD_EXCEPTION:
if (vmx->idt_vectoring_info &
VECTORING_INFO_DELIVER_CODE_MASK) {
has_error_code = true;
error_code =
vmcs_read32(IDT_VECTORING_ERROR_CODE);
}
/* fall through */
case INTR_TYPE_SOFT_EXCEPTION:
kvm_clear_exception_queue(vcpu);
break;
default:
break;
}
}
tss_selector = exit_qualification;
if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
type != INTR_TYPE_EXT_INTR &&
type != INTR_TYPE_NMI_INTR))
skip_emulated_instruction(vcpu);
if (kvm_task_switch(vcpu, tss_selector,
type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
has_error_code, error_code) == EMULATE_FAIL) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
return 0;
}
/*
* TODO: What about debug traps on tss switch?
* Are we supposed to inject them and update dr6?
*/
return 1;
}
static int handle_ept_violation(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
gpa_t gpa;
u32 error_code;
int gla_validity;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
gla_validity = (exit_qualification >> 7) & 0x3;
if (gla_validity == 0x2) {
printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
(long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
vmcs_readl(GUEST_LINEAR_ADDRESS));
printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
(long unsigned int)exit_qualification);
vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
return 0;
}
/*
* EPT violation happened while executing iret from NMI,
* "blocked by NMI" bit has to be set before next VM entry.
* There are errata that may cause this bit to not be set:
* AAK134, BY25.
*/
if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
cpu_has_virtual_nmis() &&
(exit_qualification & INTR_INFO_UNBLOCK_NMI))
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
trace_kvm_page_fault(gpa, exit_qualification);
/* it is a read fault? */
error_code = (exit_qualification << 2) & PFERR_USER_MASK;
/* it is a write fault? */
error_code |= exit_qualification & PFERR_WRITE_MASK;
/* It is a fetch fault? */
error_code |= (exit_qualification << 2) & PFERR_FETCH_MASK;
/* ept page table is present? */
error_code |= (exit_qualification & 0x38) != 0;
vcpu->arch.exit_qualification = exit_qualification;
return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
}
static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
{
int ret;
gpa_t gpa;
gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
if (!kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
trace_kvm_fast_mmio(gpa);
return kvm_skip_emulated_instruction(vcpu);
}
ret = handle_mmio_page_fault(vcpu, gpa, true);
if (likely(ret == RET_MMIO_PF_EMULATE))
return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
EMULATE_DONE;
if (unlikely(ret == RET_MMIO_PF_INVALID))
return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0);
if (unlikely(ret == RET_MMIO_PF_RETRY))
return 1;
/* It is the real ept misconfig */
WARN_ON(1);
vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
return 0;
}
static int handle_nmi_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
/* clear pending NMI */
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
++vcpu->stat.nmi_window_exits;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 1;
}
static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
enum emulation_result err = EMULATE_DONE;
int ret = 1;
u32 cpu_exec_ctrl;
bool intr_window_requested;
unsigned count = 130;
cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
while (vmx->emulation_required && count-- != 0) {
if (intr_window_requested && vmx_interrupt_allowed(vcpu))
return handle_interrupt_window(&vmx->vcpu);
if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
return 1;
err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE);
if (err == EMULATE_USER_EXIT) {
++vcpu->stat.mmio_exits;
ret = 0;
goto out;
}
if (err != EMULATE_DONE) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
return 0;
}
if (vcpu->arch.halt_request) {
vcpu->arch.halt_request = 0;
ret = kvm_vcpu_halt(vcpu);
goto out;
}
if (signal_pending(current))
goto out;
if (need_resched())
schedule();
}
out:
return ret;
}
static int __grow_ple_window(int val)
{
if (ple_window_grow < 1)
return ple_window;
val = min(val, ple_window_actual_max);
if (ple_window_grow < ple_window)
val *= ple_window_grow;
else
val += ple_window_grow;
return val;
}
static int __shrink_ple_window(int val, int modifier, int minimum)
{
if (modifier < 1)
return ple_window;
if (modifier < ple_window)
val /= modifier;
else
val -= modifier;
return max(val, minimum);
}
static void grow_ple_window(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int old = vmx->ple_window;
vmx->ple_window = __grow_ple_window(old);
if (vmx->ple_window != old)
vmx->ple_window_dirty = true;
trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
}
static void shrink_ple_window(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int old = vmx->ple_window;
vmx->ple_window = __shrink_ple_window(old,
ple_window_shrink, ple_window);
if (vmx->ple_window != old)
vmx->ple_window_dirty = true;
trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
}
/*
* ple_window_actual_max is computed to be one grow_ple_window() below
* ple_window_max. (See __grow_ple_window for the reason.)
* This prevents overflows, because ple_window_max is int.
* ple_window_max effectively rounded down to a multiple of ple_window_grow in
* this process.
* ple_window_max is also prevented from setting vmx->ple_window < ple_window.
*/
static void update_ple_window_actual_max(void)
{
ple_window_actual_max =
__shrink_ple_window(max(ple_window_max, ple_window),
ple_window_grow, INT_MIN);
}
/*
* Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
*/
static void wakeup_handler(void)
{
struct kvm_vcpu *vcpu;
int cpu = smp_processor_id();
spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
blocked_vcpu_list) {
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
if (pi_test_on(pi_desc) == 1)
kvm_vcpu_kick(vcpu);
}
spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
}
static __init int hardware_setup(void)
{
int r = -ENOMEM, i, msr;
rdmsrl_safe(MSR_EFER, &host_efer);
for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
kvm_define_shared_msr(i, vmx_msr_index[i]);
for (i = 0; i < VMX_BITMAP_NR; i++) {
vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_bitmap[i])
goto out;
}
vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
/*
* Allow direct access to the PC debug port (it is often used for I/O
* delays, but the vmexits simply slow things down).
*/
memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
clear_bit(0x80, vmx_io_bitmap_a);
memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
if (setup_vmcs_config(&vmcs_config) < 0) {
r = -EIO;
goto out;
}
if (boot_cpu_has(X86_FEATURE_NX))
kvm_enable_efer_bits(EFER_NX);
if (!cpu_has_vmx_vpid())
enable_vpid = 0;
if (!cpu_has_vmx_shadow_vmcs())
enable_shadow_vmcs = 0;
if (enable_shadow_vmcs)
init_vmcs_shadow_fields();
if (!cpu_has_vmx_ept() ||
!cpu_has_vmx_ept_4levels()) {
enable_ept = 0;
enable_unrestricted_guest = 0;
enable_ept_ad_bits = 0;
}
if (!cpu_has_vmx_ept_ad_bits())
enable_ept_ad_bits = 0;
if (!cpu_has_vmx_unrestricted_guest())
enable_unrestricted_guest = 0;
if (!cpu_has_vmx_flexpriority())
flexpriority_enabled = 0;
/*
* set_apic_access_page_addr() is used to reload apic access
* page upon invalidation. No need to do anything if not
* using the APIC_ACCESS_ADDR VMCS field.
*/
if (!flexpriority_enabled)
kvm_x86_ops->set_apic_access_page_addr = NULL;
if (!cpu_has_vmx_tpr_shadow())
kvm_x86_ops->update_cr8_intercept = NULL;
if (enable_ept && !cpu_has_vmx_ept_2m_page())
kvm_disable_largepages();
if (!cpu_has_vmx_ple())
ple_gap = 0;
if (!cpu_has_vmx_apicv())
enable_apicv = 0;
if (cpu_has_vmx_tsc_scaling()) {
kvm_has_tsc_control = true;
kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
kvm_tsc_scaling_ratio_frac_bits = 48;
}
vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
vmx_disable_intercept_for_msr(MSR_IA32_BNDCFGS, true);
memcpy(vmx_msr_bitmap_legacy_x2apic_apicv,
vmx_msr_bitmap_legacy, PAGE_SIZE);
memcpy(vmx_msr_bitmap_longmode_x2apic_apicv,
vmx_msr_bitmap_longmode, PAGE_SIZE);
memcpy(vmx_msr_bitmap_legacy_x2apic,
vmx_msr_bitmap_legacy, PAGE_SIZE);
memcpy(vmx_msr_bitmap_longmode_x2apic,
vmx_msr_bitmap_longmode, PAGE_SIZE);
set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
for (msr = 0x800; msr <= 0x8ff; msr++) {
if (msr == 0x839 /* TMCCT */)
continue;
vmx_disable_intercept_msr_x2apic(msr, MSR_TYPE_R, true);
}
/*
* TPR reads and writes can be virtualized even if virtual interrupt
* delivery is not in use.
*/
vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_W, true);
vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_R | MSR_TYPE_W, false);
/* EOI */
vmx_disable_intercept_msr_x2apic(0x80b, MSR_TYPE_W, true);
/* SELF-IPI */
vmx_disable_intercept_msr_x2apic(0x83f, MSR_TYPE_W, true);
if (enable_ept) {
kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
(enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
(enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
0ull, VMX_EPT_EXECUTABLE_MASK,
cpu_has_vmx_ept_execute_only() ?
0ull : VMX_EPT_READABLE_MASK);
ept_set_mmio_spte_mask();
kvm_enable_tdp();
} else
kvm_disable_tdp();
update_ple_window_actual_max();
/*
* Only enable PML when hardware supports PML feature, and both EPT
* and EPT A/D bit features are enabled -- PML depends on them to work.
*/
if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
enable_pml = 0;
if (!enable_pml) {
kvm_x86_ops->slot_enable_log_dirty = NULL;
kvm_x86_ops->slot_disable_log_dirty = NULL;
kvm_x86_ops->flush_log_dirty = NULL;
kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
}
if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
u64 vmx_msr;
rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
cpu_preemption_timer_multi =
vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
} else {
kvm_x86_ops->set_hv_timer = NULL;
kvm_x86_ops->cancel_hv_timer = NULL;
}
kvm_set_posted_intr_wakeup_handler(wakeup_handler);
kvm_mce_cap_supported |= MCG_LMCE_P;
return alloc_kvm_area();
out:
for (i = 0; i < VMX_BITMAP_NR; i++)
free_page((unsigned long)vmx_bitmap[i]);
return r;
}
static __exit void hardware_unsetup(void)
{
int i;
for (i = 0; i < VMX_BITMAP_NR; i++)
free_page((unsigned long)vmx_bitmap[i]);
free_kvm_area();
}
/*
* Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
* exiting, so only get here on cpu with PAUSE-Loop-Exiting.
*/
static int handle_pause(struct kvm_vcpu *vcpu)
{
if (ple_gap)
grow_ple_window(vcpu);
kvm_vcpu_on_spin(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_nop(struct kvm_vcpu *vcpu)
{
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_mwait(struct kvm_vcpu *vcpu)
{
printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
return handle_nop(vcpu);
}
static int handle_monitor_trap(struct kvm_vcpu *vcpu)
{
return 1;
}
static int handle_monitor(struct kvm_vcpu *vcpu)
{
printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
return handle_nop(vcpu);
}
/*
* To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
* We could reuse a single VMCS for all the L2 guests, but we also want the
* option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
* allows keeping them loaded on the processor, and in the future will allow
* optimizations where prepare_vmcs02 doesn't need to set all the fields on
* every entry if they never change.
* So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
* (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
*
* The following functions allocate and free a vmcs02 in this pool.
*/
/* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
{
struct vmcs02_list *item;
list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
if (item->vmptr == vmx->nested.current_vmptr) {
list_move(&item->list, &vmx->nested.vmcs02_pool);
return &item->vmcs02;
}
if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
/* Recycle the least recently used VMCS. */
item = list_last_entry(&vmx->nested.vmcs02_pool,
struct vmcs02_list, list);
item->vmptr = vmx->nested.current_vmptr;
list_move(&item->list, &vmx->nested.vmcs02_pool);
return &item->vmcs02;
}
/* Create a new VMCS */
item = kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
if (!item)
return NULL;
item->vmcs02.vmcs = alloc_vmcs();
item->vmcs02.shadow_vmcs = NULL;
if (!item->vmcs02.vmcs) {
kfree(item);
return NULL;
}
loaded_vmcs_init(&item->vmcs02);
item->vmptr = vmx->nested.current_vmptr;
list_add(&(item->list), &(vmx->nested.vmcs02_pool));
vmx->nested.vmcs02_num++;
return &item->vmcs02;
}
/* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
{
struct vmcs02_list *item;
list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
if (item->vmptr == vmptr) {
free_loaded_vmcs(&item->vmcs02);
list_del(&item->list);
kfree(item);
vmx->nested.vmcs02_num--;
return;
}
}
/*
* Free all VMCSs saved for this vcpu, except the one pointed by
* vmx->loaded_vmcs. We must be running L1, so vmx->loaded_vmcs
* must be &vmx->vmcs01.
*/
static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
{
struct vmcs02_list *item, *n;
WARN_ON(vmx->loaded_vmcs != &vmx->vmcs01);
list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
/*
* Something will leak if the above WARN triggers. Better than
* a use-after-free.
*/
if (vmx->loaded_vmcs == &item->vmcs02)
continue;
free_loaded_vmcs(&item->vmcs02);
list_del(&item->list);
kfree(item);
vmx->nested.vmcs02_num--;
}
}
/*
* The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
* set the success or error code of an emulated VMX instruction, as specified
* by Vol 2B, VMX Instruction Reference, "Conventions".
*/
static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
{
vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
}
static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
{
vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
& ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
X86_EFLAGS_SF | X86_EFLAGS_OF))
| X86_EFLAGS_CF);
}
static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
u32 vm_instruction_error)
{
if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
/*
* failValid writes the error number to the current VMCS, which
* can't be done there isn't a current VMCS.
*/
nested_vmx_failInvalid(vcpu);
return;
}
vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_SF | X86_EFLAGS_OF))
| X86_EFLAGS_ZF);
get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
/*
* We don't need to force a shadow sync because
* VM_INSTRUCTION_ERROR is not shadowed
*/
}
static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
{
/* TODO: not to reset guest simply here. */
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
}
static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
{
struct vcpu_vmx *vmx =
container_of(timer, struct vcpu_vmx, nested.preemption_timer);
vmx->nested.preemption_timer_expired = true;
kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
kvm_vcpu_kick(&vmx->vcpu);
return HRTIMER_NORESTART;
}
/*
* Decode the memory-address operand of a vmx instruction, as recorded on an
* exit caused by such an instruction (run by a guest hypervisor).
* On success, returns 0. When the operand is invalid, returns 1 and throws
* #UD or #GP.
*/
static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
unsigned long exit_qualification,
u32 vmx_instruction_info, bool wr, gva_t *ret)
{
gva_t off;
bool exn;
struct kvm_segment s;
/*
* According to Vol. 3B, "Information for VM Exits Due to Instruction
* Execution", on an exit, vmx_instruction_info holds most of the
* addressing components of the operand. Only the displacement part
* is put in exit_qualification (see 3B, "Basic VM-Exit Information").
* For how an actual address is calculated from all these components,
* refer to Vol. 1, "Operand Addressing".
*/
int scaling = vmx_instruction_info & 3;
int addr_size = (vmx_instruction_info >> 7) & 7;
bool is_reg = vmx_instruction_info & (1u << 10);
int seg_reg = (vmx_instruction_info >> 15) & 7;
int index_reg = (vmx_instruction_info >> 18) & 0xf;
bool index_is_valid = !(vmx_instruction_info & (1u << 22));
int base_reg = (vmx_instruction_info >> 23) & 0xf;
bool base_is_valid = !(vmx_instruction_info & (1u << 27));
if (is_reg) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
/* Addr = segment_base + offset */
/* offset = base + [index * scale] + displacement */
off = exit_qualification; /* holds the displacement */
if (base_is_valid)
off += kvm_register_read(vcpu, base_reg);
if (index_is_valid)
off += kvm_register_read(vcpu, index_reg)<<scaling;
vmx_get_segment(vcpu, &s, seg_reg);
*ret = s.base + off;
if (addr_size == 1) /* 32 bit */
*ret &= 0xffffffff;
/* Checks for #GP/#SS exceptions. */
exn = false;
if (is_long_mode(vcpu)) {
/* Long mode: #GP(0)/#SS(0) if the memory address is in a
* non-canonical form. This is the only check on the memory
* destination for long mode!
*/
exn = is_noncanonical_address(*ret);
} else if (is_protmode(vcpu)) {
/* Protected mode: apply checks for segment validity in the
* following order:
* - segment type check (#GP(0) may be thrown)
* - usability check (#GP(0)/#SS(0))
* - limit check (#GP(0)/#SS(0))
*/
if (wr)
/* #GP(0) if the destination operand is located in a
* read-only data segment or any code segment.
*/
exn = ((s.type & 0xa) == 0 || (s.type & 8));
else
/* #GP(0) if the source operand is located in an
* execute-only code segment
*/
exn = ((s.type & 0xa) == 8);
if (exn) {
kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
return 1;
}
/* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
*/
exn = (s.unusable != 0);
/* Protected mode: #GP(0)/#SS(0) if the memory
* operand is outside the segment limit.
*/
exn = exn || (off + sizeof(u64) > s.limit);
}
if (exn) {
kvm_queue_exception_e(vcpu,
seg_reg == VCPU_SREG_SS ?
SS_VECTOR : GP_VECTOR,
0);
return 1;
}
return 0;
}
/*
* This function performs the various checks including
* - if it's 4KB aligned
* - No bits beyond the physical address width are set
* - Returns 0 on success or else 1
* (Intel SDM Section 30.3)
*/
static int nested_vmx_check_vmptr(struct kvm_vcpu *vcpu, int exit_reason,
gpa_t *vmpointer)
{
gva_t gva;
gpa_t vmptr;
struct x86_exception e;
struct page *page;
struct vcpu_vmx *vmx = to_vmx(vcpu);
int maxphyaddr = cpuid_maxphyaddr(vcpu);
if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
sizeof(vmptr), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
switch (exit_reason) {
case EXIT_REASON_VMON:
/*
* SDM 3: 24.11.5
* The first 4 bytes of VMXON region contain the supported
* VMCS revision identifier
*
* Note - IA32_VMX_BASIC[48] will never be 1
* for the nested case;
* which replaces physical address width with 32
*
*/
if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
nested_vmx_failInvalid(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
page = nested_get_page(vcpu, vmptr);
if (page == NULL ||
*(u32 *)kmap(page) != VMCS12_REVISION) {
nested_vmx_failInvalid(vcpu);
kunmap(page);
return kvm_skip_emulated_instruction(vcpu);
}
kunmap(page);
vmx->nested.vmxon_ptr = vmptr;
break;
case EXIT_REASON_VMCLEAR:
if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
nested_vmx_failValid(vcpu,
VMXERR_VMCLEAR_INVALID_ADDRESS);
return kvm_skip_emulated_instruction(vcpu);
}
if (vmptr == vmx->nested.vmxon_ptr) {
nested_vmx_failValid(vcpu,
VMXERR_VMCLEAR_VMXON_POINTER);
return kvm_skip_emulated_instruction(vcpu);
}
break;
case EXIT_REASON_VMPTRLD:
if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
nested_vmx_failValid(vcpu,
VMXERR_VMPTRLD_INVALID_ADDRESS);
return kvm_skip_emulated_instruction(vcpu);
}
if (vmptr == vmx->nested.vmxon_ptr) {
nested_vmx_failValid(vcpu,
VMXERR_VMPTRLD_VMXON_POINTER);
return kvm_skip_emulated_instruction(vcpu);
}
break;
default:
return 1; /* shouldn't happen */
}
if (vmpointer)
*vmpointer = vmptr;
return 0;
}
/*
* Emulate the VMXON instruction.
* Currently, we just remember that VMX is active, and do not save or even
* inspect the argument to VMXON (the so-called "VMXON pointer") because we
* do not currently need to store anything in that guest-allocated memory
* region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
* argument is different from the VMXON pointer (which the spec says they do).
*/
static int handle_vmon(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs;
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs *shadow_vmcs;
const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
| FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
/* The Intel VMX Instruction Reference lists a bunch of bits that
* are prerequisite to running VMXON, most notably cr4.VMXE must be
* set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
* Otherwise, we should fail with #UD. We test these now:
*/
if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
!kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
(vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
if (is_long_mode(vcpu) && !cs.l) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
if (vmx_get_cpl(vcpu)) {
kvm_inject_gp(vcpu, 0);
return 1;
}
if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMON, NULL))
return 1;
if (vmx->nested.vmxon) {
nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
return kvm_skip_emulated_instruction(vcpu);
}
if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
!= VMXON_NEEDED_FEATURES) {
kvm_inject_gp(vcpu, 0);
return 1;
}
if (cpu_has_vmx_msr_bitmap()) {
vmx->nested.msr_bitmap =
(unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx->nested.msr_bitmap)
goto out_msr_bitmap;
}
vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
if (!vmx->nested.cached_vmcs12)
goto out_cached_vmcs12;
if (enable_shadow_vmcs) {
shadow_vmcs = alloc_vmcs();
if (!shadow_vmcs)
goto out_shadow_vmcs;
/* mark vmcs as shadow */
shadow_vmcs->revision_id |= (1u << 31);
/* init shadow vmcs */
vmcs_clear(shadow_vmcs);
vmx->vmcs01.shadow_vmcs = shadow_vmcs;
}
INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
vmx->nested.vmcs02_num = 0;
hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
HRTIMER_MODE_REL_PINNED);
vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
vmx->nested.vmxon = true;
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
out_shadow_vmcs:
kfree(vmx->nested.cached_vmcs12);
out_cached_vmcs12:
free_page((unsigned long)vmx->nested.msr_bitmap);
out_msr_bitmap:
return -ENOMEM;
}
/*
* Intel's VMX Instruction Reference specifies a common set of prerequisites
* for running VMX instructions (except VMXON, whose prerequisites are
* slightly different). It also specifies what exception to inject otherwise.
*/
static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs;
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!vmx->nested.vmxon) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
(is_long_mode(vcpu) && !cs.l)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
if (vmx_get_cpl(vcpu)) {
kvm_inject_gp(vcpu, 0);
return 0;
}
return 1;
}
static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
{
if (vmx->nested.current_vmptr == -1ull)
return;
/* current_vmptr and current_vmcs12 are always set/reset together */
if (WARN_ON(vmx->nested.current_vmcs12 == NULL))
return;
if (enable_shadow_vmcs) {
/* copy to memory all shadowed fields in case
they were modified */
copy_shadow_to_vmcs12(vmx);
vmx->nested.sync_shadow_vmcs = false;
vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_SHADOW_VMCS);
vmcs_write64(VMCS_LINK_POINTER, -1ull);
}
vmx->nested.posted_intr_nv = -1;
/* Flush VMCS12 to guest memory */
memcpy(vmx->nested.current_vmcs12, vmx->nested.cached_vmcs12,
VMCS12_SIZE);
kunmap(vmx->nested.current_vmcs12_page);
nested_release_page(vmx->nested.current_vmcs12_page);
vmx->nested.current_vmptr = -1ull;
vmx->nested.current_vmcs12 = NULL;
}
/*
* Free whatever needs to be freed from vmx->nested when L1 goes down, or
* just stops using VMX.
*/
static void free_nested(struct vcpu_vmx *vmx)
{
if (!vmx->nested.vmxon)
return;
vmx->nested.vmxon = false;
free_vpid(vmx->nested.vpid02);
nested_release_vmcs12(vmx);
if (vmx->nested.msr_bitmap) {
free_page((unsigned long)vmx->nested.msr_bitmap);
vmx->nested.msr_bitmap = NULL;
}
if (enable_shadow_vmcs) {
vmcs_clear(vmx->vmcs01.shadow_vmcs);
free_vmcs(vmx->vmcs01.shadow_vmcs);
vmx->vmcs01.shadow_vmcs = NULL;
}
kfree(vmx->nested.cached_vmcs12);
/* Unpin physical memory we referred to in current vmcs02 */
if (vmx->nested.apic_access_page) {
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page = NULL;
}
if (vmx->nested.virtual_apic_page) {
nested_release_page(vmx->nested.virtual_apic_page);
vmx->nested.virtual_apic_page = NULL;
}
if (vmx->nested.pi_desc_page) {
kunmap(vmx->nested.pi_desc_page);
nested_release_page(vmx->nested.pi_desc_page);
vmx->nested.pi_desc_page = NULL;
vmx->nested.pi_desc = NULL;
}
nested_free_all_saved_vmcss(vmx);
}
/* Emulate the VMXOFF instruction */
static int handle_vmoff(struct kvm_vcpu *vcpu)
{
if (!nested_vmx_check_permission(vcpu))
return 1;
free_nested(to_vmx(vcpu));
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
/* Emulate the VMCLEAR instruction */
static int handle_vmclear(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
gpa_t vmptr;
struct vmcs12 *vmcs12;
struct page *page;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMCLEAR, &vmptr))
return 1;
if (vmptr == vmx->nested.current_vmptr)
nested_release_vmcs12(vmx);
page = nested_get_page(vcpu, vmptr);
if (page == NULL) {
/*
* For accurate processor emulation, VMCLEAR beyond available
* physical memory should do nothing at all. However, it is
* possible that a nested vmx bug, not a guest hypervisor bug,
* resulted in this case, so let's shut down before doing any
* more damage:
*/
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return 1;
}
vmcs12 = kmap(page);
vmcs12->launch_state = 0;
kunmap(page);
nested_release_page(page);
nested_free_vmcs02(vmx, vmptr);
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
/* Emulate the VMLAUNCH instruction */
static int handle_vmlaunch(struct kvm_vcpu *vcpu)
{
return nested_vmx_run(vcpu, true);
}
/* Emulate the VMRESUME instruction */
static int handle_vmresume(struct kvm_vcpu *vcpu)
{
return nested_vmx_run(vcpu, false);
}
enum vmcs_field_type {
VMCS_FIELD_TYPE_U16 = 0,
VMCS_FIELD_TYPE_U64 = 1,
VMCS_FIELD_TYPE_U32 = 2,
VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
};
static inline int vmcs_field_type(unsigned long field)
{
if (0x1 & field) /* the *_HIGH fields are all 32 bit */
return VMCS_FIELD_TYPE_U32;
return (field >> 13) & 0x3 ;
}
static inline int vmcs_field_readonly(unsigned long field)
{
return (((field >> 10) & 0x3) == 1);
}
/*
* Read a vmcs12 field. Since these can have varying lengths and we return
* one type, we chose the biggest type (u64) and zero-extend the return value
* to that size. Note that the caller, handle_vmread, might need to use only
* some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
* 64-bit fields are to be returned).
*/
static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
unsigned long field, u64 *ret)
{
short offset = vmcs_field_to_offset(field);
char *p;
if (offset < 0)
return offset;
p = ((char *)(get_vmcs12(vcpu))) + offset;
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
*ret = *((natural_width *)p);
return 0;
case VMCS_FIELD_TYPE_U16:
*ret = *((u16 *)p);
return 0;
case VMCS_FIELD_TYPE_U32:
*ret = *((u32 *)p);
return 0;
case VMCS_FIELD_TYPE_U64:
*ret = *((u64 *)p);
return 0;
default:
WARN_ON(1);
return -ENOENT;
}
}
static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
unsigned long field, u64 field_value){
short offset = vmcs_field_to_offset(field);
char *p = ((char *) get_vmcs12(vcpu)) + offset;
if (offset < 0)
return offset;
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_U16:
*(u16 *)p = field_value;
return 0;
case VMCS_FIELD_TYPE_U32:
*(u32 *)p = field_value;
return 0;
case VMCS_FIELD_TYPE_U64:
*(u64 *)p = field_value;
return 0;
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
*(natural_width *)p = field_value;
return 0;
default:
WARN_ON(1);
return -ENOENT;
}
}
static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
{
int i;
unsigned long field;
u64 field_value;
struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
const unsigned long *fields = shadow_read_write_fields;
const int num_fields = max_shadow_read_write_fields;
preempt_disable();
vmcs_load(shadow_vmcs);
for (i = 0; i < num_fields; i++) {
field = fields[i];
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_U16:
field_value = vmcs_read16(field);
break;
case VMCS_FIELD_TYPE_U32:
field_value = vmcs_read32(field);
break;
case VMCS_FIELD_TYPE_U64:
field_value = vmcs_read64(field);
break;
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
field_value = vmcs_readl(field);
break;
default:
WARN_ON(1);
continue;
}
vmcs12_write_any(&vmx->vcpu, field, field_value);
}
vmcs_clear(shadow_vmcs);
vmcs_load(vmx->loaded_vmcs->vmcs);
preempt_enable();
}
static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
{
const unsigned long *fields[] = {
shadow_read_write_fields,
shadow_read_only_fields
};
const int max_fields[] = {
max_shadow_read_write_fields,
max_shadow_read_only_fields
};
int i, q;
unsigned long field;
u64 field_value = 0;
struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
vmcs_load(shadow_vmcs);
for (q = 0; q < ARRAY_SIZE(fields); q++) {
for (i = 0; i < max_fields[q]; i++) {
field = fields[q][i];
vmcs12_read_any(&vmx->vcpu, field, &field_value);
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_U16:
vmcs_write16(field, (u16)field_value);
break;
case VMCS_FIELD_TYPE_U32:
vmcs_write32(field, (u32)field_value);
break;
case VMCS_FIELD_TYPE_U64:
vmcs_write64(field, (u64)field_value);
break;
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
vmcs_writel(field, (long)field_value);
break;
default:
WARN_ON(1);
break;
}
}
}
vmcs_clear(shadow_vmcs);
vmcs_load(vmx->loaded_vmcs->vmcs);
}
/*
* VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
* used before) all generate the same failure when it is missing.
*/
static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (vmx->nested.current_vmptr == -1ull) {
nested_vmx_failInvalid(vcpu);
return 0;
}
return 1;
}
static int handle_vmread(struct kvm_vcpu *vcpu)
{
unsigned long field;
u64 field_value;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t gva = 0;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
return kvm_skip_emulated_instruction(vcpu);
/* Decode instruction info and find the field to read */
field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
/* Read the field, zero-extended to a u64 field_value */
if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
/*
* Now copy part of this value to register or memory, as requested.
* Note that the number of bits actually copied is 32 or 64 depending
* on the guest's mode (32 or 64 bit), not on the given field's length.
*/
if (vmx_instruction_info & (1u << 10)) {
kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
field_value);
} else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &gva))
return 1;
/* _system ok, as nested_vmx_check_permission verified cpl=0 */
kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_vmwrite(struct kvm_vcpu *vcpu)
{
unsigned long field;
gva_t gva;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
/* The value to write might be 32 or 64 bits, depending on L1's long
* mode, and eventually we need to write that into a field of several
* possible lengths. The code below first zero-extends the value to 64
* bit (field_value), and then copies only the appropriate number of
* bits into the vmcs12 field.
*/
u64 field_value = 0;
struct x86_exception e;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
return kvm_skip_emulated_instruction(vcpu);
if (vmx_instruction_info & (1u << 10))
field_value = kvm_register_readl(vcpu,
(((vmx_instruction_info) >> 3) & 0xf));
else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, false, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
}
field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
if (vmcs_field_readonly(field)) {
nested_vmx_failValid(vcpu,
VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
if (vmcs12_write_any(vcpu, field, field_value) < 0) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
/* Emulate the VMPTRLD instruction */
static int handle_vmptrld(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
gpa_t vmptr;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMPTRLD, &vmptr))
return 1;
if (vmx->nested.current_vmptr != vmptr) {
struct vmcs12 *new_vmcs12;
struct page *page;
page = nested_get_page(vcpu, vmptr);
if (page == NULL) {
nested_vmx_failInvalid(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
new_vmcs12 = kmap(page);
if (new_vmcs12->revision_id != VMCS12_REVISION) {
kunmap(page);
nested_release_page_clean(page);
nested_vmx_failValid(vcpu,
VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
return kvm_skip_emulated_instruction(vcpu);
}
nested_release_vmcs12(vmx);
vmx->nested.current_vmptr = vmptr;
vmx->nested.current_vmcs12 = new_vmcs12;
vmx->nested.current_vmcs12_page = page;
/*
* Load VMCS12 from guest memory since it is not already
* cached.
*/
memcpy(vmx->nested.cached_vmcs12,
vmx->nested.current_vmcs12, VMCS12_SIZE);
if (enable_shadow_vmcs) {
vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_SHADOW_VMCS);
vmcs_write64(VMCS_LINK_POINTER,
__pa(vmx->vmcs01.shadow_vmcs));
vmx->nested.sync_shadow_vmcs = true;
}
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
/* Emulate the VMPTRST instruction */
static int handle_vmptrst(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t vmcs_gva;
struct x86_exception e;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &vmcs_gva))
return 1;
/* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
(void *)&to_vmx(vcpu)->nested.current_vmptr,
sizeof(u64), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
/* Emulate the INVEPT instruction */
static int handle_invept(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 vmx_instruction_info, types;
unsigned long type;
gva_t gva;
struct x86_exception e;
struct {
u64 eptp, gpa;
} operand;
if (!(vmx->nested.nested_vmx_secondary_ctls_high &
SECONDARY_EXEC_ENABLE_EPT) ||
!(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
if (type >= 32 || !(types & (1 << type))) {
nested_vmx_failValid(vcpu,
VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
return kvm_skip_emulated_instruction(vcpu);
}
/* According to the Intel VMX instruction reference, the memory
* operand is read even if it isn't needed (e.g., for type==global)
*/
if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
vmx_instruction_info, false, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
sizeof(operand), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
switch (type) {
case VMX_EPT_EXTENT_GLOBAL:
/*
* TODO: track mappings and invalidate
* single context requests appropriately
*/
case VMX_EPT_EXTENT_CONTEXT:
kvm_mmu_sync_roots(vcpu);
kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
nested_vmx_succeed(vcpu);
break;
default:
BUG_ON(1);
break;
}
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_invvpid(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 vmx_instruction_info;
unsigned long type, types;
gva_t gva;
struct x86_exception e;
int vpid;
if (!(vmx->nested.nested_vmx_secondary_ctls_high &
SECONDARY_EXEC_ENABLE_VPID) ||
!(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
if (!nested_vmx_check_permission(vcpu))
return 1;
vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
types = (vmx->nested.nested_vmx_vpid_caps &
VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
if (type >= 32 || !(types & (1 << type))) {
nested_vmx_failValid(vcpu,
VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
return kvm_skip_emulated_instruction(vcpu);
}
/* according to the intel vmx instruction reference, the memory
* operand is read even if it isn't needed (e.g., for type==global)
*/
if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
vmx_instruction_info, false, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vpid,
sizeof(u32), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
switch (type) {
case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
case VMX_VPID_EXTENT_SINGLE_CONTEXT:
case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
if (!vpid) {
nested_vmx_failValid(vcpu,
VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
return kvm_skip_emulated_instruction(vcpu);
}
break;
case VMX_VPID_EXTENT_ALL_CONTEXT:
break;
default:
WARN_ON_ONCE(1);
return kvm_skip_emulated_instruction(vcpu);
}
__vmx_flush_tlb(vcpu, vmx->nested.vpid02);
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
static int handle_pml_full(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
trace_kvm_pml_full(vcpu->vcpu_id);
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
/*
* PML buffer FULL happened while executing iret from NMI,
* "blocked by NMI" bit has to be set before next VM entry.
*/
if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
cpu_has_virtual_nmis() &&
(exit_qualification & INTR_INFO_UNBLOCK_NMI))
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
/*
* PML buffer already flushed at beginning of VMEXIT. Nothing to do
* here.., and there's no userspace involvement needed for PML.
*/
return 1;
}
static int handle_preemption_timer(struct kvm_vcpu *vcpu)
{
kvm_lapic_expired_hv_timer(vcpu);
return 1;
}
/*
* The exit handlers return 1 if the exit was handled fully and guest execution
* may resume. Otherwise they set the kvm_run parameter to indicate what needs
* to be done to userspace and return 0.
*/
static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
[EXIT_REASON_EXCEPTION_NMI] = handle_exception,
[EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
[EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
[EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
[EXIT_REASON_IO_INSTRUCTION] = handle_io,
[EXIT_REASON_CR_ACCESS] = handle_cr,
[EXIT_REASON_DR_ACCESS] = handle_dr,
[EXIT_REASON_CPUID] = handle_cpuid,
[EXIT_REASON_MSR_READ] = handle_rdmsr,
[EXIT_REASON_MSR_WRITE] = handle_wrmsr,
[EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
[EXIT_REASON_HLT] = handle_halt,
[EXIT_REASON_INVD] = handle_invd,
[EXIT_REASON_INVLPG] = handle_invlpg,
[EXIT_REASON_RDPMC] = handle_rdpmc,
[EXIT_REASON_VMCALL] = handle_vmcall,
[EXIT_REASON_VMCLEAR] = handle_vmclear,
[EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
[EXIT_REASON_VMPTRLD] = handle_vmptrld,
[EXIT_REASON_VMPTRST] = handle_vmptrst,
[EXIT_REASON_VMREAD] = handle_vmread,
[EXIT_REASON_VMRESUME] = handle_vmresume,
[EXIT_REASON_VMWRITE] = handle_vmwrite,
[EXIT_REASON_VMOFF] = handle_vmoff,
[EXIT_REASON_VMON] = handle_vmon,
[EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
[EXIT_REASON_APIC_ACCESS] = handle_apic_access,
[EXIT_REASON_APIC_WRITE] = handle_apic_write,
[EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
[EXIT_REASON_WBINVD] = handle_wbinvd,
[EXIT_REASON_XSETBV] = handle_xsetbv,
[EXIT_REASON_TASK_SWITCH] = handle_task_switch,
[EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
[EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
[EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
[EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
[EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
[EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
[EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
[EXIT_REASON_INVEPT] = handle_invept,
[EXIT_REASON_INVVPID] = handle_invvpid,
[EXIT_REASON_XSAVES] = handle_xsaves,
[EXIT_REASON_XRSTORS] = handle_xrstors,
[EXIT_REASON_PML_FULL] = handle_pml_full,
[EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
};
static const int kvm_vmx_max_exit_handlers =
ARRAY_SIZE(kvm_vmx_exit_handlers);
static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
unsigned long exit_qualification;
gpa_t bitmap, last_bitmap;
unsigned int port;
int size;
u8 b;
if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
port = exit_qualification >> 16;
size = (exit_qualification & 7) + 1;
last_bitmap = (gpa_t)-1;
b = -1;
while (size > 0) {
if (port < 0x8000)
bitmap = vmcs12->io_bitmap_a;
else if (port < 0x10000)
bitmap = vmcs12->io_bitmap_b;
else
return true;
bitmap += (port & 0x7fff) / 8;
if (last_bitmap != bitmap)
if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
return true;
if (b & (1 << (port & 7)))
return true;
port++;
size--;
last_bitmap = bitmap;
}
return false;
}
/*
* Return 1 if we should exit from L2 to L1 to handle an MSR access access,
* rather than handle it ourselves in L0. I.e., check whether L1 expressed
* disinterest in the current event (read or write a specific MSR) by using an
* MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
*/
static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12, u32 exit_reason)
{
u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
gpa_t bitmap;
if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
return true;
/*
* The MSR_BITMAP page is divided into four 1024-byte bitmaps,
* for the four combinations of read/write and low/high MSR numbers.
* First we need to figure out which of the four to use:
*/
bitmap = vmcs12->msr_bitmap;
if (exit_reason == EXIT_REASON_MSR_WRITE)
bitmap += 2048;
if (msr_index >= 0xc0000000) {
msr_index -= 0xc0000000;
bitmap += 1024;
}
/* Then read the msr_index'th bit from this bitmap: */
if (msr_index < 1024*8) {
unsigned char b;
if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
return true;
return 1 & (b >> (msr_index & 7));
} else
return true; /* let L1 handle the wrong parameter */
}
/*
* Return 1 if we should exit from L2 to L1 to handle a CR access exit,
* rather than handle it ourselves in L0. I.e., check if L1 wanted to
* intercept (via guest_host_mask etc.) the current event.
*/
static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
int cr = exit_qualification & 15;
int reg = (exit_qualification >> 8) & 15;
unsigned long val = kvm_register_readl(vcpu, reg);
switch ((exit_qualification >> 4) & 3) {
case 0: /* mov to cr */
switch (cr) {
case 0:
if (vmcs12->cr0_guest_host_mask &
(val ^ vmcs12->cr0_read_shadow))
return true;
break;
case 3:
if ((vmcs12->cr3_target_count >= 1 &&
vmcs12->cr3_target_value0 == val) ||
(vmcs12->cr3_target_count >= 2 &&
vmcs12->cr3_target_value1 == val) ||
(vmcs12->cr3_target_count >= 3 &&
vmcs12->cr3_target_value2 == val) ||
(vmcs12->cr3_target_count >= 4 &&
vmcs12->cr3_target_value3 == val))
return false;
if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
return true;
break;
case 4:
if (vmcs12->cr4_guest_host_mask &
(vmcs12->cr4_read_shadow ^ val))
return true;
break;
case 8:
if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
return true;
break;
}
break;
case 2: /* clts */
if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
(vmcs12->cr0_read_shadow & X86_CR0_TS))
return true;
break;
case 1: /* mov from cr */
switch (cr) {
case 3:
if (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_CR3_STORE_EXITING)
return true;
break;
case 8:
if (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_CR8_STORE_EXITING)
return true;
break;
}
break;
case 3: /* lmsw */
/*
* lmsw can change bits 1..3 of cr0, and only set bit 0 of
* cr0. Other attempted changes are ignored, with no exit.
*/
if (vmcs12->cr0_guest_host_mask & 0xe &
(val ^ vmcs12->cr0_read_shadow))
return true;
if ((vmcs12->cr0_guest_host_mask & 0x1) &&
!(vmcs12->cr0_read_shadow & 0x1) &&
(val & 0x1))
return true;
break;
}
return false;
}
/*
* Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
* should handle it ourselves in L0 (and then continue L2). Only call this
* when in is_guest_mode (L2).
*/
static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
{
u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
u32 exit_reason = vmx->exit_reason;
trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
vmcs_readl(EXIT_QUALIFICATION),
vmx->idt_vectoring_info,
intr_info,
vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
KVM_ISA_VMX);
if (vmx->nested.nested_run_pending)
return false;
if (unlikely(vmx->fail)) {
pr_info_ratelimited("%s failed vm entry %x\n", __func__,
vmcs_read32(VM_INSTRUCTION_ERROR));
return true;
}
switch (exit_reason) {
case EXIT_REASON_EXCEPTION_NMI:
if (is_nmi(intr_info))
return false;
else if (is_page_fault(intr_info))
return enable_ept;
else if (is_no_device(intr_info) &&
!(vmcs12->guest_cr0 & X86_CR0_TS))
return false;
else if (is_debug(intr_info) &&
vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
return false;
else if (is_breakpoint(intr_info) &&
vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
return false;
return vmcs12->exception_bitmap &
(1u << (intr_info & INTR_INFO_VECTOR_MASK));
case EXIT_REASON_EXTERNAL_INTERRUPT:
return false;
case EXIT_REASON_TRIPLE_FAULT:
return true;
case EXIT_REASON_PENDING_INTERRUPT:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
case EXIT_REASON_NMI_WINDOW:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
case EXIT_REASON_TASK_SWITCH:
return true;
case EXIT_REASON_CPUID:
if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa)
return false;
return true;
case EXIT_REASON_HLT:
return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
case EXIT_REASON_INVD:
return true;
case EXIT_REASON_INVLPG:
return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
case EXIT_REASON_RDPMC:
return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
/*
* VMX instructions trap unconditionally. This allows L1 to
* emulate them for its L2 guest, i.e., allows 3-level nesting!
*/
return true;
case EXIT_REASON_CR_ACCESS:
return nested_vmx_exit_handled_cr(vcpu, vmcs12);
case EXIT_REASON_DR_ACCESS:
return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
case EXIT_REASON_IO_INSTRUCTION:
return nested_vmx_exit_handled_io(vcpu, vmcs12);
case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
case EXIT_REASON_MSR_READ:
case EXIT_REASON_MSR_WRITE:
return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
case EXIT_REASON_INVALID_STATE:
return true;
case EXIT_REASON_MWAIT_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
case EXIT_REASON_MONITOR_TRAP_FLAG:
return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
case EXIT_REASON_MONITOR_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
case EXIT_REASON_PAUSE_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
nested_cpu_has2(vmcs12,
SECONDARY_EXEC_PAUSE_LOOP_EXITING);
case EXIT_REASON_MCE_DURING_VMENTRY:
return false;
case EXIT_REASON_TPR_BELOW_THRESHOLD:
return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
case EXIT_REASON_APIC_ACCESS:
return nested_cpu_has2(vmcs12,
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
case EXIT_REASON_APIC_WRITE:
case EXIT_REASON_EOI_INDUCED:
/* apic_write and eoi_induced should exit unconditionally. */
return true;
case EXIT_REASON_EPT_VIOLATION:
/*
* L0 always deals with the EPT violation. If nested EPT is
* used, and the nested mmu code discovers that the address is
* missing in the guest EPT table (EPT12), the EPT violation
* will be injected with nested_ept_inject_page_fault()
*/
return false;
case EXIT_REASON_EPT_MISCONFIG:
/*
* L2 never uses directly L1's EPT, but rather L0's own EPT
* table (shadow on EPT) or a merged EPT table that L0 built
* (EPT on EPT). So any problems with the structure of the
* table is L0's fault.
*/
return false;
case EXIT_REASON_WBINVD:
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
case EXIT_REASON_XSETBV:
return true;
case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
/*
* This should never happen, since it is not possible to
* set XSS to a non-zero value---neither in L1 nor in L2.
* If if it were, XSS would have to be checked against
* the XSS exit bitmap in vmcs12.
*/
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
case EXIT_REASON_PREEMPTION_TIMER:
return false;
default:
return true;
}
}
static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
{
*info1 = vmcs_readl(EXIT_QUALIFICATION);
*info2 = vmcs_read32(VM_EXIT_INTR_INFO);
}
static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
{
if (vmx->pml_pg) {
__free_page(vmx->pml_pg);
vmx->pml_pg = NULL;
}
}
static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 *pml_buf;
u16 pml_idx;
pml_idx = vmcs_read16(GUEST_PML_INDEX);
/* Do nothing if PML buffer is empty */
if (pml_idx == (PML_ENTITY_NUM - 1))
return;
/* PML index always points to next available PML buffer entity */
if (pml_idx >= PML_ENTITY_NUM)
pml_idx = 0;
else
pml_idx++;
pml_buf = page_address(vmx->pml_pg);
for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
u64 gpa;
gpa = pml_buf[pml_idx];
WARN_ON(gpa & (PAGE_SIZE - 1));
kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
}
/* reset PML index */
vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
}
/*
* Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
* Called before reporting dirty_bitmap to userspace.
*/
static void kvm_flush_pml_buffers(struct kvm *kvm)
{
int i;
struct kvm_vcpu *vcpu;
/*
* We only need to kick vcpu out of guest mode here, as PML buffer
* is flushed at beginning of all VMEXITs, and it's obvious that only
* vcpus running in guest are possible to have unflushed GPAs in PML
* buffer.
*/
kvm_for_each_vcpu(i, vcpu, kvm)
kvm_vcpu_kick(vcpu);
}
static void vmx_dump_sel(char *name, uint32_t sel)
{
pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
name, vmcs_read32(sel),
vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
}
static void vmx_dump_dtsel(char *name, uint32_t limit)
{
pr_err("%s limit=0x%08x, base=0x%016lx\n",
name, vmcs_read32(limit),
vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
}
static void dump_vmcs(void)
{
u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
u32 secondary_exec_control = 0;
unsigned long cr4 = vmcs_readl(GUEST_CR4);
u64 efer = vmcs_read64(GUEST_IA32_EFER);
int i, n;
if (cpu_has_secondary_exec_ctrls())
secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
pr_err("*** Guest State ***\n");
pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
vmcs_readl(CR0_GUEST_HOST_MASK));
pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
(cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
{
pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
}
pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
vmcs_readl(GUEST_SYSENTER_ESP),
vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
(vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
efer, vmcs_read64(GUEST_IA32_PAT));
pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
vmcs_read64(GUEST_IA32_DEBUGCTL),
vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
pr_err("PerfGlobCtl = 0x%016llx\n",
vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
pr_err("Interruptibility = %08x ActivityState = %08x\n",
vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
vmcs_read32(GUEST_ACTIVITY_STATE));
if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
pr_err("InterruptStatus = %04x\n",
vmcs_read16(GUEST_INTR_STATUS));
pr_err("*** Host State ***\n");
pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
vmcs_read16(HOST_TR_SELECTOR));
pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
vmcs_readl(HOST_TR_BASE));
pr_err("GDTBase=%016lx IDTBase=%016lx\n",
vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
vmcs_readl(HOST_CR4));
pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
vmcs_readl(HOST_IA32_SYSENTER_ESP),
vmcs_read32(HOST_IA32_SYSENTER_CS),
vmcs_readl(HOST_IA32_SYSENTER_EIP));
if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
vmcs_read64(HOST_IA32_EFER),
vmcs_read64(HOST_IA32_PAT));
if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
pr_err("PerfGlobCtl = 0x%016llx\n",
vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
pr_err("*** Control State ***\n");
pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
vmcs_read32(EXCEPTION_BITMAP),
vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
vmcs_read32(VM_EXIT_INTR_INFO),
vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
pr_err(" reason=%08x qualification=%016lx\n",
vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
pr_err("IDTVectoring: info=%08x errcode=%08x\n",
vmcs_read32(IDT_VECTORING_INFO_FIELD),
vmcs_read32(IDT_VECTORING_ERROR_CODE));
pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
pr_err("TSC Multiplier = 0x%016llx\n",
vmcs_read64(TSC_MULTIPLIER));
if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
n = vmcs_read32(CR3_TARGET_COUNT);
for (i = 0; i + 1 < n; i += 4)
pr_err("CR3 target%u=%016lx target%u=%016lx\n",
i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
if (i < n)
pr_err("CR3 target%u=%016lx\n",
i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
pr_err("PLE Gap=%08x Window=%08x\n",
vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
pr_err("Virtual processor ID = 0x%04x\n",
vmcs_read16(VIRTUAL_PROCESSOR_ID));
}
/*
* The guest has exited. See if we can fix it or if we need userspace
* assistance.
*/
static int vmx_handle_exit(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 exit_reason = vmx->exit_reason;
u32 vectoring_info = vmx->idt_vectoring_info;
trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
/*
* Flush logged GPAs PML buffer, this will make dirty_bitmap more
* updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
* querying dirty_bitmap, we only need to kick all vcpus out of guest
* mode as if vcpus is in root mode, the PML buffer must has been
* flushed already.
*/
if (enable_pml)
vmx_flush_pml_buffer(vcpu);
/* If guest state is invalid, start emulating */
if (vmx->emulation_required)
return handle_invalid_guest_state(vcpu);
if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
nested_vmx_vmexit(vcpu, exit_reason,
vmcs_read32(VM_EXIT_INTR_INFO),
vmcs_readl(EXIT_QUALIFICATION));
return 1;
}
if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
dump_vmcs();
vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
vcpu->run->fail_entry.hardware_entry_failure_reason
= exit_reason;
return 0;
}
if (unlikely(vmx->fail)) {
vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
vcpu->run->fail_entry.hardware_entry_failure_reason
= vmcs_read32(VM_INSTRUCTION_ERROR);
return 0;
}
/*
* Note:
* Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
* delivery event since it indicates guest is accessing MMIO.
* The vm-exit can be triggered again after return to guest that
* will cause infinite loop.
*/
if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
(exit_reason != EXIT_REASON_EXCEPTION_NMI &&
exit_reason != EXIT_REASON_EPT_VIOLATION &&
exit_reason != EXIT_REASON_PML_FULL &&
exit_reason != EXIT_REASON_TASK_SWITCH)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
vcpu->run->internal.ndata = 2;
vcpu->run->internal.data[0] = vectoring_info;
vcpu->run->internal.data[1] = exit_reason;
return 0;
}
if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
!(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
get_vmcs12(vcpu))))) {
if (vmx_interrupt_allowed(vcpu)) {
vmx->soft_vnmi_blocked = 0;
} else if (vmx->vnmi_blocked_time > 1000000000LL &&
vcpu->arch.nmi_pending) {
/*
* This CPU don't support us in finding the end of an
* NMI-blocked window if the guest runs with IRQs
* disabled. So we pull the trigger after 1 s of
* futile waiting, but inform the user about this.
*/
printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
"state on VCPU %d after 1 s timeout\n",
__func__, vcpu->vcpu_id);
vmx->soft_vnmi_blocked = 0;
}
}
if (exit_reason < kvm_vmx_max_exit_handlers
&& kvm_vmx_exit_handlers[exit_reason])
return kvm_vmx_exit_handlers[exit_reason](vcpu);
else {
WARN_ONCE(1, "vmx: unexpected exit reason 0x%x\n", exit_reason);
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
}
static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
if (is_guest_mode(vcpu) &&
nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
return;
if (irr == -1 || tpr < irr) {
vmcs_write32(TPR_THRESHOLD, 0);
return;
}
vmcs_write32(TPR_THRESHOLD, irr);
}
static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
{
u32 sec_exec_control;
/* Postpone execution until vmcs01 is the current VMCS. */
if (is_guest_mode(vcpu)) {
to_vmx(vcpu)->nested.change_vmcs01_virtual_x2apic_mode = true;
return;
}
if (!cpu_has_vmx_virtualize_x2apic_mode())
return;
if (!cpu_need_tpr_shadow(vcpu))
return;
sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
if (set) {
sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
} else {
sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
}
vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
vmx_set_msr_bitmap(vcpu);
}
static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
/*
* Currently we do not handle the nested case where L2 has an
* APIC access page of its own; that page is still pinned.
* Hence, we skip the case where the VCPU is in guest mode _and_
* L1 prepared an APIC access page for L2.
*
* For the case where L1 and L2 share the same APIC access page
* (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
* in the vmcs12), this function will only update either the vmcs01
* or the vmcs02. If the former, the vmcs02 will be updated by
* prepare_vmcs02. If the latter, the vmcs01 will be updated in
* the next L2->L1 exit.
*/
if (!is_guest_mode(vcpu) ||
!nested_cpu_has2(get_vmcs12(&vmx->vcpu),
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
vmcs_write64(APIC_ACCESS_ADDR, hpa);
}
static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
{
u16 status;
u8 old;
if (max_isr == -1)
max_isr = 0;
status = vmcs_read16(GUEST_INTR_STATUS);
old = status >> 8;
if (max_isr != old) {
status &= 0xff;
status |= max_isr << 8;
vmcs_write16(GUEST_INTR_STATUS, status);
}
}
static void vmx_set_rvi(int vector)
{
u16 status;
u8 old;
if (vector == -1)
vector = 0;
status = vmcs_read16(GUEST_INTR_STATUS);
old = (u8)status & 0xff;
if ((u8)vector != old) {
status &= ~0xff;
status |= (u8)vector;
vmcs_write16(GUEST_INTR_STATUS, status);
}
}
static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
{
if (!is_guest_mode(vcpu)) {
vmx_set_rvi(max_irr);
return;
}
if (max_irr == -1)
return;
/*
* In guest mode. If a vmexit is needed, vmx_check_nested_events
* handles it.
*/
if (nested_exit_on_intr(vcpu))
return;
/*
* Else, fall back to pre-APICv interrupt injection since L2
* is run without virtual interrupt delivery.
*/
if (!kvm_event_needs_reinjection(vcpu) &&
vmx_interrupt_allowed(vcpu)) {
kvm_queue_interrupt(vcpu, max_irr, false);
vmx_inject_irq(vcpu);
}
}
static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
{
if (!kvm_vcpu_apicv_active(vcpu))
return;
vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
}
static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
{
u32 exit_intr_info;
if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
|| vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
return;
vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
exit_intr_info = vmx->exit_intr_info;
/* Handle machine checks before interrupts are enabled */
if (is_machine_check(exit_intr_info))
kvm_machine_check();
/* We need to handle NMIs before interrupts are enabled */
if (is_nmi(exit_intr_info)) {
kvm_before_handle_nmi(&vmx->vcpu);
asm("int $2");
kvm_after_handle_nmi(&vmx->vcpu);
}
}
static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
{
u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
register void *__sp asm(_ASM_SP);
if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
== (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
unsigned int vector;
unsigned long entry;
gate_desc *desc;
struct vcpu_vmx *vmx = to_vmx(vcpu);
#ifdef CONFIG_X86_64
unsigned long tmp;
#endif
vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
desc = (gate_desc *)vmx->host_idt_base + vector;
entry = gate_offset(*desc);
asm volatile(
#ifdef CONFIG_X86_64
"mov %%" _ASM_SP ", %[sp]\n\t"
"and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
"push $%c[ss]\n\t"
"push %[sp]\n\t"
#endif
"pushf\n\t"
__ASM_SIZE(push) " $%c[cs]\n\t"
"call *%[entry]\n\t"
:
#ifdef CONFIG_X86_64
[sp]"=&r"(tmp),
#endif
"+r"(__sp)
:
[entry]"r"(entry),
[ss]"i"(__KERNEL_DS),
[cs]"i"(__KERNEL_CS)
);
}
}
static bool vmx_has_high_real_mode_segbase(void)
{
return enable_unrestricted_guest || emulate_invalid_guest_state;
}
static bool vmx_mpx_supported(void)
{
return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
(vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
}
static bool vmx_xsaves_supported(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_XSAVES;
}
static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
{
u32 exit_intr_info;
bool unblock_nmi;
u8 vector;
bool idtv_info_valid;
idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
if (cpu_has_virtual_nmis()) {
if (vmx->nmi_known_unmasked)
return;
/*
* Can't use vmx->exit_intr_info since we're not sure what
* the exit reason is.
*/
exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
/*
* SDM 3: 27.7.1.2 (September 2008)
* Re-set bit "block by NMI" before VM entry if vmexit caused by
* a guest IRET fault.
* SDM 3: 23.2.2 (September 2008)
* Bit 12 is undefined in any of the following cases:
* If the VM exit sets the valid bit in the IDT-vectoring
* information field.
* If the VM exit is due to a double fault.
*/
if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
vector != DF_VECTOR && !idtv_info_valid)
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
else
vmx->nmi_known_unmasked =
!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
& GUEST_INTR_STATE_NMI);
} else if (unlikely(vmx->soft_vnmi_blocked))
vmx->vnmi_blocked_time +=
ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
}
static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
u32 idt_vectoring_info,
int instr_len_field,
int error_code_field)
{
u8 vector;
int type;
bool idtv_info_valid;
idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
vcpu->arch.nmi_injected = false;
kvm_clear_exception_queue(vcpu);
kvm_clear_interrupt_queue(vcpu);
if (!idtv_info_valid)
return;
kvm_make_request(KVM_REQ_EVENT, vcpu);
vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
switch (type) {
case INTR_TYPE_NMI_INTR:
vcpu->arch.nmi_injected = true;
/*
* SDM 3: 27.7.1.2 (September 2008)
* Clear bit "block by NMI" before VM entry if a NMI
* delivery faulted.
*/
vmx_set_nmi_mask(vcpu, false);
break;
case INTR_TYPE_SOFT_EXCEPTION:
vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
/* fall through */
case INTR_TYPE_HARD_EXCEPTION:
if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
u32 err = vmcs_read32(error_code_field);
kvm_requeue_exception_e(vcpu, vector, err);
} else
kvm_requeue_exception(vcpu, vector);
break;
case INTR_TYPE_SOFT_INTR:
vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
/* fall through */
case INTR_TYPE_EXT_INTR:
kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
break;
default:
break;
}
}
static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
{
__vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
VM_EXIT_INSTRUCTION_LEN,
IDT_VECTORING_ERROR_CODE);
}
static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
{
__vmx_complete_interrupts(vcpu,
vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
VM_ENTRY_INSTRUCTION_LEN,
VM_ENTRY_EXCEPTION_ERROR_CODE);
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
}
static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
{
int i, nr_msrs;
struct perf_guest_switch_msr *msrs;
msrs = perf_guest_get_msrs(&nr_msrs);
if (!msrs)
return;
for (i = 0; i < nr_msrs; i++)
if (msrs[i].host == msrs[i].guest)
clear_atomic_switch_msr(vmx, msrs[i].msr);
else
add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
msrs[i].host);
}
static void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 tscl;
u32 delta_tsc;
if (vmx->hv_deadline_tsc == -1)
return;
tscl = rdtsc();
if (vmx->hv_deadline_tsc > tscl)
/* sure to be 32 bit only because checked on set_hv_timer */
delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
cpu_preemption_timer_multi);
else
delta_tsc = 0;
vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
}
static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long debugctlmsr, cr4;
/* Record the guest's net vcpu time for enforced NMI injections. */
if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
vmx->entry_time = ktime_get();
/* Don't enter VMX if guest state is invalid, let the exit handler
start emulation until we arrive back to a valid state */
if (vmx->emulation_required)
return;
if (vmx->ple_window_dirty) {
vmx->ple_window_dirty = false;
vmcs_write32(PLE_WINDOW, vmx->ple_window);
}
if (vmx->nested.sync_shadow_vmcs) {
copy_vmcs12_to_shadow(vmx);
vmx->nested.sync_shadow_vmcs = false;
}
if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
cr4 = cr4_read_shadow();
if (unlikely(cr4 != vmx->host_state.vmcs_host_cr4)) {
vmcs_writel(HOST_CR4, cr4);
vmx->host_state.vmcs_host_cr4 = cr4;
}
/* When single-stepping over STI and MOV SS, we must clear the
* corresponding interruptibility bits in the guest state. Otherwise
* vmentry fails as it then expects bit 14 (BS) in pending debug
* exceptions being set, but that's not correct for the guest debugging
* case. */
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
vmx_set_interrupt_shadow(vcpu, 0);
if (vmx->guest_pkru_valid)
__write_pkru(vmx->guest_pkru);
atomic_switch_perf_msrs(vmx);
debugctlmsr = get_debugctlmsr();
vmx_arm_hv_timer(vcpu);
vmx->__launched = vmx->loaded_vmcs->launched;
asm(
/* Store host registers */
"push %%" _ASM_DX "; push %%" _ASM_BP ";"
"push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
"push %%" _ASM_CX " \n\t"
"cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
"je 1f \n\t"
"mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
__ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
"1: \n\t"
/* Reload cr2 if changed */
"mov %c[cr2](%0), %%" _ASM_AX " \n\t"
"mov %%cr2, %%" _ASM_DX " \n\t"
"cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
"je 2f \n\t"
"mov %%" _ASM_AX", %%cr2 \n\t"
"2: \n\t"
/* Check if vmlaunch of vmresume is needed */
"cmpl $0, %c[launched](%0) \n\t"
/* Load guest registers. Don't clobber flags. */
"mov %c[rax](%0), %%" _ASM_AX " \n\t"
"mov %c[rbx](%0), %%" _ASM_BX " \n\t"
"mov %c[rdx](%0), %%" _ASM_DX " \n\t"
"mov %c[rsi](%0), %%" _ASM_SI " \n\t"
"mov %c[rdi](%0), %%" _ASM_DI " \n\t"
"mov %c[rbp](%0), %%" _ASM_BP " \n\t"
#ifdef CONFIG_X86_64
"mov %c[r8](%0), %%r8 \n\t"
"mov %c[r9](%0), %%r9 \n\t"
"mov %c[r10](%0), %%r10 \n\t"
"mov %c[r11](%0), %%r11 \n\t"
"mov %c[r12](%0), %%r12 \n\t"
"mov %c[r13](%0), %%r13 \n\t"
"mov %c[r14](%0), %%r14 \n\t"
"mov %c[r15](%0), %%r15 \n\t"
#endif
"mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
/* Enter guest mode */
"jne 1f \n\t"
__ex(ASM_VMX_VMLAUNCH) "\n\t"
"jmp 2f \n\t"
"1: " __ex(ASM_VMX_VMRESUME) "\n\t"
"2: "
/* Save guest registers, load host registers, keep flags */
"mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
"pop %0 \n\t"
"mov %%" _ASM_AX ", %c[rax](%0) \n\t"
"mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
__ASM_SIZE(pop) " %c[rcx](%0) \n\t"
"mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
"mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
"mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
"mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
#ifdef CONFIG_X86_64
"mov %%r8, %c[r8](%0) \n\t"
"mov %%r9, %c[r9](%0) \n\t"
"mov %%r10, %c[r10](%0) \n\t"
"mov %%r11, %c[r11](%0) \n\t"
"mov %%r12, %c[r12](%0) \n\t"
"mov %%r13, %c[r13](%0) \n\t"
"mov %%r14, %c[r14](%0) \n\t"
"mov %%r15, %c[r15](%0) \n\t"
#endif
"mov %%cr2, %%" _ASM_AX " \n\t"
"mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
"pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
"setbe %c[fail](%0) \n\t"
".pushsection .rodata \n\t"
".global vmx_return \n\t"
"vmx_return: " _ASM_PTR " 2b \n\t"
".popsection"
: : "c"(vmx), "d"((unsigned long)HOST_RSP),
[launched]"i"(offsetof(struct vcpu_vmx, __launched)),
[fail]"i"(offsetof(struct vcpu_vmx, fail)),
[host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
[rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
[rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
[rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
[rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
[rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
[rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
[rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
#ifdef CONFIG_X86_64
[r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
[r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
[r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
[r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
[r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
[r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
[r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
[r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
#endif
[cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
[wordsize]"i"(sizeof(ulong))
: "cc", "memory"
#ifdef CONFIG_X86_64
, "rax", "rbx", "rdi", "rsi"
, "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
#else
, "eax", "ebx", "edi", "esi"
#endif
);
/* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
if (debugctlmsr)
update_debugctlmsr(debugctlmsr);
#ifndef CONFIG_X86_64
/*
* The sysexit path does not restore ds/es, so we must set them to
* a reasonable value ourselves.
*
* We can't defer this to vmx_load_host_state() since that function
* may be executed in interrupt context, which saves and restore segments
* around it, nullifying its effect.
*/
loadsegment(ds, __USER_DS);
loadsegment(es, __USER_DS);
#endif
vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
| (1 << VCPU_EXREG_RFLAGS)
| (1 << VCPU_EXREG_PDPTR)
| (1 << VCPU_EXREG_SEGMENTS)
| (1 << VCPU_EXREG_CR3));
vcpu->arch.regs_dirty = 0;
vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
vmx->loaded_vmcs->launched = 1;
vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
/*
* eager fpu is enabled if PKEY is supported and CR4 is switched
* back on host, so it is safe to read guest PKRU from current
* XSAVE.
*/
if (boot_cpu_has(X86_FEATURE_OSPKE)) {
vmx->guest_pkru = __read_pkru();
if (vmx->guest_pkru != vmx->host_pkru) {
vmx->guest_pkru_valid = true;
__write_pkru(vmx->host_pkru);
} else
vmx->guest_pkru_valid = false;
}
/*
* the KVM_REQ_EVENT optimization bit is only on for one entry, and if
* we did not inject a still-pending event to L1 now because of
* nested_run_pending, we need to re-enable this bit.
*/
if (vmx->nested.nested_run_pending)
kvm_make_request(KVM_REQ_EVENT, vcpu);
vmx->nested.nested_run_pending = 0;
vmx_complete_atomic_exit(vmx);
vmx_recover_nmi_blocking(vmx);
vmx_complete_interrupts(vmx);
}
static void vmx_load_vmcs01(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int cpu;
if (vmx->loaded_vmcs == &vmx->vmcs01)
return;
cpu = get_cpu();
vmx->loaded_vmcs = &vmx->vmcs01;
vmx_vcpu_put(vcpu);
vmx_vcpu_load(vcpu, cpu);
vcpu->cpu = cpu;
put_cpu();
}
/*
* Ensure that the current vmcs of the logical processor is the
* vmcs01 of the vcpu before calling free_nested().
*/
static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int r;
r = vcpu_load(vcpu);
BUG_ON(r);
vmx_load_vmcs01(vcpu);
free_nested(vmx);
vcpu_put(vcpu);
}
static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (enable_pml)
vmx_destroy_pml_buffer(vmx);
free_vpid(vmx->vpid);
leave_guest_mode(vcpu);
vmx_free_vcpu_nested(vcpu);
free_loaded_vmcs(vmx->loaded_vmcs);
kfree(vmx->guest_msrs);
kvm_vcpu_uninit(vcpu);
kmem_cache_free(kvm_vcpu_cache, vmx);
}
static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
{
int err;
struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
int cpu;
if (!vmx)
return ERR_PTR(-ENOMEM);
vmx->vpid = allocate_vpid();
err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
if (err)
goto free_vcpu;
err = -ENOMEM;
/*
* If PML is turned on, failure on enabling PML just results in failure
* of creating the vcpu, therefore we can simplify PML logic (by
* avoiding dealing with cases, such as enabling PML partially on vcpus
* for the guest, etc.
*/
if (enable_pml) {
vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!vmx->pml_pg)
goto uninit_vcpu;
}
vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
> PAGE_SIZE);
if (!vmx->guest_msrs)
goto free_pml;
vmx->loaded_vmcs = &vmx->vmcs01;
vmx->loaded_vmcs->vmcs = alloc_vmcs();
vmx->loaded_vmcs->shadow_vmcs = NULL;
if (!vmx->loaded_vmcs->vmcs)
goto free_msrs;
if (!vmm_exclusive)
kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
loaded_vmcs_init(vmx->loaded_vmcs);
if (!vmm_exclusive)
kvm_cpu_vmxoff();
cpu = get_cpu();
vmx_vcpu_load(&vmx->vcpu, cpu);
vmx->vcpu.cpu = cpu;
err = vmx_vcpu_setup(vmx);
vmx_vcpu_put(&vmx->vcpu);
put_cpu();
if (err)
goto free_vmcs;
if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
err = alloc_apic_access_page(kvm);
if (err)
goto free_vmcs;
}
if (enable_ept) {
if (!kvm->arch.ept_identity_map_addr)
kvm->arch.ept_identity_map_addr =
VMX_EPT_IDENTITY_PAGETABLE_ADDR;
err = init_rmode_identity_map(kvm);
if (err)
goto free_vmcs;
}
if (nested) {
nested_vmx_setup_ctls_msrs(vmx);
vmx->nested.vpid02 = allocate_vpid();
}
vmx->nested.posted_intr_nv = -1;
vmx->nested.current_vmptr = -1ull;
vmx->nested.current_vmcs12 = NULL;
vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
return &vmx->vcpu;
free_vmcs:
free_vpid(vmx->nested.vpid02);
free_loaded_vmcs(vmx->loaded_vmcs);
free_msrs:
kfree(vmx->guest_msrs);
free_pml:
vmx_destroy_pml_buffer(vmx);
uninit_vcpu:
kvm_vcpu_uninit(&vmx->vcpu);
free_vcpu:
free_vpid(vmx->vpid);
kmem_cache_free(kvm_vcpu_cache, vmx);
return ERR_PTR(err);
}
static void __init vmx_check_processor_compat(void *rtn)
{
struct vmcs_config vmcs_conf;
*(int *)rtn = 0;
if (setup_vmcs_config(&vmcs_conf) < 0)
*(int *)rtn = -EIO;
if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
smp_processor_id());
*(int *)rtn = -EIO;
}
}
static int get_ept_level(void)
{
return VMX_EPT_DEFAULT_GAW + 1;
}
static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
{
u8 cache;
u64 ipat = 0;
/* For VT-d and EPT combination
* 1. MMIO: always map as UC
* 2. EPT with VT-d:
* a. VT-d without snooping control feature: can't guarantee the
* result, try to trust guest.
* b. VT-d with snooping control feature: snooping control feature of
* VT-d engine can guarantee the cache correctness. Just set it
* to WB to keep consistent with host. So the same as item 3.
* 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
* consistent with host MTRR
*/
if (is_mmio) {
cache = MTRR_TYPE_UNCACHABLE;
goto exit;
}
if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
ipat = VMX_EPT_IPAT_BIT;
cache = MTRR_TYPE_WRBACK;
goto exit;
}
if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
ipat = VMX_EPT_IPAT_BIT;
if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
cache = MTRR_TYPE_WRBACK;
else
cache = MTRR_TYPE_UNCACHABLE;
goto exit;
}
cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
exit:
return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
}
static int vmx_get_lpage_level(void)
{
if (enable_ept && !cpu_has_vmx_ept_1g_page())
return PT_DIRECTORY_LEVEL;
else
/* For shadow and EPT supported 1GB page */
return PT_PDPE_LEVEL;
}
static void vmcs_set_secondary_exec_control(u32 new_ctl)
{
/*
* These bits in the secondary execution controls field
* are dynamic, the others are mostly based on the hypervisor
* architecture and the guest's CPUID. Do not touch the
* dynamic bits.
*/
u32 mask =
SECONDARY_EXEC_SHADOW_VMCS |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
(new_ctl & ~mask) | (cur_ctl & mask));
}
/*
* Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
* (indicating "allowed-1") if they are supported in the guest's CPUID.
*/
static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_cpuid_entry2 *entry;
vmx->nested.nested_vmx_cr0_fixed1 = 0xffffffff;
vmx->nested.nested_vmx_cr4_fixed1 = X86_CR4_PCE;
#define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
if (entry && (entry->_reg & (_cpuid_mask))) \
vmx->nested.nested_vmx_cr4_fixed1 |= (_cr4_mask); \
} while (0)
entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
/* TODO: Use X86_CR4_UMIP and X86_FEATURE_UMIP macros */
cr4_fixed1_update(bit(11), ecx, bit(2));
#undef cr4_fixed1_update
}
static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
{
struct kvm_cpuid_entry2 *best;
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 secondary_exec_ctl = vmx_secondary_exec_control(vmx);
if (vmx_rdtscp_supported()) {
bool rdtscp_enabled = guest_cpuid_has_rdtscp(vcpu);
if (!rdtscp_enabled)
secondary_exec_ctl &= ~SECONDARY_EXEC_RDTSCP;
if (nested) {
if (rdtscp_enabled)
vmx->nested.nested_vmx_secondary_ctls_high |=
SECONDARY_EXEC_RDTSCP;
else
vmx->nested.nested_vmx_secondary_ctls_high &=
~SECONDARY_EXEC_RDTSCP;
}
}
/* Exposing INVPCID only when PCID is exposed */
best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
if (vmx_invpcid_supported() &&
(!best || !(best->ebx & bit(X86_FEATURE_INVPCID)) ||
!guest_cpuid_has_pcid(vcpu))) {
secondary_exec_ctl &= ~SECONDARY_EXEC_ENABLE_INVPCID;
if (best)
best->ebx &= ~bit(X86_FEATURE_INVPCID);
}
if (cpu_has_secondary_exec_ctrls())
vmcs_set_secondary_exec_control(secondary_exec_ctl);
if (nested_vmx_allowed(vcpu))
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
else
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
if (nested_vmx_allowed(vcpu))
nested_vmx_cr_fixed1_bits_update(vcpu);
}
static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
{
if (func == 1 && nested)
entry->ecx |= bit(X86_FEATURE_VMX);
}
static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
struct x86_exception *fault)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
u32 exit_reason;
if (fault->error_code & PFERR_RSVD_MASK)
exit_reason = EXIT_REASON_EPT_MISCONFIG;
else
exit_reason = EXIT_REASON_EPT_VIOLATION;
nested_vmx_vmexit(vcpu, exit_reason, 0, vcpu->arch.exit_qualification);
vmcs12->guest_physical_address = fault->address;
}
/* Callbacks for nested_ept_init_mmu_context: */
static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
{
/* return the page table to be shadowed - in our case, EPT12 */
return get_vmcs12(vcpu)->ept_pointer;
}
static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
{
WARN_ON(mmu_is_nested(vcpu));
kvm_init_shadow_ept_mmu(vcpu,
to_vmx(vcpu)->nested.nested_vmx_ept_caps &
VMX_EPT_EXECUTE_ONLY_BIT);
vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
}
static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
{
vcpu->arch.walk_mmu = &vcpu->arch.mmu;
}
static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
u16 error_code)
{
bool inequality, bit;
bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
inequality =
(error_code & vmcs12->page_fault_error_code_mask) !=
vmcs12->page_fault_error_code_match;
return inequality ^ bit;
}
static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
struct x86_exception *fault)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
WARN_ON(!is_guest_mode(vcpu));
if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code))
nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
vmcs_read32(VM_EXIT_INTR_INFO),
vmcs_readl(EXIT_QUALIFICATION));
else
kvm_inject_page_fault(vcpu, fault);
}
static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int maxphyaddr = cpuid_maxphyaddr(vcpu);
if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
if (!PAGE_ALIGNED(vmcs12->apic_access_addr) ||
vmcs12->apic_access_addr >> maxphyaddr)
return false;
/*
* Translate L1 physical address to host physical
* address for vmcs02. Keep the page pinned, so this
* physical address remains valid. We keep a reference
* to it so we can release it later.
*/
if (vmx->nested.apic_access_page) /* shouldn't happen */
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page =
nested_get_page(vcpu, vmcs12->apic_access_addr);
}
if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
if (!PAGE_ALIGNED(vmcs12->virtual_apic_page_addr) ||
vmcs12->virtual_apic_page_addr >> maxphyaddr)
return false;
if (vmx->nested.virtual_apic_page) /* shouldn't happen */
nested_release_page(vmx->nested.virtual_apic_page);
vmx->nested.virtual_apic_page =
nested_get_page(vcpu, vmcs12->virtual_apic_page_addr);
/*
* Failing the vm entry is _not_ what the processor does
* but it's basically the only possibility we have.
* We could still enter the guest if CR8 load exits are
* enabled, CR8 store exits are enabled, and virtualize APIC
* access is disabled; in this case the processor would never
* use the TPR shadow and we could simply clear the bit from
* the execution control. But such a configuration is useless,
* so let's keep the code simple.
*/
if (!vmx->nested.virtual_apic_page)
return false;
}
if (nested_cpu_has_posted_intr(vmcs12)) {
if (!IS_ALIGNED(vmcs12->posted_intr_desc_addr, 64) ||
vmcs12->posted_intr_desc_addr >> maxphyaddr)
return false;
if (vmx->nested.pi_desc_page) { /* shouldn't happen */
kunmap(vmx->nested.pi_desc_page);
nested_release_page(vmx->nested.pi_desc_page);
}
vmx->nested.pi_desc_page =
nested_get_page(vcpu, vmcs12->posted_intr_desc_addr);
if (!vmx->nested.pi_desc_page)
return false;
vmx->nested.pi_desc =
(struct pi_desc *)kmap(vmx->nested.pi_desc_page);
if (!vmx->nested.pi_desc) {
nested_release_page_clean(vmx->nested.pi_desc_page);
return false;
}
vmx->nested.pi_desc =
(struct pi_desc *)((void *)vmx->nested.pi_desc +
(unsigned long)(vmcs12->posted_intr_desc_addr &
(PAGE_SIZE - 1)));
}
return true;
}
static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
{
u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (vcpu->arch.virtual_tsc_khz == 0)
return;
/* Make sure short timeouts reliably trigger an immediate vmexit.
* hrtimer_start does not guarantee this. */
if (preemption_timeout <= 1) {
vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
return;
}
preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
preemption_timeout *= 1000000;
do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
hrtimer_start(&vmx->nested.preemption_timer,
ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
}
static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
int maxphyaddr;
u64 addr;
if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
return 0;
if (vmcs12_read_any(vcpu, MSR_BITMAP, &addr)) {
WARN_ON(1);
return -EINVAL;
}
maxphyaddr = cpuid_maxphyaddr(vcpu);
if (!PAGE_ALIGNED(vmcs12->msr_bitmap) ||
((addr + PAGE_SIZE) >> maxphyaddr))
return -EINVAL;
return 0;
}
/*
* Merge L0's and L1's MSR bitmap, return false to indicate that
* we do not use the hardware.
*/
static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
int msr;
struct page *page;
unsigned long *msr_bitmap_l1;
unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.msr_bitmap;
/* This shortcut is ok because we support only x2APIC MSRs so far. */
if (!nested_cpu_has_virt_x2apic_mode(vmcs12))
return false;
page = nested_get_page(vcpu, vmcs12->msr_bitmap);
if (!page) {
WARN_ON(1);
return false;
}
msr_bitmap_l1 = (unsigned long *)kmap(page);
if (!msr_bitmap_l1) {
nested_release_page_clean(page);
WARN_ON(1);
return false;
}
memset(msr_bitmap_l0, 0xff, PAGE_SIZE);
if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
if (nested_cpu_has_apic_reg_virt(vmcs12))
for (msr = 0x800; msr <= 0x8ff; msr++)
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
msr, MSR_TYPE_R);
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
APIC_BASE_MSR + (APIC_TASKPRI >> 4),
MSR_TYPE_R | MSR_TYPE_W);
if (nested_cpu_has_vid(vmcs12)) {
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
APIC_BASE_MSR + (APIC_EOI >> 4),
MSR_TYPE_W);
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
MSR_TYPE_W);
}
}
kunmap(page);
nested_release_page_clean(page);
return true;
}
static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
!nested_cpu_has_apic_reg_virt(vmcs12) &&
!nested_cpu_has_vid(vmcs12) &&
!nested_cpu_has_posted_intr(vmcs12))
return 0;
/*
* If virtualize x2apic mode is enabled,
* virtualize apic access must be disabled.
*/
if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
return -EINVAL;
/*
* If virtual interrupt delivery is enabled,
* we must exit on external interrupts.
*/
if (nested_cpu_has_vid(vmcs12) &&
!nested_exit_on_intr(vcpu))
return -EINVAL;
/*
* bits 15:8 should be zero in posted_intr_nv,
* the descriptor address has been already checked
* in nested_get_vmcs12_pages.
*/
if (nested_cpu_has_posted_intr(vmcs12) &&
(!nested_cpu_has_vid(vmcs12) ||
!nested_exit_intr_ack_set(vcpu) ||
vmcs12->posted_intr_nv & 0xff00))
return -EINVAL;
/* tpr shadow is needed by all apicv features. */
if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
return -EINVAL;
return 0;
}
static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
unsigned long count_field,
unsigned long addr_field)
{
int maxphyaddr;
u64 count, addr;
if (vmcs12_read_any(vcpu, count_field, &count) ||
vmcs12_read_any(vcpu, addr_field, &addr)) {
WARN_ON(1);
return -EINVAL;
}
if (count == 0)
return 0;
maxphyaddr = cpuid_maxphyaddr(vcpu);
if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
(addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
pr_debug_ratelimited(
"nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
addr_field, maxphyaddr, count, addr);
return -EINVAL;
}
return 0;
}
static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
if (vmcs12->vm_exit_msr_load_count == 0 &&
vmcs12->vm_exit_msr_store_count == 0 &&
vmcs12->vm_entry_msr_load_count == 0)
return 0; /* Fast path */
if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
VM_EXIT_MSR_LOAD_ADDR) ||
nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
VM_EXIT_MSR_STORE_ADDR) ||
nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
VM_ENTRY_MSR_LOAD_ADDR))
return -EINVAL;
return 0;
}
static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
struct vmx_msr_entry *e)
{
/* x2APIC MSR accesses are not allowed */
if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
return -EINVAL;
if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
e->index == MSR_IA32_UCODE_REV)
return -EINVAL;
if (e->reserved != 0)
return -EINVAL;
return 0;
}
static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
struct vmx_msr_entry *e)
{
if (e->index == MSR_FS_BASE ||
e->index == MSR_GS_BASE ||
e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
nested_vmx_msr_check_common(vcpu, e))
return -EINVAL;
return 0;
}
static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
struct vmx_msr_entry *e)
{
if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
nested_vmx_msr_check_common(vcpu, e))
return -EINVAL;
return 0;
}
/*
* Load guest's/host's msr at nested entry/exit.
* return 0 for success, entry index for failure.
*/
static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
{
u32 i;
struct vmx_msr_entry e;
struct msr_data msr;
msr.host_initiated = false;
for (i = 0; i < count; i++) {
if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
&e, sizeof(e))) {
pr_debug_ratelimited(
"%s cannot read MSR entry (%u, 0x%08llx)\n",
__func__, i, gpa + i * sizeof(e));
goto fail;
}
if (nested_vmx_load_msr_check(vcpu, &e)) {
pr_debug_ratelimited(
"%s check failed (%u, 0x%x, 0x%x)\n",
__func__, i, e.index, e.reserved);
goto fail;
}
msr.index = e.index;
msr.data = e.value;
if (kvm_set_msr(vcpu, &msr)) {
pr_debug_ratelimited(
"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
__func__, i, e.index, e.value);
goto fail;
}
}
return 0;
fail:
return i + 1;
}
static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
{
u32 i;
struct vmx_msr_entry e;
for (i = 0; i < count; i++) {
struct msr_data msr_info;
if (kvm_vcpu_read_guest(vcpu,
gpa + i * sizeof(e),
&e, 2 * sizeof(u32))) {
pr_debug_ratelimited(
"%s cannot read MSR entry (%u, 0x%08llx)\n",
__func__, i, gpa + i * sizeof(e));
return -EINVAL;
}
if (nested_vmx_store_msr_check(vcpu, &e)) {
pr_debug_ratelimited(
"%s check failed (%u, 0x%x, 0x%x)\n",
__func__, i, e.index, e.reserved);
return -EINVAL;
}
msr_info.host_initiated = false;
msr_info.index = e.index;
if (kvm_get_msr(vcpu, &msr_info)) {
pr_debug_ratelimited(
"%s cannot read MSR (%u, 0x%x)\n",
__func__, i, e.index);
return -EINVAL;
}
if (kvm_vcpu_write_guest(vcpu,
gpa + i * sizeof(e) +
offsetof(struct vmx_msr_entry, value),
&msr_info.data, sizeof(msr_info.data))) {
pr_debug_ratelimited(
"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
__func__, i, e.index, msr_info.data);
return -EINVAL;
}
}
return 0;
}
static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
{
unsigned long invalid_mask;
invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
return (val & invalid_mask) == 0;
}
/*
* Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
* emulating VM entry into a guest with EPT enabled.
* Returns 0 on success, 1 on failure. Invalid state exit qualification code
* is assigned to entry_failure_code on failure.
*/
static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
unsigned long *entry_failure_code)
{
if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
if (!nested_cr3_valid(vcpu, cr3)) {
*entry_failure_code = ENTRY_FAIL_DEFAULT;
return 1;
}
/*
* If PAE paging and EPT are both on, CR3 is not used by the CPU and
* must not be dereferenced.
*/
if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
!nested_ept) {
if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
*entry_failure_code = ENTRY_FAIL_PDPTE;
return 1;
}
}
vcpu->arch.cr3 = cr3;
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
}
kvm_mmu_reset_context(vcpu);
return 0;
}
/*
* prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
* L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
* with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
* guest in a way that will both be appropriate to L1's requests, and our
* needs. In addition to modifying the active vmcs (which is vmcs02), this
* function also has additional necessary side-effects, like setting various
* vcpu->arch fields.
* Returns 0 on success, 1 on failure. Invalid state exit qualification code
* is assigned to entry_failure_code on failure.
*/
static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
unsigned long *entry_failure_code)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 exec_control;
bool nested_ept_enabled = false;
vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
} else {
kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
}
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
vmcs12->vm_entry_intr_info_field);
vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
vmcs12->vm_entry_exception_error_code);
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmcs12->vm_entry_instruction_len);
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
vmcs12->guest_interruptibility_info);
vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
vmx_set_rflags(vcpu, vmcs12->guest_rflags);
vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
vmcs12->guest_pending_dbg_exceptions);
vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
if (nested_cpu_has_xsaves(vmcs12))
vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
vmcs_write64(VMCS_LINK_POINTER, -1ull);
exec_control = vmcs12->pin_based_vm_exec_control;
/* Preemption timer setting is only taken from vmcs01. */
exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
exec_control |= vmcs_config.pin_based_exec_ctrl;
if (vmx->hv_deadline_tsc == -1)
exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
/* Posted interrupts setting is only taken from vmcs12. */
if (nested_cpu_has_posted_intr(vmcs12)) {
/*
* Note that we use L0's vector here and in
* vmx_deliver_nested_posted_interrupt.
*/
vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
vmx->nested.pi_pending = false;
vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
vmcs_write64(POSTED_INTR_DESC_ADDR,
page_to_phys(vmx->nested.pi_desc_page) +
(unsigned long)(vmcs12->posted_intr_desc_addr &
(PAGE_SIZE - 1)));
} else
exec_control &= ~PIN_BASED_POSTED_INTR;
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
vmx->nested.preemption_timer_expired = false;
if (nested_cpu_has_preemption_timer(vmcs12))
vmx_start_preemption_timer(vcpu);
/*
* Whether page-faults are trapped is determined by a combination of
* 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
* If enable_ept, L0 doesn't care about page faults and we should
* set all of these to L1's desires. However, if !enable_ept, L0 does
* care about (at least some) page faults, and because it is not easy
* (if at all possible?) to merge L0 and L1's desires, we simply ask
* to exit on each and every L2 page fault. This is done by setting
* MASK=MATCH=0 and (see below) EB.PF=1.
* Note that below we don't need special code to set EB.PF beyond the
* "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
* vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
* !enable_ept, EB.PF is 1, so the "or" will always be 1.
*
* A problem with this approach (when !enable_ept) is that L1 may be
* injected with more page faults than it asked for. This could have
* caused problems, but in practice existing hypervisors don't care.
* To fix this, we will need to emulate the PFEC checking (on the L1
* page tables), using walk_addr(), when injecting PFs to L1.
*/
vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
enable_ept ? vmcs12->page_fault_error_code_mask : 0);
vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
enable_ept ? vmcs12->page_fault_error_code_match : 0);
if (cpu_has_secondary_exec_ctrls()) {
exec_control = vmx_secondary_exec_control(vmx);
/* Take the following fields only from vmcs12 */
exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
SECONDARY_EXEC_RDTSCP |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
SECONDARY_EXEC_APIC_REGISTER_VIRT);
if (nested_cpu_has(vmcs12,
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
exec_control |= vmcs12->secondary_vm_exec_control;
if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
/*
* If translation failed, no matter: This feature asks
* to exit when accessing the given address, and if it
* can never be accessed, this feature won't do
* anything anyway.
*/
if (!vmx->nested.apic_access_page)
exec_control &=
~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
else
vmcs_write64(APIC_ACCESS_ADDR,
page_to_phys(vmx->nested.apic_access_page));
} else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
exec_control |=
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
kvm_vcpu_reload_apic_access_page(vcpu);
}
if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
vmcs_write64(EOI_EXIT_BITMAP0,
vmcs12->eoi_exit_bitmap0);
vmcs_write64(EOI_EXIT_BITMAP1,
vmcs12->eoi_exit_bitmap1);
vmcs_write64(EOI_EXIT_BITMAP2,
vmcs12->eoi_exit_bitmap2);
vmcs_write64(EOI_EXIT_BITMAP3,
vmcs12->eoi_exit_bitmap3);
vmcs_write16(GUEST_INTR_STATUS,
vmcs12->guest_intr_status);
}
nested_ept_enabled = (exec_control & SECONDARY_EXEC_ENABLE_EPT) != 0;
vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
}
/*
* Set host-state according to L0's settings (vmcs12 is irrelevant here)
* Some constant fields are set here by vmx_set_constant_host_state().
* Other fields are different per CPU, and will be set later when
* vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
*/
vmx_set_constant_host_state(vmx);
/*
* Set the MSR load/store lists to match L0's settings.
*/
vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
/*
* HOST_RSP is normally set correctly in vmx_vcpu_run() just before
* entry, but only if the current (host) sp changed from the value
* we wrote last (vmx->host_rsp). This cache is no longer relevant
* if we switch vmcs, and rather than hold a separate cache per vmcs,
* here we just force the write to happen on entry.
*/
vmx->host_rsp = 0;
exec_control = vmx_exec_control(vmx); /* L0's desires */
exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
exec_control &= ~CPU_BASED_TPR_SHADOW;
exec_control |= vmcs12->cpu_based_vm_exec_control;
if (exec_control & CPU_BASED_TPR_SHADOW) {
vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
page_to_phys(vmx->nested.virtual_apic_page));
vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
}
if (cpu_has_vmx_msr_bitmap() &&
exec_control & CPU_BASED_USE_MSR_BITMAPS &&
nested_vmx_merge_msr_bitmap(vcpu, vmcs12))
; /* MSR_BITMAP will be set by following vmx_set_efer. */
else
exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
/*
* Merging of IO bitmap not currently supported.
* Rather, exit every time.
*/
exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
exec_control |= CPU_BASED_UNCOND_IO_EXITING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
/* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
* bitwise-or of what L1 wants to trap for L2, and what we want to
* trap. Note that CR0.TS also needs updating - we do this later.
*/
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
/* L2->L1 exit controls are emulated - the hardware exit is to L0 so
* we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
* bits are further modified by vmx_set_efer() below.
*/
vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
/* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
* emulated by vmx_set_efer(), below.
*/
vm_entry_controls_init(vmx,
(vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
~VM_ENTRY_IA32E_MODE) |
(vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) {
vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
vcpu->arch.pat = vmcs12->guest_ia32_pat;
} else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
set_cr4_guest_host_mask(vmx);
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
vmcs_write64(TSC_OFFSET,
vcpu->arch.tsc_offset + vmcs12->tsc_offset);
else
vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
if (kvm_has_tsc_control)
decache_tsc_multiplier(vmx);
if (enable_vpid) {
/*
* There is no direct mapping between vpid02 and vpid12, the
* vpid02 is per-vCPU for L0 and reused while the value of
* vpid12 is changed w/ one invvpid during nested vmentry.
* The vpid12 is allocated by L1 for L2, so it will not
* influence global bitmap(for vpid01 and vpid02 allocation)
* even if spawn a lot of nested vCPUs.
*/
if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
vmx->nested.last_vpid = vmcs12->virtual_processor_id;
__vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
}
} else {
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
vmx_flush_tlb(vcpu);
}
}
if (nested_cpu_has_ept(vmcs12)) {
kvm_mmu_unload(vcpu);
nested_ept_init_mmu_context(vcpu);
}
/*
* This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
* TS bit (for lazy fpu) and bits which we consider mandatory enabled.
* The CR0_READ_SHADOW is what L2 should have expected to read given
* the specifications by L1; It's not enough to take
* vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
* have more bits than L1 expected.
*/
vmx_set_cr0(vcpu, vmcs12->guest_cr0);
vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
vmx_set_cr4(vcpu, vmcs12->guest_cr4);
vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
vcpu->arch.efer = vmcs12->guest_ia32_efer;
else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
vcpu->arch.efer |= (EFER_LMA | EFER_LME);
else
vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
/* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
vmx_set_efer(vcpu, vcpu->arch.efer);
/* Shadow page tables on either EPT or shadow page tables. */
if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_ept_enabled,
entry_failure_code))
return 1;
kvm_mmu_reset_context(vcpu);
if (!enable_ept)
vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
/*
* L1 may access the L2's PDPTR, so save them to construct vmcs12
*/
if (enable_ept) {
vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
}
kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
return 0;
}
/*
* nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
* for running an L2 nested guest.
*/
static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
{
struct vmcs12 *vmcs12;
struct vcpu_vmx *vmx = to_vmx(vcpu);
int cpu;
struct loaded_vmcs *vmcs02;
bool ia32e;
u32 msr_entry_idx;
unsigned long exit_qualification;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
goto out;
vmcs12 = get_vmcs12(vcpu);
if (enable_shadow_vmcs)
copy_shadow_to_vmcs12(vmx);
/*
* The nested entry process starts with enforcing various prerequisites
* on vmcs12 as required by the Intel SDM, and act appropriately when
* they fail: As the SDM explains, some conditions should cause the
* instruction to fail, while others will cause the instruction to seem
* to succeed, but return an EXIT_REASON_INVALID_STATE.
* To speed up the normal (success) code path, we should avoid checking
* for misconfigurations which will anyway be caught by the processor
* when using the merged vmcs02.
*/
if (vmcs12->launch_state == launch) {
nested_vmx_failValid(vcpu,
launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
: VMXERR_VMRESUME_NONLAUNCHED_VMCS);
goto out;
}
if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (!nested_get_vmcs12_pages(vcpu, vmcs12)) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12)) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (nested_vmx_check_apicv_controls(vcpu, vmcs12)) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12)) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
vmx->nested.nested_vmx_procbased_ctls_low,
vmx->nested.nested_vmx_procbased_ctls_high) ||
!vmx_control_verify(vmcs12->secondary_vm_exec_control,
vmx->nested.nested_vmx_secondary_ctls_low,
vmx->nested.nested_vmx_secondary_ctls_high) ||
!vmx_control_verify(vmcs12->pin_based_vm_exec_control,
vmx->nested.nested_vmx_pinbased_ctls_low,
vmx->nested.nested_vmx_pinbased_ctls_high) ||
!vmx_control_verify(vmcs12->vm_exit_controls,
vmx->nested.nested_vmx_exit_ctls_low,
vmx->nested.nested_vmx_exit_ctls_high) ||
!vmx_control_verify(vmcs12->vm_entry_controls,
vmx->nested.nested_vmx_entry_ctls_low,
vmx->nested.nested_vmx_entry_ctls_high))
{
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
goto out;
}
if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
!nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
!nested_cr3_valid(vcpu, vmcs12->host_cr3)) {
nested_vmx_failValid(vcpu,
VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
goto out;
}
if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
!nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4)) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
goto out;
}
if (vmcs12->vmcs_link_pointer != -1ull) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
goto out;
}
/*
* If the load IA32_EFER VM-entry control is 1, the following checks
* are performed on the field for the IA32_EFER MSR:
* - Bits reserved in the IA32_EFER MSR must be 0.
* - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
* the IA-32e mode guest VM-exit control. It must also be identical
* to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
* CR0.PG) is 1.
*/
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) {
ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
((vmcs12->guest_cr0 & X86_CR0_PG) &&
ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
goto out;
}
}
/*
* If the load IA32_EFER VM-exit control is 1, bits reserved in the
* IA32_EFER MSR must be 0 in the field for that register. In addition,
* the values of the LMA and LME bits in the field must each be that of
* the host address-space size VM-exit control.
*/
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
ia32e = (vmcs12->vm_exit_controls &
VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
goto out;
}
}
/*
* We're finally done with prerequisite checking, and can start with
* the nested entry.
*/
vmcs02 = nested_get_current_vmcs02(vmx);
if (!vmcs02)
return -ENOMEM;
/*
* After this point, the trap flag no longer triggers a singlestep trap
* on the vm entry instructions. Don't call
* kvm_skip_emulated_instruction.
*/
skip_emulated_instruction(vcpu);
enter_guest_mode(vcpu);
if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
cpu = get_cpu();
vmx->loaded_vmcs = vmcs02;
vmx_vcpu_put(vcpu);
vmx_vcpu_load(vcpu, cpu);
vcpu->cpu = cpu;
put_cpu();
vmx_segment_cache_clear(vmx);
if (prepare_vmcs02(vcpu, vmcs12, &exit_qualification)) {
leave_guest_mode(vcpu);
vmx_load_vmcs01(vcpu);
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, exit_qualification);
return 1;
}
msr_entry_idx = nested_vmx_load_msr(vcpu,
vmcs12->vm_entry_msr_load_addr,
vmcs12->vm_entry_msr_load_count);
if (msr_entry_idx) {
leave_guest_mode(vcpu);
vmx_load_vmcs01(vcpu);
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
return 1;
}
vmcs12->launch_state = 1;
if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
return kvm_vcpu_halt(vcpu);
vmx->nested.nested_run_pending = 1;
/*
* Note no nested_vmx_succeed or nested_vmx_fail here. At this point
* we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
* returned as far as L1 is concerned. It will only return (and set
* the success flag) when L2 exits (see nested_vmx_vmexit()).
*/
return 1;
out:
return kvm_skip_emulated_instruction(vcpu);
}
/*
* On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
* because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
* This function returns the new value we should put in vmcs12.guest_cr0.
* It's not enough to just return the vmcs02 GUEST_CR0. Rather,
* 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
* available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
* didn't trap the bit, because if L1 did, so would L0).
* 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
* been modified by L2, and L1 knows it. So just leave the old value of
* the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
* isn't relevant, because if L0 traps this bit it can set it to anything.
* 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
* changed these bits, and therefore they need to be updated, but L0
* didn't necessarily allow them to be changed in GUEST_CR0 - and rather
* put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
*/
static inline unsigned long
vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
{
return
/*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
/*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
/*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
vcpu->arch.cr0_guest_owned_bits));
}
static inline unsigned long
vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
{
return
/*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
/*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
/*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
vcpu->arch.cr4_guest_owned_bits));
}
static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
u32 idt_vectoring;
unsigned int nr;
if (vcpu->arch.exception.pending && vcpu->arch.exception.reinject) {
nr = vcpu->arch.exception.nr;
idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
if (kvm_exception_is_soft(nr)) {
vmcs12->vm_exit_instruction_len =
vcpu->arch.event_exit_inst_len;
idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
} else
idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
if (vcpu->arch.exception.has_error_code) {
idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
vmcs12->idt_vectoring_error_code =
vcpu->arch.exception.error_code;
}
vmcs12->idt_vectoring_info_field = idt_vectoring;
} else if (vcpu->arch.nmi_injected) {
vmcs12->idt_vectoring_info_field =
INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
} else if (vcpu->arch.interrupt.pending) {
nr = vcpu->arch.interrupt.nr;
idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
if (vcpu->arch.interrupt.soft) {
idt_vectoring |= INTR_TYPE_SOFT_INTR;
vmcs12->vm_entry_instruction_len =
vcpu->arch.event_exit_inst_len;
} else
idt_vectoring |= INTR_TYPE_EXT_INTR;
vmcs12->idt_vectoring_info_field = idt_vectoring;
}
}
static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
vmx->nested.preemption_timer_expired) {
if (vmx->nested.nested_run_pending)
return -EBUSY;
nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
return 0;
}
if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
if (vmx->nested.nested_run_pending ||
vcpu->arch.interrupt.pending)
return -EBUSY;
nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
NMI_VECTOR | INTR_TYPE_NMI_INTR |
INTR_INFO_VALID_MASK, 0);
/*
* The NMI-triggered VM exit counts as injection:
* clear this one and block further NMIs.
*/
vcpu->arch.nmi_pending = 0;
vmx_set_nmi_mask(vcpu, true);
return 0;
}
if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
nested_exit_on_intr(vcpu)) {
if (vmx->nested.nested_run_pending)
return -EBUSY;
nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
return 0;
}
return vmx_complete_nested_posted_interrupt(vcpu);
}
static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
{
ktime_t remaining =
hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
u64 value;
if (ktime_to_ns(remaining) <= 0)
return 0;
value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
do_div(value, 1000000);
return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
}
/*
* prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
* and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
* and this function updates it to reflect the changes to the guest state while
* L2 was running (and perhaps made some exits which were handled directly by L0
* without going back to L1), and to reflect the exit reason.
* Note that we do not have to copy here all VMCS fields, just those that
* could have changed by the L2 guest or the exit - i.e., the guest-state and
* exit-information fields only. Other fields are modified by L1 with VMWRITE,
* which already writes to vmcs12 directly.
*/
static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
u32 exit_reason, u32 exit_intr_info,
unsigned long exit_qualification)
{
/* update guest state fields: */
vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
vmcs12->guest_interruptibility_info =
vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
vmcs12->guest_pending_dbg_exceptions =
vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
else
vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
if (nested_cpu_has_preemption_timer(vmcs12)) {
if (vmcs12->vm_exit_controls &
VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
vmcs12->vmx_preemption_timer_value =
vmx_get_preemption_timer_value(vcpu);
hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
}
/*
* In some cases (usually, nested EPT), L2 is allowed to change its
* own CR3 without exiting. If it has changed it, we must keep it.
* Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
* by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
*
* Additionally, restore L2's PDPTR to vmcs12.
*/
if (enable_ept) {
vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
}
if (nested_cpu_has_ept(vmcs12))
vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
if (nested_cpu_has_vid(vmcs12))
vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
vmcs12->vm_entry_controls =
(vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
(vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
}
/* TODO: These cannot have changed unless we have MSR bitmaps and
* the relevant bit asks not to trap the change */
if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
vmcs12->guest_ia32_efer = vcpu->arch.efer;
vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
if (kvm_mpx_supported())
vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
if (nested_cpu_has_xsaves(vmcs12))
vmcs12->xss_exit_bitmap = vmcs_read64(XSS_EXIT_BITMAP);
/* update exit information fields: */
vmcs12->vm_exit_reason = exit_reason;
vmcs12->exit_qualification = exit_qualification;
vmcs12->vm_exit_intr_info = exit_intr_info;
if ((vmcs12->vm_exit_intr_info &
(INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
(INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK))
vmcs12->vm_exit_intr_error_code =
vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
vmcs12->idt_vectoring_info_field = 0;
vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
/* vm_entry_intr_info_field is cleared on exit. Emulate this
* instead of reading the real value. */
vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
/*
* Transfer the event that L0 or L1 may wanted to inject into
* L2 to IDT_VECTORING_INFO_FIELD.
*/
vmcs12_save_pending_event(vcpu, vmcs12);
}
/*
* Drop what we picked up for L2 via vmx_complete_interrupts. It is
* preserved above and would only end up incorrectly in L1.
*/
vcpu->arch.nmi_injected = false;
kvm_clear_exception_queue(vcpu);
kvm_clear_interrupt_queue(vcpu);
}
/*
* A part of what we need to when the nested L2 guest exits and we want to
* run its L1 parent, is to reset L1's guest state to the host state specified
* in vmcs12.
* This function is to be called not only on normal nested exit, but also on
* a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
* Failures During or After Loading Guest State").
* This function should be called when the active VMCS is L1's (vmcs01).
*/
static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
struct kvm_segment seg;
unsigned long entry_failure_code;
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
vcpu->arch.efer = vmcs12->host_ia32_efer;
else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
vcpu->arch.efer |= (EFER_LMA | EFER_LME);
else
vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
vmx_set_efer(vcpu, vcpu->arch.efer);
kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
/*
* Note that calling vmx_set_cr0 is important, even if cr0 hasn't
* actually changed, because it depends on the current state of
* fpu_active (which may have changed).
* Note that vmx_set_cr0 refers to efer set above.
*/
vmx_set_cr0(vcpu, vmcs12->host_cr0);
/*
* If we did fpu_activate()/fpu_deactivate() during L2's run, we need
* to apply the same changes to L1's vmcs. We just set cr0 correctly,
* but we also need to update cr0_guest_host_mask and exception_bitmap.
*/
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
/*
* Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
* (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
*/
vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
kvm_set_cr4(vcpu, vmcs12->host_cr4);
nested_ept_uninit_mmu_context(vcpu);
/*
* Only PDPTE load can fail as the value of cr3 was checked on entry and
* couldn't have changed.
*/
if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
if (!enable_ept)
vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
if (enable_vpid) {
/*
* Trivially support vpid by letting L2s share their parent
* L1's vpid. TODO: move to a more elaborate solution, giving
* each L2 its own vpid and exposing the vpid feature to L1.
*/
vmx_flush_tlb(vcpu);
}
vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
/* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
vmcs_write64(GUEST_BNDCFGS, 0);
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
vcpu->arch.pat = vmcs12->host_ia32_pat;
}
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
vmcs12->host_ia32_perf_global_ctrl);
/* Set L1 segment info according to Intel SDM
27.5.2 Loading Host Segment and Descriptor-Table Registers */
seg = (struct kvm_segment) {
.base = 0,
.limit = 0xFFFFFFFF,
.selector = vmcs12->host_cs_selector,
.type = 11,
.present = 1,
.s = 1,
.g = 1
};
if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
seg.l = 1;
else
seg.db = 1;
vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
seg = (struct kvm_segment) {
.base = 0,
.limit = 0xFFFFFFFF,
.type = 3,
.present = 1,
.s = 1,
.db = 1,
.g = 1
};
seg.selector = vmcs12->host_ds_selector;
vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
seg.selector = vmcs12->host_es_selector;
vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
seg.selector = vmcs12->host_ss_selector;
vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
seg.selector = vmcs12->host_fs_selector;
seg.base = vmcs12->host_fs_base;
vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
seg.selector = vmcs12->host_gs_selector;
seg.base = vmcs12->host_gs_base;
vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
seg = (struct kvm_segment) {
.base = vmcs12->host_tr_base,
.limit = 0x67,
.selector = vmcs12->host_tr_selector,
.type = 11,
.present = 1
};
vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
kvm_set_dr(vcpu, 7, 0x400);
vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
if (cpu_has_vmx_msr_bitmap())
vmx_set_msr_bitmap(vcpu);
if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
vmcs12->vm_exit_msr_load_count))
nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
}
/*
* Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
* and modify vmcs12 to make it see what it would expect to see there if
* L2 was its real guest. Must only be called when in L2 (is_guest_mode())
*/
static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
u32 exit_intr_info,
unsigned long exit_qualification)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
u32 vm_inst_error = 0;
/* trying to cancel vmlaunch/vmresume is a bug */
WARN_ON_ONCE(vmx->nested.nested_run_pending);
leave_guest_mode(vcpu);
prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
exit_qualification);
if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
vmcs12->vm_exit_msr_store_count))
nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
if (unlikely(vmx->fail))
vm_inst_error = vmcs_read32(VM_INSTRUCTION_ERROR);
vmx_load_vmcs01(vcpu);
if ((exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
&& nested_exit_intr_ack_set(vcpu)) {
int irq = kvm_cpu_get_interrupt(vcpu);
WARN_ON(irq < 0);
vmcs12->vm_exit_intr_info = irq |
INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
}
trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
vmcs12->exit_qualification,
vmcs12->idt_vectoring_info_field,
vmcs12->vm_exit_intr_info,
vmcs12->vm_exit_intr_error_code,
KVM_ISA_VMX);
vm_entry_controls_reset_shadow(vmx);
vm_exit_controls_reset_shadow(vmx);
vmx_segment_cache_clear(vmx);
/* if no vmcs02 cache requested, remove the one we used */
if (VMCS02_POOL_SIZE == 0)
nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
load_vmcs12_host_state(vcpu, vmcs12);
/* Update any VMCS fields that might have changed while L2 ran */
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
if (vmx->hv_deadline_tsc == -1)
vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
PIN_BASED_VMX_PREEMPTION_TIMER);
else
vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
PIN_BASED_VMX_PREEMPTION_TIMER);
if (kvm_has_tsc_control)
decache_tsc_multiplier(vmx);
if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
vmx_set_virtual_x2apic_mode(vcpu,
vcpu->arch.apic_base & X2APIC_ENABLE);
}
/* This is needed for same reason as it was needed in prepare_vmcs02 */
vmx->host_rsp = 0;
/* Unpin physical memory we referred to in vmcs02 */
if (vmx->nested.apic_access_page) {
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page = NULL;
}
if (vmx->nested.virtual_apic_page) {
nested_release_page(vmx->nested.virtual_apic_page);
vmx->nested.virtual_apic_page = NULL;
}
if (vmx->nested.pi_desc_page) {
kunmap(vmx->nested.pi_desc_page);
nested_release_page(vmx->nested.pi_desc_page);
vmx->nested.pi_desc_page = NULL;
vmx->nested.pi_desc = NULL;
}
/*
* We are now running in L2, mmu_notifier will force to reload the
* page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
*/
kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
/*
* Exiting from L2 to L1, we're now back to L1 which thinks it just
* finished a VMLAUNCH or VMRESUME instruction, so we need to set the
* success or failure flag accordingly.
*/
if (unlikely(vmx->fail)) {
vmx->fail = 0;
nested_vmx_failValid(vcpu, vm_inst_error);
} else
nested_vmx_succeed(vcpu);
if (enable_shadow_vmcs)
vmx->nested.sync_shadow_vmcs = true;
/* in case we halted in L2 */
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
}
/*
* Forcibly leave nested mode in order to be able to reset the VCPU later on.
*/
static void vmx_leave_nested(struct kvm_vcpu *vcpu)
{
if (is_guest_mode(vcpu))
nested_vmx_vmexit(vcpu, -1, 0, 0);
free_nested(to_vmx(vcpu));
}
/*
* L1's failure to enter L2 is a subset of a normal exit, as explained in
* 23.7 "VM-entry failures during or after loading guest state" (this also
* lists the acceptable exit-reason and exit-qualification parameters).
* It should only be called before L2 actually succeeded to run, and when
* vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
*/
static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12,
u32 reason, unsigned long qualification)
{
load_vmcs12_host_state(vcpu, vmcs12);
vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
vmcs12->exit_qualification = qualification;
nested_vmx_succeed(vcpu);
if (enable_shadow_vmcs)
to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
}
static int vmx_check_intercept(struct kvm_vcpu *vcpu,
struct x86_instruction_info *info,
enum x86_intercept_stage stage)
{
return X86EMUL_CONTINUE;
}
#ifdef CONFIG_X86_64
/* (a << shift) / divisor, return 1 if overflow otherwise 0 */
static inline int u64_shl_div_u64(u64 a, unsigned int shift,
u64 divisor, u64 *result)
{
u64 low = a << shift, high = a >> (64 - shift);
/* To avoid the overflow on divq */
if (high >= divisor)
return 1;
/* Low hold the result, high hold rem which is discarded */
asm("divq %2\n\t" : "=a" (low), "=d" (high) :
"rm" (divisor), "0" (low), "1" (high));
*result = low;
return 0;
}
static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 tscl = rdtsc();
u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
/* Convert to host delta tsc if tsc scaling is enabled */
if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
u64_shl_div_u64(delta_tsc,
kvm_tsc_scaling_ratio_frac_bits,
vcpu->arch.tsc_scaling_ratio,
&delta_tsc))
return -ERANGE;
/*
* If the delta tsc can't fit in the 32 bit after the multi shift,
* we can't use the preemption timer.
* It's possible that it fits on later vmentries, but checking
* on every vmentry is costly so we just use an hrtimer.
*/
if (delta_tsc >> (cpu_preemption_timer_multi + 32))
return -ERANGE;
vmx->hv_deadline_tsc = tscl + delta_tsc;
vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
PIN_BASED_VMX_PREEMPTION_TIMER);
return 0;
}
static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmx->hv_deadline_tsc = -1;
vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
PIN_BASED_VMX_PREEMPTION_TIMER);
}
#endif
static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
{
if (ple_gap)
shrink_ple_window(vcpu);
}
static void vmx_slot_enable_log_dirty(struct kvm *kvm,
struct kvm_memory_slot *slot)
{
kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
}
static void vmx_slot_disable_log_dirty(struct kvm *kvm,
struct kvm_memory_slot *slot)
{
kvm_mmu_slot_set_dirty(kvm, slot);
}
static void vmx_flush_log_dirty(struct kvm *kvm)
{
kvm_flush_pml_buffers(kvm);
}
static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
struct kvm_memory_slot *memslot,
gfn_t offset, unsigned long mask)
{
kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
}
/*
* This routine does the following things for vCPU which is going
* to be blocked if VT-d PI is enabled.
* - Store the vCPU to the wakeup list, so when interrupts happen
* we can find the right vCPU to wake up.
* - Change the Posted-interrupt descriptor as below:
* 'NDST' <-- vcpu->pre_pcpu
* 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
* - If 'ON' is set during this process, which means at least one
* interrupt is posted for this vCPU, we cannot block it, in
* this case, return 1, otherwise, return 0.
*
*/
static int pi_pre_block(struct kvm_vcpu *vcpu)
{
unsigned long flags;
unsigned int dest;
struct pi_desc old, new;
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(vcpu))
return 0;
vcpu->pre_pcpu = vcpu->cpu;
spin_lock_irqsave(&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
list_add_tail(&vcpu->blocked_vcpu_list,
&per_cpu(blocked_vcpu_on_cpu,
vcpu->pre_pcpu));
spin_unlock_irqrestore(&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
do {
old.control = new.control = pi_desc->control;
/*
* We should not block the vCPU if
* an interrupt is posted for it.
*/
if (pi_test_on(pi_desc) == 1) {
spin_lock_irqsave(&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
list_del(&vcpu->blocked_vcpu_list);
spin_unlock_irqrestore(
&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
vcpu->pre_pcpu = -1;
return 1;
}
WARN((pi_desc->sn == 1),
"Warning: SN field of posted-interrupts "
"is set before blocking\n");
/*
* Since vCPU can be preempted during this process,
* vcpu->cpu could be different with pre_pcpu, we
* need to set pre_pcpu as the destination of wakeup
* notification event, then we can find the right vCPU
* to wakeup in wakeup handler if interrupts happen
* when the vCPU is in blocked state.
*/
dest = cpu_physical_id(vcpu->pre_pcpu);
if (x2apic_enabled())
new.ndst = dest;
else
new.ndst = (dest << 8) & 0xFF00;
/* set 'NV' to 'wakeup vector' */
new.nv = POSTED_INTR_WAKEUP_VECTOR;
} while (cmpxchg(&pi_desc->control, old.control,
new.control) != old.control);
return 0;
}
static int vmx_pre_block(struct kvm_vcpu *vcpu)
{
if (pi_pre_block(vcpu))
return 1;
if (kvm_lapic_hv_timer_in_use(vcpu))
kvm_lapic_switch_to_sw_timer(vcpu);
return 0;
}
static void pi_post_block(struct kvm_vcpu *vcpu)
{
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
struct pi_desc old, new;
unsigned int dest;
unsigned long flags;
if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(vcpu))
return;
do {
old.control = new.control = pi_desc->control;
dest = cpu_physical_id(vcpu->cpu);
if (x2apic_enabled())
new.ndst = dest;
else
new.ndst = (dest << 8) & 0xFF00;
/* Allow posting non-urgent interrupts */
new.sn = 0;
/* set 'NV' to 'notification vector' */
new.nv = POSTED_INTR_VECTOR;
} while (cmpxchg(&pi_desc->control, old.control,
new.control) != old.control);
if(vcpu->pre_pcpu != -1) {
spin_lock_irqsave(
&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
list_del(&vcpu->blocked_vcpu_list);
spin_unlock_irqrestore(
&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
vcpu->pre_pcpu = -1;
}
}
static void vmx_post_block(struct kvm_vcpu *vcpu)
{
if (kvm_x86_ops->set_hv_timer)
kvm_lapic_switch_to_hv_timer(vcpu);
pi_post_block(vcpu);
}
/*
* vmx_update_pi_irte - set IRTE for Posted-Interrupts
*
* @kvm: kvm
* @host_irq: host irq of the interrupt
* @guest_irq: gsi of the interrupt
* @set: set or unset PI
* returns 0 on success, < 0 on failure
*/
static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
uint32_t guest_irq, bool set)
{
struct kvm_kernel_irq_routing_entry *e;
struct kvm_irq_routing_table *irq_rt;
struct kvm_lapic_irq irq;
struct kvm_vcpu *vcpu;
struct vcpu_data vcpu_info;
int idx, ret = -EINVAL;
if (!kvm_arch_has_assigned_device(kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(kvm->vcpus[0]))
return 0;
idx = srcu_read_lock(&kvm->irq_srcu);
irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
BUG_ON(guest_irq >= irq_rt->nr_rt_entries);
hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
if (e->type != KVM_IRQ_ROUTING_MSI)
continue;
/*
* VT-d PI cannot support posting multicast/broadcast
* interrupts to a vCPU, we still use interrupt remapping
* for these kind of interrupts.
*
* For lowest-priority interrupts, we only support
* those with single CPU as the destination, e.g. user
* configures the interrupts via /proc/irq or uses
* irqbalance to make the interrupts single-CPU.
*
* We will support full lowest-priority interrupt later.
*/
kvm_set_msi_irq(kvm, e, &irq);
if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
/*
* Make sure the IRTE is in remapped mode if
* we don't handle it in posted mode.
*/
ret = irq_set_vcpu_affinity(host_irq, NULL);
if (ret < 0) {
printk(KERN_INFO
"failed to back to remapped mode, irq: %u\n",
host_irq);
goto out;
}
continue;
}
vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
vcpu_info.vector = irq.vector;
trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
vcpu_info.vector, vcpu_info.pi_desc_addr, set);
if (set)
ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
else {
/* suppress notification event before unposting */
pi_set_sn(vcpu_to_pi_desc(vcpu));
ret = irq_set_vcpu_affinity(host_irq, NULL);
pi_clear_sn(vcpu_to_pi_desc(vcpu));
}
if (ret < 0) {
printk(KERN_INFO "%s: failed to update PI IRTE\n",
__func__);
goto out;
}
}
ret = 0;
out:
srcu_read_unlock(&kvm->irq_srcu, idx);
return ret;
}
static void vmx_setup_mce(struct kvm_vcpu *vcpu)
{
if (vcpu->arch.mcg_cap & MCG_LMCE_P)
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
FEATURE_CONTROL_LMCE;
else
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
~FEATURE_CONTROL_LMCE;
}
static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
.cpu_has_kvm_support = cpu_has_kvm_support,
.disabled_by_bios = vmx_disabled_by_bios,
.hardware_setup = hardware_setup,
.hardware_unsetup = hardware_unsetup,
.check_processor_compatibility = vmx_check_processor_compat,
.hardware_enable = hardware_enable,
.hardware_disable = hardware_disable,
.cpu_has_accelerated_tpr = report_flexpriority,
.cpu_has_high_real_mode_segbase = vmx_has_high_real_mode_segbase,
.vcpu_create = vmx_create_vcpu,
.vcpu_free = vmx_free_vcpu,
.vcpu_reset = vmx_vcpu_reset,
.prepare_guest_switch = vmx_save_host_state,
.vcpu_load = vmx_vcpu_load,
.vcpu_put = vmx_vcpu_put,
.update_bp_intercept = update_exception_bitmap,
.get_msr = vmx_get_msr,
.set_msr = vmx_set_msr,
.get_segment_base = vmx_get_segment_base,
.get_segment = vmx_get_segment,
.set_segment = vmx_set_segment,
.get_cpl = vmx_get_cpl,
.get_cs_db_l_bits = vmx_get_cs_db_l_bits,
.decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
.decache_cr3 = vmx_decache_cr3,
.decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
.set_cr0 = vmx_set_cr0,
.set_cr3 = vmx_set_cr3,
.set_cr4 = vmx_set_cr4,
.set_efer = vmx_set_efer,
.get_idt = vmx_get_idt,
.set_idt = vmx_set_idt,
.get_gdt = vmx_get_gdt,
.set_gdt = vmx_set_gdt,
.get_dr6 = vmx_get_dr6,
.set_dr6 = vmx_set_dr6,
.set_dr7 = vmx_set_dr7,
.sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
.cache_reg = vmx_cache_reg,
.get_rflags = vmx_get_rflags,
.set_rflags = vmx_set_rflags,
.get_pkru = vmx_get_pkru,
.fpu_activate = vmx_fpu_activate,
.fpu_deactivate = vmx_fpu_deactivate,
.tlb_flush = vmx_flush_tlb,
.run = vmx_vcpu_run,
.handle_exit = vmx_handle_exit,
.skip_emulated_instruction = skip_emulated_instruction,
.set_interrupt_shadow = vmx_set_interrupt_shadow,
.get_interrupt_shadow = vmx_get_interrupt_shadow,
.patch_hypercall = vmx_patch_hypercall,
.set_irq = vmx_inject_irq,
.set_nmi = vmx_inject_nmi,
.queue_exception = vmx_queue_exception,
.cancel_injection = vmx_cancel_injection,
.interrupt_allowed = vmx_interrupt_allowed,
.nmi_allowed = vmx_nmi_allowed,
.get_nmi_mask = vmx_get_nmi_mask,
.set_nmi_mask = vmx_set_nmi_mask,
.enable_nmi_window = enable_nmi_window,
.enable_irq_window = enable_irq_window,
.update_cr8_intercept = update_cr8_intercept,
.set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
.set_apic_access_page_addr = vmx_set_apic_access_page_addr,
.get_enable_apicv = vmx_get_enable_apicv,
.refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
.load_eoi_exitmap = vmx_load_eoi_exitmap,
.hwapic_irr_update = vmx_hwapic_irr_update,
.hwapic_isr_update = vmx_hwapic_isr_update,
.sync_pir_to_irr = vmx_sync_pir_to_irr,
.deliver_posted_interrupt = vmx_deliver_posted_interrupt,
.set_tss_addr = vmx_set_tss_addr,
.get_tdp_level = get_ept_level,
.get_mt_mask = vmx_get_mt_mask,
.get_exit_info = vmx_get_exit_info,
.get_lpage_level = vmx_get_lpage_level,
.cpuid_update = vmx_cpuid_update,
.rdtscp_supported = vmx_rdtscp_supported,
.invpcid_supported = vmx_invpcid_supported,
.set_supported_cpuid = vmx_set_supported_cpuid,
.has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
.write_tsc_offset = vmx_write_tsc_offset,
.set_tdp_cr3 = vmx_set_cr3,
.check_intercept = vmx_check_intercept,
.handle_external_intr = vmx_handle_external_intr,
.mpx_supported = vmx_mpx_supported,
.xsaves_supported = vmx_xsaves_supported,
.check_nested_events = vmx_check_nested_events,
.sched_in = vmx_sched_in,
.slot_enable_log_dirty = vmx_slot_enable_log_dirty,
.slot_disable_log_dirty = vmx_slot_disable_log_dirty,
.flush_log_dirty = vmx_flush_log_dirty,
.enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
.pre_block = vmx_pre_block,
.post_block = vmx_post_block,
.pmu_ops = &intel_pmu_ops,
.update_pi_irte = vmx_update_pi_irte,
#ifdef CONFIG_X86_64
.set_hv_timer = vmx_set_hv_timer,
.cancel_hv_timer = vmx_cancel_hv_timer,
#endif
.setup_mce = vmx_setup_mce,
};
static int __init vmx_init(void)
{
int r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
__alignof__(struct vcpu_vmx), THIS_MODULE);
if (r)
return r;
#ifdef CONFIG_KEXEC_CORE
rcu_assign_pointer(crash_vmclear_loaded_vmcss,
crash_vmclear_local_loaded_vmcss);
#endif
return 0;
}
static void __exit vmx_exit(void)
{
#ifdef CONFIG_KEXEC_CORE
RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
synchronize_rcu();
#endif
kvm_exit();
}
module_init(vmx_init)
module_exit(vmx_exit)
| ./CrossVul/dataset_final_sorted/CWE-388/c/good_5494_0 |
crossvul-cpp_data_good_3289_0 | /*
* Simple NUMA memory policy for the Linux kernel.
*
* Copyright 2003,2004 Andi Kleen, SuSE Labs.
* (C) Copyright 2005 Christoph Lameter, Silicon Graphics, Inc.
* Subject to the GNU Public License, version 2.
*
* NUMA policy allows the user to give hints in which node(s) memory should
* be allocated.
*
* Support four policies per VMA and per process:
*
* The VMA policy has priority over the process policy for a page fault.
*
* interleave Allocate memory interleaved over a set of nodes,
* with normal fallback if it fails.
* For VMA based allocations this interleaves based on the
* offset into the backing object or offset into the mapping
* for anonymous memory. For process policy an process counter
* is used.
*
* bind Only allocate memory on a specific set of nodes,
* no fallback.
* FIXME: memory is allocated starting with the first node
* to the last. It would be better if bind would truly restrict
* the allocation to memory nodes instead
*
* preferred Try a specific node first before normal fallback.
* As a special case NUMA_NO_NODE here means do the allocation
* on the local CPU. This is normally identical to default,
* but useful to set in a VMA when you have a non default
* process policy.
*
* default Allocate on the local node first, or when on a VMA
* use the process policy. This is what Linux always did
* in a NUMA aware kernel and still does by, ahem, default.
*
* The process policy is applied for most non interrupt memory allocations
* in that process' context. Interrupts ignore the policies and always
* try to allocate on the local CPU. The VMA policy is only applied for memory
* allocations for a VMA in the VM.
*
* Currently there are a few corner cases in swapping where the policy
* is not applied, but the majority should be handled. When process policy
* is used it is not remembered over swap outs/swap ins.
*
* Only the highest zone in the zone hierarchy gets policied. Allocations
* requesting a lower zone just use default policy. This implies that
* on systems with highmem kernel lowmem allocation don't get policied.
* Same with GFP_DMA allocations.
*
* For shmfs/tmpfs/hugetlbfs shared memory the policy is shared between
* all users and remembered even when nobody has memory mapped.
*/
/* Notebook:
fix mmap readahead to honour policy and enable policy for any page cache
object
statistics for bigpages
global policy for page cache? currently it uses process policy. Requires
first item above.
handle mremap for shared memory (currently ignored for the policy)
grows down?
make bind policy root only? It can trigger oom much faster and the
kernel is not always grateful with that.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/mempolicy.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/hugetlb.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/sched/mm.h>
#include <linux/sched/numa_balancing.h>
#include <linux/sched/task.h>
#include <linux/nodemask.h>
#include <linux/cpuset.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/export.h>
#include <linux/nsproxy.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/compat.h>
#include <linux/swap.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/migrate.h>
#include <linux/ksm.h>
#include <linux/rmap.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/ctype.h>
#include <linux/mm_inline.h>
#include <linux/mmu_notifier.h>
#include <linux/printk.h>
#include <asm/tlbflush.h>
#include <linux/uaccess.h>
#include "internal.h"
/* Internal flags */
#define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0) /* Skip checks for continuous vmas */
#define MPOL_MF_INVERT (MPOL_MF_INTERNAL << 1) /* Invert check for nodemask */
static struct kmem_cache *policy_cache;
static struct kmem_cache *sn_cache;
/* Highest zone. An specific allocation for a zone below that is not
policied. */
enum zone_type policy_zone = 0;
/*
* run-time system-wide default policy => local allocation
*/
static struct mempolicy default_policy = {
.refcnt = ATOMIC_INIT(1), /* never free it */
.mode = MPOL_PREFERRED,
.flags = MPOL_F_LOCAL,
};
static struct mempolicy preferred_node_policy[MAX_NUMNODES];
struct mempolicy *get_task_policy(struct task_struct *p)
{
struct mempolicy *pol = p->mempolicy;
int node;
if (pol)
return pol;
node = numa_node_id();
if (node != NUMA_NO_NODE) {
pol = &preferred_node_policy[node];
/* preferred_node_policy is not initialised early in boot */
if (pol->mode)
return pol;
}
return &default_policy;
}
static const struct mempolicy_operations {
int (*create)(struct mempolicy *pol, const nodemask_t *nodes);
/*
* If read-side task has no lock to protect task->mempolicy, write-side
* task will rebind the task->mempolicy by two step. The first step is
* setting all the newly nodes, and the second step is cleaning all the
* disallowed nodes. In this way, we can avoid finding no node to alloc
* page.
* If we have a lock to protect task->mempolicy in read-side, we do
* rebind directly.
*
* step:
* MPOL_REBIND_ONCE - do rebind work at once
* MPOL_REBIND_STEP1 - set all the newly nodes
* MPOL_REBIND_STEP2 - clean all the disallowed nodes
*/
void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes,
enum mpol_rebind_step step);
} mpol_ops[MPOL_MAX];
static inline int mpol_store_user_nodemask(const struct mempolicy *pol)
{
return pol->flags & MPOL_MODE_FLAGS;
}
static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig,
const nodemask_t *rel)
{
nodemask_t tmp;
nodes_fold(tmp, *orig, nodes_weight(*rel));
nodes_onto(*ret, tmp, *rel);
}
static int mpol_new_interleave(struct mempolicy *pol, const nodemask_t *nodes)
{
if (nodes_empty(*nodes))
return -EINVAL;
pol->v.nodes = *nodes;
return 0;
}
static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes)
{
if (!nodes)
pol->flags |= MPOL_F_LOCAL; /* local allocation */
else if (nodes_empty(*nodes))
return -EINVAL; /* no allowed nodes */
else
pol->v.preferred_node = first_node(*nodes);
return 0;
}
static int mpol_new_bind(struct mempolicy *pol, const nodemask_t *nodes)
{
if (nodes_empty(*nodes))
return -EINVAL;
pol->v.nodes = *nodes;
return 0;
}
/*
* mpol_set_nodemask is called after mpol_new() to set up the nodemask, if
* any, for the new policy. mpol_new() has already validated the nodes
* parameter with respect to the policy mode and flags. But, we need to
* handle an empty nodemask with MPOL_PREFERRED here.
*
* Must be called holding task's alloc_lock to protect task's mems_allowed
* and mempolicy. May also be called holding the mmap_semaphore for write.
*/
static int mpol_set_nodemask(struct mempolicy *pol,
const nodemask_t *nodes, struct nodemask_scratch *nsc)
{
int ret;
/* if mode is MPOL_DEFAULT, pol is NULL. This is right. */
if (pol == NULL)
return 0;
/* Check N_MEMORY */
nodes_and(nsc->mask1,
cpuset_current_mems_allowed, node_states[N_MEMORY]);
VM_BUG_ON(!nodes);
if (pol->mode == MPOL_PREFERRED && nodes_empty(*nodes))
nodes = NULL; /* explicit local allocation */
else {
if (pol->flags & MPOL_F_RELATIVE_NODES)
mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1);
else
nodes_and(nsc->mask2, *nodes, nsc->mask1);
if (mpol_store_user_nodemask(pol))
pol->w.user_nodemask = *nodes;
else
pol->w.cpuset_mems_allowed =
cpuset_current_mems_allowed;
}
if (nodes)
ret = mpol_ops[pol->mode].create(pol, &nsc->mask2);
else
ret = mpol_ops[pol->mode].create(pol, NULL);
return ret;
}
/*
* This function just creates a new policy, does some check and simple
* initialization. You must invoke mpol_set_nodemask() to set nodes.
*/
static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags,
nodemask_t *nodes)
{
struct mempolicy *policy;
pr_debug("setting mode %d flags %d nodes[0] %lx\n",
mode, flags, nodes ? nodes_addr(*nodes)[0] : NUMA_NO_NODE);
if (mode == MPOL_DEFAULT) {
if (nodes && !nodes_empty(*nodes))
return ERR_PTR(-EINVAL);
return NULL;
}
VM_BUG_ON(!nodes);
/*
* MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or
* MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation).
* All other modes require a valid pointer to a non-empty nodemask.
*/
if (mode == MPOL_PREFERRED) {
if (nodes_empty(*nodes)) {
if (((flags & MPOL_F_STATIC_NODES) ||
(flags & MPOL_F_RELATIVE_NODES)))
return ERR_PTR(-EINVAL);
}
} else if (mode == MPOL_LOCAL) {
if (!nodes_empty(*nodes) ||
(flags & MPOL_F_STATIC_NODES) ||
(flags & MPOL_F_RELATIVE_NODES))
return ERR_PTR(-EINVAL);
mode = MPOL_PREFERRED;
} else if (nodes_empty(*nodes))
return ERR_PTR(-EINVAL);
policy = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!policy)
return ERR_PTR(-ENOMEM);
atomic_set(&policy->refcnt, 1);
policy->mode = mode;
policy->flags = flags;
return policy;
}
/* Slow path of a mpol destructor. */
void __mpol_put(struct mempolicy *p)
{
if (!atomic_dec_and_test(&p->refcnt))
return;
kmem_cache_free(policy_cache, p);
}
static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes,
enum mpol_rebind_step step)
{
}
/*
* step:
* MPOL_REBIND_ONCE - do rebind work at once
* MPOL_REBIND_STEP1 - set all the newly nodes
* MPOL_REBIND_STEP2 - clean all the disallowed nodes
*/
static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes,
enum mpol_rebind_step step)
{
nodemask_t tmp;
if (pol->flags & MPOL_F_STATIC_NODES)
nodes_and(tmp, pol->w.user_nodemask, *nodes);
else if (pol->flags & MPOL_F_RELATIVE_NODES)
mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
else {
/*
* if step == 1, we use ->w.cpuset_mems_allowed to cache the
* result
*/
if (step == MPOL_REBIND_ONCE || step == MPOL_REBIND_STEP1) {
nodes_remap(tmp, pol->v.nodes,
pol->w.cpuset_mems_allowed, *nodes);
pol->w.cpuset_mems_allowed = step ? tmp : *nodes;
} else if (step == MPOL_REBIND_STEP2) {
tmp = pol->w.cpuset_mems_allowed;
pol->w.cpuset_mems_allowed = *nodes;
} else
BUG();
}
if (nodes_empty(tmp))
tmp = *nodes;
if (step == MPOL_REBIND_STEP1)
nodes_or(pol->v.nodes, pol->v.nodes, tmp);
else if (step == MPOL_REBIND_ONCE || step == MPOL_REBIND_STEP2)
pol->v.nodes = tmp;
else
BUG();
if (!node_isset(current->il_next, tmp)) {
current->il_next = next_node_in(current->il_next, tmp);
if (current->il_next >= MAX_NUMNODES)
current->il_next = numa_node_id();
}
}
static void mpol_rebind_preferred(struct mempolicy *pol,
const nodemask_t *nodes,
enum mpol_rebind_step step)
{
nodemask_t tmp;
if (pol->flags & MPOL_F_STATIC_NODES) {
int node = first_node(pol->w.user_nodemask);
if (node_isset(node, *nodes)) {
pol->v.preferred_node = node;
pol->flags &= ~MPOL_F_LOCAL;
} else
pol->flags |= MPOL_F_LOCAL;
} else if (pol->flags & MPOL_F_RELATIVE_NODES) {
mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
pol->v.preferred_node = first_node(tmp);
} else if (!(pol->flags & MPOL_F_LOCAL)) {
pol->v.preferred_node = node_remap(pol->v.preferred_node,
pol->w.cpuset_mems_allowed,
*nodes);
pol->w.cpuset_mems_allowed = *nodes;
}
}
/*
* mpol_rebind_policy - Migrate a policy to a different set of nodes
*
* If read-side task has no lock to protect task->mempolicy, write-side
* task will rebind the task->mempolicy by two step. The first step is
* setting all the newly nodes, and the second step is cleaning all the
* disallowed nodes. In this way, we can avoid finding no node to alloc
* page.
* If we have a lock to protect task->mempolicy in read-side, we do
* rebind directly.
*
* step:
* MPOL_REBIND_ONCE - do rebind work at once
* MPOL_REBIND_STEP1 - set all the newly nodes
* MPOL_REBIND_STEP2 - clean all the disallowed nodes
*/
static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask,
enum mpol_rebind_step step)
{
if (!pol)
return;
if (!mpol_store_user_nodemask(pol) && step == MPOL_REBIND_ONCE &&
nodes_equal(pol->w.cpuset_mems_allowed, *newmask))
return;
if (step == MPOL_REBIND_STEP1 && (pol->flags & MPOL_F_REBINDING))
return;
if (step == MPOL_REBIND_STEP2 && !(pol->flags & MPOL_F_REBINDING))
BUG();
if (step == MPOL_REBIND_STEP1)
pol->flags |= MPOL_F_REBINDING;
else if (step == MPOL_REBIND_STEP2)
pol->flags &= ~MPOL_F_REBINDING;
else if (step >= MPOL_REBIND_NSTEP)
BUG();
mpol_ops[pol->mode].rebind(pol, newmask, step);
}
/*
* Wrapper for mpol_rebind_policy() that just requires task
* pointer, and updates task mempolicy.
*
* Called with task's alloc_lock held.
*/
void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new,
enum mpol_rebind_step step)
{
mpol_rebind_policy(tsk->mempolicy, new, step);
}
/*
* Rebind each vma in mm to new nodemask.
*
* Call holding a reference to mm. Takes mm->mmap_sem during call.
*/
void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new)
{
struct vm_area_struct *vma;
down_write(&mm->mmap_sem);
for (vma = mm->mmap; vma; vma = vma->vm_next)
mpol_rebind_policy(vma->vm_policy, new, MPOL_REBIND_ONCE);
up_write(&mm->mmap_sem);
}
static const struct mempolicy_operations mpol_ops[MPOL_MAX] = {
[MPOL_DEFAULT] = {
.rebind = mpol_rebind_default,
},
[MPOL_INTERLEAVE] = {
.create = mpol_new_interleave,
.rebind = mpol_rebind_nodemask,
},
[MPOL_PREFERRED] = {
.create = mpol_new_preferred,
.rebind = mpol_rebind_preferred,
},
[MPOL_BIND] = {
.create = mpol_new_bind,
.rebind = mpol_rebind_nodemask,
},
};
static void migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags);
struct queue_pages {
struct list_head *pagelist;
unsigned long flags;
nodemask_t *nmask;
struct vm_area_struct *prev;
};
/*
* Scan through pages checking if pages follow certain conditions,
* and move them to the pagelist if they do.
*/
static int queue_pages_pte_range(pmd_t *pmd, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct page *page;
struct queue_pages *qp = walk->private;
unsigned long flags = qp->flags;
int nid, ret;
pte_t *pte;
spinlock_t *ptl;
if (pmd_trans_huge(*pmd)) {
ptl = pmd_lock(walk->mm, pmd);
if (pmd_trans_huge(*pmd)) {
page = pmd_page(*pmd);
if (is_huge_zero_page(page)) {
spin_unlock(ptl);
__split_huge_pmd(vma, pmd, addr, false, NULL);
} else {
get_page(page);
spin_unlock(ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (ret)
return 0;
}
} else {
spin_unlock(ptl);
}
}
if (pmd_trans_unstable(pmd))
return 0;
retry:
pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE) {
if (!pte_present(*pte))
continue;
page = vm_normal_page(vma, addr, *pte);
if (!page)
continue;
/*
* vm_normal_page() filters out zero pages, but there might
* still be PageReserved pages to skip, perhaps in a VDSO.
*/
if (PageReserved(page))
continue;
nid = page_to_nid(page);
if (node_isset(nid, *qp->nmask) == !!(flags & MPOL_MF_INVERT))
continue;
if (PageTransCompound(page)) {
get_page(page);
pte_unmap_unlock(pte, ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
/* Failed to split -- skip. */
if (ret) {
pte = pte_offset_map_lock(walk->mm, pmd,
addr, &ptl);
continue;
}
goto retry;
}
migrate_page_add(page, qp->pagelist, flags);
}
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 0;
}
static int queue_pages_hugetlb(pte_t *pte, unsigned long hmask,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
#ifdef CONFIG_HUGETLB_PAGE
struct queue_pages *qp = walk->private;
unsigned long flags = qp->flags;
int nid;
struct page *page;
spinlock_t *ptl;
pte_t entry;
ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
entry = huge_ptep_get(pte);
if (!pte_present(entry))
goto unlock;
page = pte_page(entry);
nid = page_to_nid(page);
if (node_isset(nid, *qp->nmask) == !!(flags & MPOL_MF_INVERT))
goto unlock;
/* With MPOL_MF_MOVE, we migrate only unshared hugepage. */
if (flags & (MPOL_MF_MOVE_ALL) ||
(flags & MPOL_MF_MOVE && page_mapcount(page) == 1))
isolate_huge_page(page, qp->pagelist);
unlock:
spin_unlock(ptl);
#else
BUG();
#endif
return 0;
}
#ifdef CONFIG_NUMA_BALANCING
/*
* This is used to mark a range of virtual addresses to be inaccessible.
* These are later cleared by a NUMA hinting fault. Depending on these
* faults, pages may be migrated for better NUMA placement.
*
* This is assuming that NUMA faults are handled using PROT_NONE. If
* an architecture makes a different choice, it will need further
* changes to the core.
*/
unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
int nr_updated;
nr_updated = change_protection(vma, addr, end, PAGE_NONE, 0, 1);
if (nr_updated)
count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated);
return nr_updated;
}
#else
static unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
return 0;
}
#endif /* CONFIG_NUMA_BALANCING */
static int queue_pages_test_walk(unsigned long start, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct queue_pages *qp = walk->private;
unsigned long endvma = vma->vm_end;
unsigned long flags = qp->flags;
if (!vma_migratable(vma))
return 1;
if (endvma > end)
endvma = end;
if (vma->vm_start > start)
start = vma->vm_start;
if (!(flags & MPOL_MF_DISCONTIG_OK)) {
if (!vma->vm_next && vma->vm_end < end)
return -EFAULT;
if (qp->prev && qp->prev->vm_end < vma->vm_start)
return -EFAULT;
}
qp->prev = vma;
if (flags & MPOL_MF_LAZY) {
/* Similar to task_numa_work, skip inaccessible VMAs */
if (!is_vm_hugetlb_page(vma) &&
(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)) &&
!(vma->vm_flags & VM_MIXEDMAP))
change_prot_numa(vma, start, endvma);
return 1;
}
/* queue pages from current vma */
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
return 0;
return 1;
}
/*
* Walk through page tables and collect pages to be migrated.
*
* If pages found in a given range are on a set of nodes (determined by
* @nodes and @flags,) it's isolated and queued to the pagelist which is
* passed via @private.)
*/
static int
queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end,
nodemask_t *nodes, unsigned long flags,
struct list_head *pagelist)
{
struct queue_pages qp = {
.pagelist = pagelist,
.flags = flags,
.nmask = nodes,
.prev = NULL,
};
struct mm_walk queue_pages_walk = {
.hugetlb_entry = queue_pages_hugetlb,
.pmd_entry = queue_pages_pte_range,
.test_walk = queue_pages_test_walk,
.mm = mm,
.private = &qp,
};
return walk_page_range(start, end, &queue_pages_walk);
}
/*
* Apply policy to a single VMA
* This must be called with the mmap_sem held for writing.
*/
static int vma_replace_policy(struct vm_area_struct *vma,
struct mempolicy *pol)
{
int err;
struct mempolicy *old;
struct mempolicy *new;
pr_debug("vma %lx-%lx/%lx vm_ops %p vm_file %p set_policy %p\n",
vma->vm_start, vma->vm_end, vma->vm_pgoff,
vma->vm_ops, vma->vm_file,
vma->vm_ops ? vma->vm_ops->set_policy : NULL);
new = mpol_dup(pol);
if (IS_ERR(new))
return PTR_ERR(new);
if (vma->vm_ops && vma->vm_ops->set_policy) {
err = vma->vm_ops->set_policy(vma, new);
if (err)
goto err_out;
}
old = vma->vm_policy;
vma->vm_policy = new; /* protected by mmap_sem */
mpol_put(old);
return 0;
err_out:
mpol_put(new);
return err;
}
/* Step 2: apply policy to a range and do splits. */
static int mbind_range(struct mm_struct *mm, unsigned long start,
unsigned long end, struct mempolicy *new_pol)
{
struct vm_area_struct *next;
struct vm_area_struct *prev;
struct vm_area_struct *vma;
int err = 0;
pgoff_t pgoff;
unsigned long vmstart;
unsigned long vmend;
vma = find_vma(mm, start);
if (!vma || vma->vm_start > start)
return -EFAULT;
prev = vma->vm_prev;
if (start > vma->vm_start)
prev = vma;
for (; vma && vma->vm_start < end; prev = vma, vma = next) {
next = vma->vm_next;
vmstart = max(start, vma->vm_start);
vmend = min(end, vma->vm_end);
if (mpol_equal(vma_policy(vma), new_pol))
continue;
pgoff = vma->vm_pgoff +
((vmstart - vma->vm_start) >> PAGE_SHIFT);
prev = vma_merge(mm, prev, vmstart, vmend, vma->vm_flags,
vma->anon_vma, vma->vm_file, pgoff,
new_pol, vma->vm_userfaultfd_ctx);
if (prev) {
vma = prev;
next = vma->vm_next;
if (mpol_equal(vma_policy(vma), new_pol))
continue;
/* vma_merge() joined vma && vma->next, case 8 */
goto replace;
}
if (vma->vm_start != vmstart) {
err = split_vma(vma->vm_mm, vma, vmstart, 1);
if (err)
goto out;
}
if (vma->vm_end != vmend) {
err = split_vma(vma->vm_mm, vma, vmend, 0);
if (err)
goto out;
}
replace:
err = vma_replace_policy(vma, new_pol);
if (err)
goto out;
}
out:
return err;
}
/* Set the process memory policy */
static long do_set_mempolicy(unsigned short mode, unsigned short flags,
nodemask_t *nodes)
{
struct mempolicy *new, *old;
NODEMASK_SCRATCH(scratch);
int ret;
if (!scratch)
return -ENOMEM;
new = mpol_new(mode, flags, nodes);
if (IS_ERR(new)) {
ret = PTR_ERR(new);
goto out;
}
task_lock(current);
ret = mpol_set_nodemask(new, nodes, scratch);
if (ret) {
task_unlock(current);
mpol_put(new);
goto out;
}
old = current->mempolicy;
current->mempolicy = new;
if (new && new->mode == MPOL_INTERLEAVE &&
nodes_weight(new->v.nodes))
current->il_next = first_node(new->v.nodes);
task_unlock(current);
mpol_put(old);
ret = 0;
out:
NODEMASK_SCRATCH_FREE(scratch);
return ret;
}
/*
* Return nodemask for policy for get_mempolicy() query
*
* Called with task's alloc_lock held
*/
static void get_policy_nodemask(struct mempolicy *p, nodemask_t *nodes)
{
nodes_clear(*nodes);
if (p == &default_policy)
return;
switch (p->mode) {
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
*nodes = p->v.nodes;
break;
case MPOL_PREFERRED:
if (!(p->flags & MPOL_F_LOCAL))
node_set(p->v.preferred_node, *nodes);
/* else return empty node mask for local allocation */
break;
default:
BUG();
}
}
static int lookup_node(unsigned long addr)
{
struct page *p;
int err;
err = get_user_pages(addr & PAGE_MASK, 1, 0, &p, NULL);
if (err >= 0) {
err = page_to_nid(p);
put_page(p);
}
return err;
}
/* Retrieve NUMA policy */
static long do_get_mempolicy(int *policy, nodemask_t *nmask,
unsigned long addr, unsigned long flags)
{
int err;
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = NULL;
struct mempolicy *pol = current->mempolicy;
if (flags &
~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
return -EINVAL;
if (flags & MPOL_F_MEMS_ALLOWED) {
if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
return -EINVAL;
*policy = 0; /* just so it's initialized */
task_lock(current);
*nmask = cpuset_current_mems_allowed;
task_unlock(current);
return 0;
}
if (flags & MPOL_F_ADDR) {
/*
* Do NOT fall back to task policy if the
* vma/shared policy at addr is NULL. We
* want to return MPOL_DEFAULT in this case.
*/
down_read(&mm->mmap_sem);
vma = find_vma_intersection(mm, addr, addr+1);
if (!vma) {
up_read(&mm->mmap_sem);
return -EFAULT;
}
if (vma->vm_ops && vma->vm_ops->get_policy)
pol = vma->vm_ops->get_policy(vma, addr);
else
pol = vma->vm_policy;
} else if (addr)
return -EINVAL;
if (!pol)
pol = &default_policy; /* indicates default behavior */
if (flags & MPOL_F_NODE) {
if (flags & MPOL_F_ADDR) {
err = lookup_node(addr);
if (err < 0)
goto out;
*policy = err;
} else if (pol == current->mempolicy &&
pol->mode == MPOL_INTERLEAVE) {
*policy = current->il_next;
} else {
err = -EINVAL;
goto out;
}
} else {
*policy = pol == &default_policy ? MPOL_DEFAULT :
pol->mode;
/*
* Internal mempolicy flags must be masked off before exposing
* the policy to userspace.
*/
*policy |= (pol->flags & MPOL_MODE_FLAGS);
}
if (vma) {
up_read(¤t->mm->mmap_sem);
vma = NULL;
}
err = 0;
if (nmask) {
if (mpol_store_user_nodemask(pol)) {
*nmask = pol->w.user_nodemask;
} else {
task_lock(current);
get_policy_nodemask(pol, nmask);
task_unlock(current);
}
}
out:
mpol_cond_put(pol);
if (vma)
up_read(¤t->mm->mmap_sem);
return err;
}
#ifdef CONFIG_MIGRATION
/*
* page migration
*/
static void migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags)
{
/*
* Avoid migrating a page that is shared with others.
*/
if ((flags & MPOL_MF_MOVE_ALL) || page_mapcount(page) == 1) {
if (!isolate_lru_page(page)) {
list_add_tail(&page->lru, pagelist);
inc_node_page_state(page, NR_ISOLATED_ANON +
page_is_file_cache(page));
}
}
}
static struct page *new_node_page(struct page *page, unsigned long node, int **x)
{
if (PageHuge(page))
return alloc_huge_page_node(page_hstate(compound_head(page)),
node);
else
return __alloc_pages_node(node, GFP_HIGHUSER_MOVABLE |
__GFP_THISNODE, 0);
}
/*
* Migrate pages from one node to a target node.
* Returns error or the number of pages not migrated.
*/
static int migrate_to_node(struct mm_struct *mm, int source, int dest,
int flags)
{
nodemask_t nmask;
LIST_HEAD(pagelist);
int err = 0;
nodes_clear(nmask);
node_set(source, nmask);
/*
* This does not "check" the range but isolates all pages that
* need migration. Between passing in the full user address
* space range and MPOL_MF_DISCONTIG_OK, this call can not fail.
*/
VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)));
queue_pages_range(mm, mm->mmap->vm_start, mm->task_size, &nmask,
flags | MPOL_MF_DISCONTIG_OK, &pagelist);
if (!list_empty(&pagelist)) {
err = migrate_pages(&pagelist, new_node_page, NULL, dest,
MIGRATE_SYNC, MR_SYSCALL);
if (err)
putback_movable_pages(&pagelist);
}
return err;
}
/*
* Move pages between the two nodesets so as to preserve the physical
* layout as much as possible.
*
* Returns the number of page that could not be moved.
*/
int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
const nodemask_t *to, int flags)
{
int busy = 0;
int err;
nodemask_t tmp;
err = migrate_prep();
if (err)
return err;
down_read(&mm->mmap_sem);
/*
* Find a 'source' bit set in 'tmp' whose corresponding 'dest'
* bit in 'to' is not also set in 'tmp'. Clear the found 'source'
* bit in 'tmp', and return that <source, dest> pair for migration.
* The pair of nodemasks 'to' and 'from' define the map.
*
* If no pair of bits is found that way, fallback to picking some
* pair of 'source' and 'dest' bits that are not the same. If the
* 'source' and 'dest' bits are the same, this represents a node
* that will be migrating to itself, so no pages need move.
*
* If no bits are left in 'tmp', or if all remaining bits left
* in 'tmp' correspond to the same bit in 'to', return false
* (nothing left to migrate).
*
* This lets us pick a pair of nodes to migrate between, such that
* if possible the dest node is not already occupied by some other
* source node, minimizing the risk of overloading the memory on a
* node that would happen if we migrated incoming memory to a node
* before migrating outgoing memory source that same node.
*
* A single scan of tmp is sufficient. As we go, we remember the
* most recent <s, d> pair that moved (s != d). If we find a pair
* that not only moved, but what's better, moved to an empty slot
* (d is not set in tmp), then we break out then, with that pair.
* Otherwise when we finish scanning from_tmp, we at least have the
* most recent <s, d> pair that moved. If we get all the way through
* the scan of tmp without finding any node that moved, much less
* moved to an empty node, then there is nothing left worth migrating.
*/
tmp = *from;
while (!nodes_empty(tmp)) {
int s,d;
int source = NUMA_NO_NODE;
int dest = 0;
for_each_node_mask(s, tmp) {
/*
* do_migrate_pages() tries to maintain the relative
* node relationship of the pages established between
* threads and memory areas.
*
* However if the number of source nodes is not equal to
* the number of destination nodes we can not preserve
* this node relative relationship. In that case, skip
* copying memory from a node that is in the destination
* mask.
*
* Example: [2,3,4] -> [3,4,5] moves everything.
* [0-7] - > [3,4,5] moves only 0,1,2,6,7.
*/
if ((nodes_weight(*from) != nodes_weight(*to)) &&
(node_isset(s, *to)))
continue;
d = node_remap(s, *from, *to);
if (s == d)
continue;
source = s; /* Node moved. Memorize */
dest = d;
/* dest not in remaining from nodes? */
if (!node_isset(dest, tmp))
break;
}
if (source == NUMA_NO_NODE)
break;
node_clear(source, tmp);
err = migrate_to_node(mm, source, dest, flags);
if (err > 0)
busy += err;
if (err < 0)
break;
}
up_read(&mm->mmap_sem);
if (err < 0)
return err;
return busy;
}
/*
* Allocate a new page for page migration based on vma policy.
* Start by assuming the page is mapped by the same vma as contains @start.
* Search forward from there, if not. N.B., this assumes that the
* list of pages handed to migrate_pages()--which is how we get here--
* is in virtual address order.
*/
static struct page *new_page(struct page *page, unsigned long start, int **x)
{
struct vm_area_struct *vma;
unsigned long uninitialized_var(address);
vma = find_vma(current->mm, start);
while (vma) {
address = page_address_in_vma(page, vma);
if (address != -EFAULT)
break;
vma = vma->vm_next;
}
if (PageHuge(page)) {
BUG_ON(!vma);
return alloc_huge_page_noerr(vma, address, 1);
}
/*
* if !vma, alloc_page_vma() will use task or system default policy
*/
return alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
}
#else
static void migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags)
{
}
int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
const nodemask_t *to, int flags)
{
return -ENOSYS;
}
static struct page *new_page(struct page *page, unsigned long start, int **x)
{
return NULL;
}
#endif
static long do_mbind(unsigned long start, unsigned long len,
unsigned short mode, unsigned short mode_flags,
nodemask_t *nmask, unsigned long flags)
{
struct mm_struct *mm = current->mm;
struct mempolicy *new;
unsigned long end;
int err;
LIST_HEAD(pagelist);
if (flags & ~(unsigned long)MPOL_MF_VALID)
return -EINVAL;
if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
return -EPERM;
if (start & ~PAGE_MASK)
return -EINVAL;
if (mode == MPOL_DEFAULT)
flags &= ~MPOL_MF_STRICT;
len = (len + PAGE_SIZE - 1) & PAGE_MASK;
end = start + len;
if (end < start)
return -EINVAL;
if (end == start)
return 0;
new = mpol_new(mode, mode_flags, nmask);
if (IS_ERR(new))
return PTR_ERR(new);
if (flags & MPOL_MF_LAZY)
new->flags |= MPOL_F_MOF;
/*
* If we are using the default policy then operation
* on discontinuous address spaces is okay after all
*/
if (!new)
flags |= MPOL_MF_DISCONTIG_OK;
pr_debug("mbind %lx-%lx mode:%d flags:%d nodes:%lx\n",
start, start + len, mode, mode_flags,
nmask ? nodes_addr(*nmask)[0] : NUMA_NO_NODE);
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) {
err = migrate_prep();
if (err)
goto mpol_out;
}
{
NODEMASK_SCRATCH(scratch);
if (scratch) {
down_write(&mm->mmap_sem);
task_lock(current);
err = mpol_set_nodemask(new, nmask, scratch);
task_unlock(current);
if (err)
up_write(&mm->mmap_sem);
} else
err = -ENOMEM;
NODEMASK_SCRATCH_FREE(scratch);
}
if (err)
goto mpol_out;
err = queue_pages_range(mm, start, end, nmask,
flags | MPOL_MF_INVERT, &pagelist);
if (!err)
err = mbind_range(mm, start, end, new);
if (!err) {
int nr_failed = 0;
if (!list_empty(&pagelist)) {
WARN_ON_ONCE(flags & MPOL_MF_LAZY);
nr_failed = migrate_pages(&pagelist, new_page, NULL,
start, MIGRATE_SYNC, MR_MEMPOLICY_MBIND);
if (nr_failed)
putback_movable_pages(&pagelist);
}
if (nr_failed && (flags & MPOL_MF_STRICT))
err = -EIO;
} else
putback_movable_pages(&pagelist);
up_write(&mm->mmap_sem);
mpol_out:
mpol_put(new);
return err;
}
/*
* User space interface with variable sized bitmaps for nodelists.
*/
/* Copy a node mask from user space. */
static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask,
unsigned long maxnode)
{
unsigned long k;
unsigned long nlongs;
unsigned long endmask;
--maxnode;
nodes_clear(*nodes);
if (maxnode == 0 || !nmask)
return 0;
if (maxnode > PAGE_SIZE*BITS_PER_BYTE)
return -EINVAL;
nlongs = BITS_TO_LONGS(maxnode);
if ((maxnode % BITS_PER_LONG) == 0)
endmask = ~0UL;
else
endmask = (1UL << (maxnode % BITS_PER_LONG)) - 1;
/* When the user specified more nodes than supported just check
if the non supported part is all zero. */
if (nlongs > BITS_TO_LONGS(MAX_NUMNODES)) {
if (nlongs > PAGE_SIZE/sizeof(long))
return -EINVAL;
for (k = BITS_TO_LONGS(MAX_NUMNODES); k < nlongs; k++) {
unsigned long t;
if (get_user(t, nmask + k))
return -EFAULT;
if (k == nlongs - 1) {
if (t & endmask)
return -EINVAL;
} else if (t)
return -EINVAL;
}
nlongs = BITS_TO_LONGS(MAX_NUMNODES);
endmask = ~0UL;
}
if (copy_from_user(nodes_addr(*nodes), nmask, nlongs*sizeof(unsigned long)))
return -EFAULT;
nodes_addr(*nodes)[nlongs-1] &= endmask;
return 0;
}
/* Copy a kernel node mask to user space */
static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode,
nodemask_t *nodes)
{
unsigned long copy = ALIGN(maxnode-1, 64) / 8;
const int nbytes = BITS_TO_LONGS(MAX_NUMNODES) * sizeof(long);
if (copy > nbytes) {
if (copy > PAGE_SIZE)
return -EINVAL;
if (clear_user((char __user *)mask + nbytes, copy - nbytes))
return -EFAULT;
copy = nbytes;
}
return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0;
}
SYSCALL_DEFINE6(mbind, unsigned long, start, unsigned long, len,
unsigned long, mode, const unsigned long __user *, nmask,
unsigned long, maxnode, unsigned, flags)
{
nodemask_t nodes;
int err;
unsigned short mode_flags;
mode_flags = mode & MPOL_MODE_FLAGS;
mode &= ~MPOL_MODE_FLAGS;
if (mode >= MPOL_MAX)
return -EINVAL;
if ((mode_flags & MPOL_F_STATIC_NODES) &&
(mode_flags & MPOL_F_RELATIVE_NODES))
return -EINVAL;
err = get_nodes(&nodes, nmask, maxnode);
if (err)
return err;
return do_mbind(start, len, mode, mode_flags, &nodes, flags);
}
/* Set the process memory policy */
SYSCALL_DEFINE3(set_mempolicy, int, mode, const unsigned long __user *, nmask,
unsigned long, maxnode)
{
int err;
nodemask_t nodes;
unsigned short flags;
flags = mode & MPOL_MODE_FLAGS;
mode &= ~MPOL_MODE_FLAGS;
if ((unsigned int)mode >= MPOL_MAX)
return -EINVAL;
if ((flags & MPOL_F_STATIC_NODES) && (flags & MPOL_F_RELATIVE_NODES))
return -EINVAL;
err = get_nodes(&nodes, nmask, maxnode);
if (err)
return err;
return do_set_mempolicy(mode, flags, &nodes);
}
SYSCALL_DEFINE4(migrate_pages, pid_t, pid, unsigned long, maxnode,
const unsigned long __user *, old_nodes,
const unsigned long __user *, new_nodes)
{
const struct cred *cred = current_cred(), *tcred;
struct mm_struct *mm = NULL;
struct task_struct *task;
nodemask_t task_nodes;
int err;
nodemask_t *old;
nodemask_t *new;
NODEMASK_SCRATCH(scratch);
if (!scratch)
return -ENOMEM;
old = &scratch->mask1;
new = &scratch->mask2;
err = get_nodes(old, old_nodes, maxnode);
if (err)
goto out;
err = get_nodes(new, new_nodes, maxnode);
if (err)
goto out;
/* Find the mm_struct */
rcu_read_lock();
task = pid ? find_task_by_vpid(pid) : current;
if (!task) {
rcu_read_unlock();
err = -ESRCH;
goto out;
}
get_task_struct(task);
err = -EINVAL;
/*
* Check if this process has the right to modify the specified
* process. The right exists if the process has administrative
* capabilities, superuser privileges or the same
* userid as the target process.
*/
tcred = __task_cred(task);
if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) &&
!uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) &&
!capable(CAP_SYS_NICE)) {
rcu_read_unlock();
err = -EPERM;
goto out_put;
}
rcu_read_unlock();
task_nodes = cpuset_mems_allowed(task);
/* Is the user allowed to access the target nodes? */
if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) {
err = -EPERM;
goto out_put;
}
if (!nodes_subset(*new, node_states[N_MEMORY])) {
err = -EINVAL;
goto out_put;
}
err = security_task_movememory(task);
if (err)
goto out_put;
mm = get_task_mm(task);
put_task_struct(task);
if (!mm) {
err = -EINVAL;
goto out;
}
err = do_migrate_pages(mm, old, new,
capable(CAP_SYS_NICE) ? MPOL_MF_MOVE_ALL : MPOL_MF_MOVE);
mmput(mm);
out:
NODEMASK_SCRATCH_FREE(scratch);
return err;
out_put:
put_task_struct(task);
goto out;
}
/* Retrieve NUMA policy */
SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
unsigned long __user *, nmask, unsigned long, maxnode,
unsigned long, addr, unsigned long, flags)
{
int err;
int uninitialized_var(pval);
nodemask_t nodes;
if (nmask != NULL && maxnode < MAX_NUMNODES)
return -EINVAL;
err = do_get_mempolicy(&pval, &nodes, addr, flags);
if (err)
return err;
if (policy && put_user(pval, policy))
return -EFAULT;
if (nmask)
err = copy_nodes_to_user(nmask, maxnode, &nodes);
return err;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode,
compat_ulong_t, addr, compat_ulong_t, flags)
{
long err;
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
DECLARE_BITMAP(bm, MAX_NUMNODES);
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask)
nm = compat_alloc_user_space(alloc_size);
err = sys_get_mempolicy(policy, nm, nr_bits+1, addr, flags);
if (!err && nmask) {
unsigned long copy_size;
copy_size = min_t(unsigned long, sizeof(bm), alloc_size);
err = copy_from_user(bm, nm, copy_size);
/* ensure entire bitmap is zeroed */
err |= clear_user(nmask, ALIGN(maxnode-1, 8) / 8);
err |= compat_put_bitmap(nmask, bm, nr_bits);
}
return err;
}
COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode)
{
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
DECLARE_BITMAP(bm, MAX_NUMNODES);
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask) {
if (compat_get_bitmap(bm, nmask, nr_bits))
return -EFAULT;
nm = compat_alloc_user_space(alloc_size);
if (copy_to_user(nm, bm, alloc_size))
return -EFAULT;
}
return sys_set_mempolicy(mode, nm, nr_bits+1);
}
COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len,
compat_ulong_t, mode, compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode, compat_ulong_t, flags)
{
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
nodemask_t bm;
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask) {
if (compat_get_bitmap(nodes_addr(bm), nmask, nr_bits))
return -EFAULT;
nm = compat_alloc_user_space(alloc_size);
if (copy_to_user(nm, nodes_addr(bm), alloc_size))
return -EFAULT;
}
return sys_mbind(start, len, mode, nm, nr_bits+1, flags);
}
#endif
struct mempolicy *__get_vma_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct mempolicy *pol = NULL;
if (vma) {
if (vma->vm_ops && vma->vm_ops->get_policy) {
pol = vma->vm_ops->get_policy(vma, addr);
} else if (vma->vm_policy) {
pol = vma->vm_policy;
/*
* shmem_alloc_page() passes MPOL_F_SHARED policy with
* a pseudo vma whose vma->vm_ops=NULL. Take a reference
* count on these policies which will be dropped by
* mpol_cond_put() later
*/
if (mpol_needs_cond_ref(pol))
mpol_get(pol);
}
}
return pol;
}
/*
* get_vma_policy(@vma, @addr)
* @vma: virtual memory area whose policy is sought
* @addr: address in @vma for shared policy lookup
*
* Returns effective policy for a VMA at specified address.
* Falls back to current->mempolicy or system default policy, as necessary.
* Shared policies [those marked as MPOL_F_SHARED] require an extra reference
* count--added by the get_policy() vm_op, as appropriate--to protect against
* freeing by another task. It is the caller's responsibility to free the
* extra reference for shared policies.
*/
static struct mempolicy *get_vma_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct mempolicy *pol = __get_vma_policy(vma, addr);
if (!pol)
pol = get_task_policy(current);
return pol;
}
bool vma_policy_mof(struct vm_area_struct *vma)
{
struct mempolicy *pol;
if (vma->vm_ops && vma->vm_ops->get_policy) {
bool ret = false;
pol = vma->vm_ops->get_policy(vma, vma->vm_start);
if (pol && (pol->flags & MPOL_F_MOF))
ret = true;
mpol_cond_put(pol);
return ret;
}
pol = vma->vm_policy;
if (!pol)
pol = get_task_policy(current);
return pol->flags & MPOL_F_MOF;
}
static int apply_policy_zone(struct mempolicy *policy, enum zone_type zone)
{
enum zone_type dynamic_policy_zone = policy_zone;
BUG_ON(dynamic_policy_zone == ZONE_MOVABLE);
/*
* if policy->v.nodes has movable memory only,
* we apply policy when gfp_zone(gfp) = ZONE_MOVABLE only.
*
* policy->v.nodes is intersect with node_states[N_MEMORY].
* so if the following test faile, it implies
* policy->v.nodes has movable memory only.
*/
if (!nodes_intersects(policy->v.nodes, node_states[N_HIGH_MEMORY]))
dynamic_policy_zone = ZONE_MOVABLE;
return zone >= dynamic_policy_zone;
}
/*
* Return a nodemask representing a mempolicy for filtering nodes for
* page allocation
*/
static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *policy)
{
/* Lower zones don't get a nodemask applied for MPOL_BIND */
if (unlikely(policy->mode == MPOL_BIND) &&
apply_policy_zone(policy, gfp_zone(gfp)) &&
cpuset_nodemask_valid_mems_allowed(&policy->v.nodes))
return &policy->v.nodes;
return NULL;
}
/* Return a zonelist indicated by gfp for node representing a mempolicy */
static struct zonelist *policy_zonelist(gfp_t gfp, struct mempolicy *policy,
int nd)
{
if (policy->mode == MPOL_PREFERRED && !(policy->flags & MPOL_F_LOCAL))
nd = policy->v.preferred_node;
else {
/*
* __GFP_THISNODE shouldn't even be used with the bind policy
* because we might easily break the expectation to stay on the
* requested node and not break the policy.
*/
WARN_ON_ONCE(policy->mode == MPOL_BIND && (gfp & __GFP_THISNODE));
}
return node_zonelist(nd, gfp);
}
/* Do dynamic interleaving for a process */
static unsigned interleave_nodes(struct mempolicy *policy)
{
unsigned nid, next;
struct task_struct *me = current;
nid = me->il_next;
next = next_node_in(nid, policy->v.nodes);
if (next < MAX_NUMNODES)
me->il_next = next;
return nid;
}
/*
* Depending on the memory policy provide a node from which to allocate the
* next slab entry.
*/
unsigned int mempolicy_slab_node(void)
{
struct mempolicy *policy;
int node = numa_mem_id();
if (in_interrupt())
return node;
policy = current->mempolicy;
if (!policy || policy->flags & MPOL_F_LOCAL)
return node;
switch (policy->mode) {
case MPOL_PREFERRED:
/*
* handled MPOL_F_LOCAL above
*/
return policy->v.preferred_node;
case MPOL_INTERLEAVE:
return interleave_nodes(policy);
case MPOL_BIND: {
struct zoneref *z;
/*
* Follow bind policy behavior and start allocation at the
* first node.
*/
struct zonelist *zonelist;
enum zone_type highest_zoneidx = gfp_zone(GFP_KERNEL);
zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK];
z = first_zones_zonelist(zonelist, highest_zoneidx,
&policy->v.nodes);
return z->zone ? z->zone->node : node;
}
default:
BUG();
}
}
/*
* Do static interleaving for a VMA with known offset @n. Returns the n'th
* node in pol->v.nodes (starting from n=0), wrapping around if n exceeds the
* number of present nodes.
*/
static unsigned offset_il_node(struct mempolicy *pol,
struct vm_area_struct *vma, unsigned long n)
{
unsigned nnodes = nodes_weight(pol->v.nodes);
unsigned target;
int i;
int nid;
if (!nnodes)
return numa_node_id();
target = (unsigned int)n % nnodes;
nid = first_node(pol->v.nodes);
for (i = 0; i < target; i++)
nid = next_node(nid, pol->v.nodes);
return nid;
}
/* Determine a node number for interleave */
static inline unsigned interleave_nid(struct mempolicy *pol,
struct vm_area_struct *vma, unsigned long addr, int shift)
{
if (vma) {
unsigned long off;
/*
* for small pages, there is no difference between
* shift and PAGE_SHIFT, so the bit-shift is safe.
* for huge pages, since vm_pgoff is in units of small
* pages, we need to shift off the always 0 bits to get
* a useful offset.
*/
BUG_ON(shift < PAGE_SHIFT);
off = vma->vm_pgoff >> (shift - PAGE_SHIFT);
off += (addr - vma->vm_start) >> shift;
return offset_il_node(pol, vma, off);
} else
return interleave_nodes(pol);
}
#ifdef CONFIG_HUGETLBFS
/*
* huge_zonelist(@vma, @addr, @gfp_flags, @mpol)
* @vma: virtual memory area whose policy is sought
* @addr: address in @vma for shared policy lookup and interleave policy
* @gfp_flags: for requested zone
* @mpol: pointer to mempolicy pointer for reference counted mempolicy
* @nodemask: pointer to nodemask pointer for MPOL_BIND nodemask
*
* Returns a zonelist suitable for a huge page allocation and a pointer
* to the struct mempolicy for conditional unref after allocation.
* If the effective policy is 'BIND, returns a pointer to the mempolicy's
* @nodemask for filtering the zonelist.
*
* Must be protected by read_mems_allowed_begin()
*/
struct zonelist *huge_zonelist(struct vm_area_struct *vma, unsigned long addr,
gfp_t gfp_flags, struct mempolicy **mpol,
nodemask_t **nodemask)
{
struct zonelist *zl;
*mpol = get_vma_policy(vma, addr);
*nodemask = NULL; /* assume !MPOL_BIND */
if (unlikely((*mpol)->mode == MPOL_INTERLEAVE)) {
zl = node_zonelist(interleave_nid(*mpol, vma, addr,
huge_page_shift(hstate_vma(vma))), gfp_flags);
} else {
zl = policy_zonelist(gfp_flags, *mpol, numa_node_id());
if ((*mpol)->mode == MPOL_BIND)
*nodemask = &(*mpol)->v.nodes;
}
return zl;
}
/*
* init_nodemask_of_mempolicy
*
* If the current task's mempolicy is "default" [NULL], return 'false'
* to indicate default policy. Otherwise, extract the policy nodemask
* for 'bind' or 'interleave' policy into the argument nodemask, or
* initialize the argument nodemask to contain the single node for
* 'preferred' or 'local' policy and return 'true' to indicate presence
* of non-default mempolicy.
*
* We don't bother with reference counting the mempolicy [mpol_get/put]
* because the current task is examining it's own mempolicy and a task's
* mempolicy is only ever changed by the task itself.
*
* N.B., it is the caller's responsibility to free a returned nodemask.
*/
bool init_nodemask_of_mempolicy(nodemask_t *mask)
{
struct mempolicy *mempolicy;
int nid;
if (!(mask && current->mempolicy))
return false;
task_lock(current);
mempolicy = current->mempolicy;
switch (mempolicy->mode) {
case MPOL_PREFERRED:
if (mempolicy->flags & MPOL_F_LOCAL)
nid = numa_node_id();
else
nid = mempolicy->v.preferred_node;
init_nodemask_of_node(mask, nid);
break;
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
*mask = mempolicy->v.nodes;
break;
default:
BUG();
}
task_unlock(current);
return true;
}
#endif
/*
* mempolicy_nodemask_intersects
*
* If tsk's mempolicy is "default" [NULL], return 'true' to indicate default
* policy. Otherwise, check for intersection between mask and the policy
* nodemask for 'bind' or 'interleave' policy. For 'perferred' or 'local'
* policy, always return true since it may allocate elsewhere on fallback.
*
* Takes task_lock(tsk) to prevent freeing of its mempolicy.
*/
bool mempolicy_nodemask_intersects(struct task_struct *tsk,
const nodemask_t *mask)
{
struct mempolicy *mempolicy;
bool ret = true;
if (!mask)
return ret;
task_lock(tsk);
mempolicy = tsk->mempolicy;
if (!mempolicy)
goto out;
switch (mempolicy->mode) {
case MPOL_PREFERRED:
/*
* MPOL_PREFERRED and MPOL_F_LOCAL are only preferred nodes to
* allocate from, they may fallback to other nodes when oom.
* Thus, it's possible for tsk to have allocated memory from
* nodes in mask.
*/
break;
case MPOL_BIND:
case MPOL_INTERLEAVE:
ret = nodes_intersects(mempolicy->v.nodes, *mask);
break;
default:
BUG();
}
out:
task_unlock(tsk);
return ret;
}
/* Allocate a page in interleaved policy.
Own path because it needs to do special accounting. */
static struct page *alloc_page_interleave(gfp_t gfp, unsigned order,
unsigned nid)
{
struct zonelist *zl;
struct page *page;
zl = node_zonelist(nid, gfp);
page = __alloc_pages(gfp, order, zl);
if (page && page_zone(page) == zonelist_zone(&zl->_zonerefs[0]))
inc_zone_page_state(page, NUMA_INTERLEAVE_HIT);
return page;
}
/**
* alloc_pages_vma - Allocate a page for a VMA.
*
* @gfp:
* %GFP_USER user allocation.
* %GFP_KERNEL kernel allocations,
* %GFP_HIGHMEM highmem/user allocations,
* %GFP_FS allocation should not call back into a file system.
* %GFP_ATOMIC don't sleep.
*
* @order:Order of the GFP allocation.
* @vma: Pointer to VMA or NULL if not available.
* @addr: Virtual Address of the allocation. Must be inside the VMA.
* @node: Which node to prefer for allocation (modulo policy).
* @hugepage: for hugepages try only the preferred node if possible
*
* This function allocates a page from the kernel page pool and applies
* a NUMA policy associated with the VMA or the current process.
* When VMA is not NULL caller must hold down_read on the mmap_sem of the
* mm_struct of the VMA to prevent it from going away. Should be used for
* all allocations for pages that will be mapped into user space. Returns
* NULL when no page can be allocated.
*/
struct page *
alloc_pages_vma(gfp_t gfp, int order, struct vm_area_struct *vma,
unsigned long addr, int node, bool hugepage)
{
struct mempolicy *pol;
struct page *page;
unsigned int cpuset_mems_cookie;
struct zonelist *zl;
nodemask_t *nmask;
retry_cpuset:
pol = get_vma_policy(vma, addr);
cpuset_mems_cookie = read_mems_allowed_begin();
if (pol->mode == MPOL_INTERLEAVE) {
unsigned nid;
nid = interleave_nid(pol, vma, addr, PAGE_SHIFT + order);
mpol_cond_put(pol);
page = alloc_page_interleave(gfp, order, nid);
goto out;
}
if (unlikely(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && hugepage)) {
int hpage_node = node;
/*
* For hugepage allocation and non-interleave policy which
* allows the current node (or other explicitly preferred
* node) we only try to allocate from the current/preferred
* node and don't fall back to other nodes, as the cost of
* remote accesses would likely offset THP benefits.
*
* If the policy is interleave, or does not allow the current
* node in its nodemask, we allocate the standard way.
*/
if (pol->mode == MPOL_PREFERRED &&
!(pol->flags & MPOL_F_LOCAL))
hpage_node = pol->v.preferred_node;
nmask = policy_nodemask(gfp, pol);
if (!nmask || node_isset(hpage_node, *nmask)) {
mpol_cond_put(pol);
page = __alloc_pages_node(hpage_node,
gfp | __GFP_THISNODE, order);
goto out;
}
}
nmask = policy_nodemask(gfp, pol);
zl = policy_zonelist(gfp, pol, node);
page = __alloc_pages_nodemask(gfp, order, zl, nmask);
mpol_cond_put(pol);
out:
if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
goto retry_cpuset;
return page;
}
/**
* alloc_pages_current - Allocate pages.
*
* @gfp:
* %GFP_USER user allocation,
* %GFP_KERNEL kernel allocation,
* %GFP_HIGHMEM highmem allocation,
* %GFP_FS don't call back into a file system.
* %GFP_ATOMIC don't sleep.
* @order: Power of two of allocation size in pages. 0 is a single page.
*
* Allocate a page from the kernel page pool. When not in
* interrupt context and apply the current process NUMA policy.
* Returns NULL when no page can be allocated.
*
* Don't call cpuset_update_task_memory_state() unless
* 1) it's ok to take cpuset_sem (can WAIT), and
* 2) allocating for current task (not interrupt).
*/
struct page *alloc_pages_current(gfp_t gfp, unsigned order)
{
struct mempolicy *pol = &default_policy;
struct page *page;
unsigned int cpuset_mems_cookie;
if (!in_interrupt() && !(gfp & __GFP_THISNODE))
pol = get_task_policy(current);
retry_cpuset:
cpuset_mems_cookie = read_mems_allowed_begin();
/*
* No reference counting needed for current->mempolicy
* nor system default_policy
*/
if (pol->mode == MPOL_INTERLEAVE)
page = alloc_page_interleave(gfp, order, interleave_nodes(pol));
else
page = __alloc_pages_nodemask(gfp, order,
policy_zonelist(gfp, pol, numa_node_id()),
policy_nodemask(gfp, pol));
if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
goto retry_cpuset;
return page;
}
EXPORT_SYMBOL(alloc_pages_current);
int vma_dup_policy(struct vm_area_struct *src, struct vm_area_struct *dst)
{
struct mempolicy *pol = mpol_dup(vma_policy(src));
if (IS_ERR(pol))
return PTR_ERR(pol);
dst->vm_policy = pol;
return 0;
}
/*
* If mpol_dup() sees current->cpuset == cpuset_being_rebound, then it
* rebinds the mempolicy its copying by calling mpol_rebind_policy()
* with the mems_allowed returned by cpuset_mems_allowed(). This
* keeps mempolicies cpuset relative after its cpuset moves. See
* further kernel/cpuset.c update_nodemask().
*
* current's mempolicy may be rebinded by the other task(the task that changes
* cpuset's mems), so we needn't do rebind work for current task.
*/
/* Slow path of a mempolicy duplicate */
struct mempolicy *__mpol_dup(struct mempolicy *old)
{
struct mempolicy *new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!new)
return ERR_PTR(-ENOMEM);
/* task's mempolicy is protected by alloc_lock */
if (old == current->mempolicy) {
task_lock(current);
*new = *old;
task_unlock(current);
} else
*new = *old;
if (current_cpuset_is_being_rebound()) {
nodemask_t mems = cpuset_mems_allowed(current);
if (new->flags & MPOL_F_REBINDING)
mpol_rebind_policy(new, &mems, MPOL_REBIND_STEP2);
else
mpol_rebind_policy(new, &mems, MPOL_REBIND_ONCE);
}
atomic_set(&new->refcnt, 1);
return new;
}
/* Slow path of a mempolicy comparison */
bool __mpol_equal(struct mempolicy *a, struct mempolicy *b)
{
if (!a || !b)
return false;
if (a->mode != b->mode)
return false;
if (a->flags != b->flags)
return false;
if (mpol_store_user_nodemask(a))
if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask))
return false;
switch (a->mode) {
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
return !!nodes_equal(a->v.nodes, b->v.nodes);
case MPOL_PREFERRED:
return a->v.preferred_node == b->v.preferred_node;
default:
BUG();
return false;
}
}
/*
* Shared memory backing store policy support.
*
* Remember policies even when nobody has shared memory mapped.
* The policies are kept in Red-Black tree linked from the inode.
* They are protected by the sp->lock rwlock, which should be held
* for any accesses to the tree.
*/
/*
* lookup first element intersecting start-end. Caller holds sp->lock for
* reading or for writing
*/
static struct sp_node *
sp_lookup(struct shared_policy *sp, unsigned long start, unsigned long end)
{
struct rb_node *n = sp->root.rb_node;
while (n) {
struct sp_node *p = rb_entry(n, struct sp_node, nd);
if (start >= p->end)
n = n->rb_right;
else if (end <= p->start)
n = n->rb_left;
else
break;
}
if (!n)
return NULL;
for (;;) {
struct sp_node *w = NULL;
struct rb_node *prev = rb_prev(n);
if (!prev)
break;
w = rb_entry(prev, struct sp_node, nd);
if (w->end <= start)
break;
n = prev;
}
return rb_entry(n, struct sp_node, nd);
}
/*
* Insert a new shared policy into the list. Caller holds sp->lock for
* writing.
*/
static void sp_insert(struct shared_policy *sp, struct sp_node *new)
{
struct rb_node **p = &sp->root.rb_node;
struct rb_node *parent = NULL;
struct sp_node *nd;
while (*p) {
parent = *p;
nd = rb_entry(parent, struct sp_node, nd);
if (new->start < nd->start)
p = &(*p)->rb_left;
else if (new->end > nd->end)
p = &(*p)->rb_right;
else
BUG();
}
rb_link_node(&new->nd, parent, p);
rb_insert_color(&new->nd, &sp->root);
pr_debug("inserting %lx-%lx: %d\n", new->start, new->end,
new->policy ? new->policy->mode : 0);
}
/* Find shared policy intersecting idx */
struct mempolicy *
mpol_shared_policy_lookup(struct shared_policy *sp, unsigned long idx)
{
struct mempolicy *pol = NULL;
struct sp_node *sn;
if (!sp->root.rb_node)
return NULL;
read_lock(&sp->lock);
sn = sp_lookup(sp, idx, idx+1);
if (sn) {
mpol_get(sn->policy);
pol = sn->policy;
}
read_unlock(&sp->lock);
return pol;
}
static void sp_free(struct sp_node *n)
{
mpol_put(n->policy);
kmem_cache_free(sn_cache, n);
}
/**
* mpol_misplaced - check whether current page node is valid in policy
*
* @page: page to be checked
* @vma: vm area where page mapped
* @addr: virtual address where page mapped
*
* Lookup current policy node id for vma,addr and "compare to" page's
* node id.
*
* Returns:
* -1 - not misplaced, page is in the right node
* node - node id where the page should be
*
* Policy determination "mimics" alloc_page_vma().
* Called from fault path where we know the vma and faulting address.
*/
int mpol_misplaced(struct page *page, struct vm_area_struct *vma, unsigned long addr)
{
struct mempolicy *pol;
struct zoneref *z;
int curnid = page_to_nid(page);
unsigned long pgoff;
int thiscpu = raw_smp_processor_id();
int thisnid = cpu_to_node(thiscpu);
int polnid = -1;
int ret = -1;
BUG_ON(!vma);
pol = get_vma_policy(vma, addr);
if (!(pol->flags & MPOL_F_MOF))
goto out;
switch (pol->mode) {
case MPOL_INTERLEAVE:
BUG_ON(addr >= vma->vm_end);
BUG_ON(addr < vma->vm_start);
pgoff = vma->vm_pgoff;
pgoff += (addr - vma->vm_start) >> PAGE_SHIFT;
polnid = offset_il_node(pol, vma, pgoff);
break;
case MPOL_PREFERRED:
if (pol->flags & MPOL_F_LOCAL)
polnid = numa_node_id();
else
polnid = pol->v.preferred_node;
break;
case MPOL_BIND:
/*
* allows binding to multiple nodes.
* use current page if in policy nodemask,
* else select nearest allowed node, if any.
* If no allowed nodes, use current [!misplaced].
*/
if (node_isset(curnid, pol->v.nodes))
goto out;
z = first_zones_zonelist(
node_zonelist(numa_node_id(), GFP_HIGHUSER),
gfp_zone(GFP_HIGHUSER),
&pol->v.nodes);
polnid = z->zone->node;
break;
default:
BUG();
}
/* Migrate the page towards the node whose CPU is referencing it */
if (pol->flags & MPOL_F_MORON) {
polnid = thisnid;
if (!should_numa_migrate_memory(current, page, curnid, thiscpu))
goto out;
}
if (curnid != polnid)
ret = polnid;
out:
mpol_cond_put(pol);
return ret;
}
/*
* Drop the (possibly final) reference to task->mempolicy. It needs to be
* dropped after task->mempolicy is set to NULL so that any allocation done as
* part of its kmem_cache_free(), such as by KASAN, doesn't reference a freed
* policy.
*/
void mpol_put_task_policy(struct task_struct *task)
{
struct mempolicy *pol;
task_lock(task);
pol = task->mempolicy;
task->mempolicy = NULL;
task_unlock(task);
mpol_put(pol);
}
static void sp_delete(struct shared_policy *sp, struct sp_node *n)
{
pr_debug("deleting %lx-l%lx\n", n->start, n->end);
rb_erase(&n->nd, &sp->root);
sp_free(n);
}
static void sp_node_init(struct sp_node *node, unsigned long start,
unsigned long end, struct mempolicy *pol)
{
node->start = start;
node->end = end;
node->policy = pol;
}
static struct sp_node *sp_alloc(unsigned long start, unsigned long end,
struct mempolicy *pol)
{
struct sp_node *n;
struct mempolicy *newpol;
n = kmem_cache_alloc(sn_cache, GFP_KERNEL);
if (!n)
return NULL;
newpol = mpol_dup(pol);
if (IS_ERR(newpol)) {
kmem_cache_free(sn_cache, n);
return NULL;
}
newpol->flags |= MPOL_F_SHARED;
sp_node_init(n, start, end, newpol);
return n;
}
/* Replace a policy range. */
static int shared_policy_replace(struct shared_policy *sp, unsigned long start,
unsigned long end, struct sp_node *new)
{
struct sp_node *n;
struct sp_node *n_new = NULL;
struct mempolicy *mpol_new = NULL;
int ret = 0;
restart:
write_lock(&sp->lock);
n = sp_lookup(sp, start, end);
/* Take care of old policies in the same range. */
while (n && n->start < end) {
struct rb_node *next = rb_next(&n->nd);
if (n->start >= start) {
if (n->end <= end)
sp_delete(sp, n);
else
n->start = end;
} else {
/* Old policy spanning whole new range. */
if (n->end > end) {
if (!n_new)
goto alloc_new;
*mpol_new = *n->policy;
atomic_set(&mpol_new->refcnt, 1);
sp_node_init(n_new, end, n->end, mpol_new);
n->end = start;
sp_insert(sp, n_new);
n_new = NULL;
mpol_new = NULL;
break;
} else
n->end = start;
}
if (!next)
break;
n = rb_entry(next, struct sp_node, nd);
}
if (new)
sp_insert(sp, new);
write_unlock(&sp->lock);
ret = 0;
err_out:
if (mpol_new)
mpol_put(mpol_new);
if (n_new)
kmem_cache_free(sn_cache, n_new);
return ret;
alloc_new:
write_unlock(&sp->lock);
ret = -ENOMEM;
n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL);
if (!n_new)
goto err_out;
mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!mpol_new)
goto err_out;
goto restart;
}
/**
* mpol_shared_policy_init - initialize shared policy for inode
* @sp: pointer to inode shared policy
* @mpol: struct mempolicy to install
*
* Install non-NULL @mpol in inode's shared policy rb-tree.
* On entry, the current task has a reference on a non-NULL @mpol.
* This must be released on exit.
* This is called at get_inode() calls and we can use GFP_KERNEL.
*/
void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol)
{
int ret;
sp->root = RB_ROOT; /* empty tree == default mempolicy */
rwlock_init(&sp->lock);
if (mpol) {
struct vm_area_struct pvma;
struct mempolicy *new;
NODEMASK_SCRATCH(scratch);
if (!scratch)
goto put_mpol;
/* contextualize the tmpfs mount point mempolicy */
new = mpol_new(mpol->mode, mpol->flags, &mpol->w.user_nodemask);
if (IS_ERR(new))
goto free_scratch; /* no valid nodemask intersection */
task_lock(current);
ret = mpol_set_nodemask(new, &mpol->w.user_nodemask, scratch);
task_unlock(current);
if (ret)
goto put_new;
/* Create pseudo-vma that contains just the policy */
memset(&pvma, 0, sizeof(struct vm_area_struct));
pvma.vm_end = TASK_SIZE; /* policy covers entire file */
mpol_set_shared_policy(sp, &pvma, new); /* adds ref */
put_new:
mpol_put(new); /* drop initial ref */
free_scratch:
NODEMASK_SCRATCH_FREE(scratch);
put_mpol:
mpol_put(mpol); /* drop our incoming ref on sb mpol */
}
}
int mpol_set_shared_policy(struct shared_policy *info,
struct vm_area_struct *vma, struct mempolicy *npol)
{
int err;
struct sp_node *new = NULL;
unsigned long sz = vma_pages(vma);
pr_debug("set_shared_policy %lx sz %lu %d %d %lx\n",
vma->vm_pgoff,
sz, npol ? npol->mode : -1,
npol ? npol->flags : -1,
npol ? nodes_addr(npol->v.nodes)[0] : NUMA_NO_NODE);
if (npol) {
new = sp_alloc(vma->vm_pgoff, vma->vm_pgoff + sz, npol);
if (!new)
return -ENOMEM;
}
err = shared_policy_replace(info, vma->vm_pgoff, vma->vm_pgoff+sz, new);
if (err && new)
sp_free(new);
return err;
}
/* Free a backing policy store on inode delete. */
void mpol_free_shared_policy(struct shared_policy *p)
{
struct sp_node *n;
struct rb_node *next;
if (!p->root.rb_node)
return;
write_lock(&p->lock);
next = rb_first(&p->root);
while (next) {
n = rb_entry(next, struct sp_node, nd);
next = rb_next(&n->nd);
sp_delete(p, n);
}
write_unlock(&p->lock);
}
#ifdef CONFIG_NUMA_BALANCING
static int __initdata numabalancing_override;
static void __init check_numabalancing_enable(void)
{
bool numabalancing_default = false;
if (IS_ENABLED(CONFIG_NUMA_BALANCING_DEFAULT_ENABLED))
numabalancing_default = true;
/* Parsed by setup_numabalancing. override == 1 enables, -1 disables */
if (numabalancing_override)
set_numabalancing_state(numabalancing_override == 1);
if (num_online_nodes() > 1 && !numabalancing_override) {
pr_info("%s automatic NUMA balancing. Configure with numa_balancing= or the kernel.numa_balancing sysctl\n",
numabalancing_default ? "Enabling" : "Disabling");
set_numabalancing_state(numabalancing_default);
}
}
static int __init setup_numabalancing(char *str)
{
int ret = 0;
if (!str)
goto out;
if (!strcmp(str, "enable")) {
numabalancing_override = 1;
ret = 1;
} else if (!strcmp(str, "disable")) {
numabalancing_override = -1;
ret = 1;
}
out:
if (!ret)
pr_warn("Unable to parse numa_balancing=\n");
return ret;
}
__setup("numa_balancing=", setup_numabalancing);
#else
static inline void __init check_numabalancing_enable(void)
{
}
#endif /* CONFIG_NUMA_BALANCING */
/* assumes fs == KERNEL_DS */
void __init numa_policy_init(void)
{
nodemask_t interleave_nodes;
unsigned long largest = 0;
int nid, prefer = 0;
policy_cache = kmem_cache_create("numa_policy",
sizeof(struct mempolicy),
0, SLAB_PANIC, NULL);
sn_cache = kmem_cache_create("shared_policy_node",
sizeof(struct sp_node),
0, SLAB_PANIC, NULL);
for_each_node(nid) {
preferred_node_policy[nid] = (struct mempolicy) {
.refcnt = ATOMIC_INIT(1),
.mode = MPOL_PREFERRED,
.flags = MPOL_F_MOF | MPOL_F_MORON,
.v = { .preferred_node = nid, },
};
}
/*
* Set interleaving policy for system init. Interleaving is only
* enabled across suitably sized nodes (default is >= 16MB), or
* fall back to the largest node if they're all smaller.
*/
nodes_clear(interleave_nodes);
for_each_node_state(nid, N_MEMORY) {
unsigned long total_pages = node_present_pages(nid);
/* Preserve the largest node */
if (largest < total_pages) {
largest = total_pages;
prefer = nid;
}
/* Interleave this node? */
if ((total_pages << PAGE_SHIFT) >= (16 << 20))
node_set(nid, interleave_nodes);
}
/* All too small, use the largest */
if (unlikely(nodes_empty(interleave_nodes)))
node_set(prefer, interleave_nodes);
if (do_set_mempolicy(MPOL_INTERLEAVE, 0, &interleave_nodes))
pr_err("%s: interleaving failed\n", __func__);
check_numabalancing_enable();
}
/* Reset policy of current process to default */
void numa_default_policy(void)
{
do_set_mempolicy(MPOL_DEFAULT, 0, NULL);
}
/*
* Parse and format mempolicy from/to strings
*/
/*
* "local" is implemented internally by MPOL_PREFERRED with MPOL_F_LOCAL flag.
*/
static const char * const policy_modes[] =
{
[MPOL_DEFAULT] = "default",
[MPOL_PREFERRED] = "prefer",
[MPOL_BIND] = "bind",
[MPOL_INTERLEAVE] = "interleave",
[MPOL_LOCAL] = "local",
};
#ifdef CONFIG_TMPFS
/**
* mpol_parse_str - parse string to mempolicy, for tmpfs mpol mount option.
* @str: string containing mempolicy to parse
* @mpol: pointer to struct mempolicy pointer, returned on success.
*
* Format of input:
* <mode>[=<flags>][:<nodelist>]
*
* On success, returns 0, else 1
*/
int mpol_parse_str(char *str, struct mempolicy **mpol)
{
struct mempolicy *new = NULL;
unsigned short mode;
unsigned short mode_flags;
nodemask_t nodes;
char *nodelist = strchr(str, ':');
char *flags = strchr(str, '=');
int err = 1;
if (nodelist) {
/* NUL-terminate mode or flags string */
*nodelist++ = '\0';
if (nodelist_parse(nodelist, nodes))
goto out;
if (!nodes_subset(nodes, node_states[N_MEMORY]))
goto out;
} else
nodes_clear(nodes);
if (flags)
*flags++ = '\0'; /* terminate mode string */
for (mode = 0; mode < MPOL_MAX; mode++) {
if (!strcmp(str, policy_modes[mode])) {
break;
}
}
if (mode >= MPOL_MAX)
goto out;
switch (mode) {
case MPOL_PREFERRED:
/*
* Insist on a nodelist of one node only
*/
if (nodelist) {
char *rest = nodelist;
while (isdigit(*rest))
rest++;
if (*rest)
goto out;
}
break;
case MPOL_INTERLEAVE:
/*
* Default to online nodes with memory if no nodelist
*/
if (!nodelist)
nodes = node_states[N_MEMORY];
break;
case MPOL_LOCAL:
/*
* Don't allow a nodelist; mpol_new() checks flags
*/
if (nodelist)
goto out;
mode = MPOL_PREFERRED;
break;
case MPOL_DEFAULT:
/*
* Insist on a empty nodelist
*/
if (!nodelist)
err = 0;
goto out;
case MPOL_BIND:
/*
* Insist on a nodelist
*/
if (!nodelist)
goto out;
}
mode_flags = 0;
if (flags) {
/*
* Currently, we only support two mutually exclusive
* mode flags.
*/
if (!strcmp(flags, "static"))
mode_flags |= MPOL_F_STATIC_NODES;
else if (!strcmp(flags, "relative"))
mode_flags |= MPOL_F_RELATIVE_NODES;
else
goto out;
}
new = mpol_new(mode, mode_flags, &nodes);
if (IS_ERR(new))
goto out;
/*
* Save nodes for mpol_to_str() to show the tmpfs mount options
* for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.
*/
if (mode != MPOL_PREFERRED)
new->v.nodes = nodes;
else if (nodelist)
new->v.preferred_node = first_node(nodes);
else
new->flags |= MPOL_F_LOCAL;
/*
* Save nodes for contextualization: this will be used to "clone"
* the mempolicy in a specific context [cpuset] at a later time.
*/
new->w.user_nodemask = nodes;
err = 0;
out:
/* Restore string for error message */
if (nodelist)
*--nodelist = ':';
if (flags)
*--flags = '=';
if (!err)
*mpol = new;
return err;
}
#endif /* CONFIG_TMPFS */
/**
* mpol_to_str - format a mempolicy structure for printing
* @buffer: to contain formatted mempolicy string
* @maxlen: length of @buffer
* @pol: pointer to mempolicy to be formatted
*
* Convert @pol into a string. If @buffer is too short, truncate the string.
* Recommend a @maxlen of at least 32 for the longest mode, "interleave", the
* longest flag, "relative", and to display at least a few node ids.
*/
void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol)
{
char *p = buffer;
nodemask_t nodes = NODE_MASK_NONE;
unsigned short mode = MPOL_DEFAULT;
unsigned short flags = 0;
if (pol && pol != &default_policy && !(pol->flags & MPOL_F_MORON)) {
mode = pol->mode;
flags = pol->flags;
}
switch (mode) {
case MPOL_DEFAULT:
break;
case MPOL_PREFERRED:
if (flags & MPOL_F_LOCAL)
mode = MPOL_LOCAL;
else
node_set(pol->v.preferred_node, nodes);
break;
case MPOL_BIND:
case MPOL_INTERLEAVE:
nodes = pol->v.nodes;
break;
default:
WARN_ON_ONCE(1);
snprintf(p, maxlen, "unknown");
return;
}
p += snprintf(p, maxlen, "%s", policy_modes[mode]);
if (flags & MPOL_MODE_FLAGS) {
p += snprintf(p, buffer + maxlen - p, "=");
/*
* Currently, the only defined flags are mutually exclusive
*/
if (flags & MPOL_F_STATIC_NODES)
p += snprintf(p, buffer + maxlen - p, "static");
else if (flags & MPOL_F_RELATIVE_NODES)
p += snprintf(p, buffer + maxlen - p, "relative");
}
if (!nodes_empty(nodes))
p += scnprintf(p, buffer + maxlen - p, ":%*pbl",
nodemask_pr_args(&nodes));
}
| ./CrossVul/dataset_final_sorted/CWE-388/c/good_3289_0 |
crossvul-cpp_data_good_5008_0 | /* $Id: minissdpd.c,v 1.37 2014/02/28 18:39:11 nanard Exp $ */
/* MiniUPnP project
* (c) 2007-2014 Thomas Bernard
* website : http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <syslog.h>
#include <ctype.h>
#include <time.h>
#include <sys/queue.h>
/* for chmod : */
#include <sys/stat.h>
/* unix sockets */
#include <sys/un.h>
/* for getpwnam() and getgrnam() */
#include <pwd.h>
#include <grp.h>
#include "upnputils.h"
#include "openssdpsocket.h"
#include "daemonize.h"
#include "codelength.h"
#include "ifacewatch.h"
/* current request management stucture */
struct reqelem {
int socket;
LIST_ENTRY(reqelem) entries;
};
/* divice data structures */
struct header {
const char * p; /* string pointer */
int l; /* string length */
};
#define HEADER_NT 0
#define HEADER_USN 1
#define HEADER_LOCATION 2
struct device {
struct device * next;
time_t t; /* validity time */
struct header headers[3]; /* NT, USN and LOCATION headers */
char data[];
};
#define NTS_SSDP_ALIVE 1
#define NTS_SSDP_BYEBYE 2
#define NTS_SSDP_UPDATE 3
/* discovered device list kept in memory */
struct device * devlist = 0;
/* bootid and configid */
unsigned int upnp_bootid = 1;
unsigned int upnp_configid = 1337;
static const char *
nts_to_str(int nts)
{
switch(nts)
{
case NTS_SSDP_ALIVE:
return "ssdp:alive";
case NTS_SSDP_BYEBYE:
return "ssdp:byebye";
case NTS_SSDP_UPDATE:
return "ssdp:update";
}
return "unknown";
}
/* updateDevice() :
* adds or updates the device to the list.
* return value :
* 0 : the device was updated (or nothing done)
* 1 : the device was new */
static int
updateDevice(const struct header * headers, time_t t)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist; */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
/*printf("found! %d\n", (int)(t - p->t));*/
syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
p->t = t;
/* update Location ! */
if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l)
{
p = realloc(p, sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l );
if(!p) /* allocation error */
{
syslog(LOG_ERR, "updateDevice() : memory allocation error");
return 0;
}
*pp = p;
}
memcpy(p->data + p->headers[0].l + p->headers[1].l,
headers[2].p, headers[2].l);
return 0;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_INFO, "new device discovered : %.*s",
headers[HEADER_USN].l, headers[HEADER_USN].p);
/* add */
{
char * pc;
int i;
p = malloc( sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l );
if(!p) {
syslog(LOG_ERR, "updateDevice(): cannot allocate memory");
return -1;
}
p->next = devlist;
p->t = t;
pc = p->data;
for(i = 0; i < 3; i++)
{
p->headers[i].p = pc;
p->headers[i].l = headers[i].l;
memcpy(pc, headers[i].p, headers[i].l);
pc += headers[i].l;
}
devlist = p;
}
return 1;
}
/* removeDevice() :
* remove a device from the list
* return value :
* 0 : no device removed
* -1 : device removed */
static int
removeDevice(const struct header * headers)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
syslog(LOG_INFO, "remove device : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
*pp = p->next;
free(p);
return -1;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_WARNING, "device not found for removing : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
return 0;
}
/* SendSSDPMSEARCHResponse() :
* build and send response to M-SEARCH SSDP packets. */
static void
SendSSDPMSEARCHResponse(int s, const struct sockaddr * sockname,
const char * st, const char * usn,
const char * server, const char * location)
{
int l, n;
char buf[512];
socklen_t sockname_len;
/*
* follow guideline from document "UPnP Device Architecture 1.0"
* uppercase is recommended.
* DATE: is recommended
* SERVER: OS/ver UPnP/1.0 miniupnpd/1.0
* - check what to put in the 'Cache-Control' header
*
* have a look at the document "UPnP Device Architecture v1.1 */
l = snprintf(buf, sizeof(buf), "HTTP/1.1 200 OK\r\n"
"CACHE-CONTROL: max-age=120\r\n"
/*"DATE: ...\r\n"*/
"ST: %s\r\n"
"USN: %s\r\n"
"EXT:\r\n"
"SERVER: %s\r\n"
"LOCATION: %s\r\n"
"OPT: \"http://schemas.upnp.org/upnp/1/0/\"; ns=01\r\n" /* UDA v1.1 */
"01-NLS: %u\r\n" /* same as BOOTID. UDA v1.1 */
"BOOTID.UPNP.ORG: %u\r\n" /* UDA v1.1 */
"CONFIGID.UPNP.ORG: %u\r\n" /* UDA v1.1 */
"\r\n",
st, usn,
server, location,
upnp_bootid, upnp_bootid, upnp_configid);
#ifdef ENABLE_IPV6
sockname_len = (sockname->sa_family == PF_INET6)
? sizeof(struct sockaddr_in6)
: sizeof(struct sockaddr_in);
#else
sockname_len = sizeof(struct sockaddr_in);
#endif
n = sendto(s, buf, l, 0,
sockname, sockname_len );
if(n < 0) {
/* XXX handle EINTR, EAGAIN, EWOULDBLOCK */
syslog(LOG_ERR, "sendto(udp): %m");
}
}
/* Services stored for answering to M-SEARCH */
struct service {
char * st; /* Service type */
char * usn; /* Unique identifier */
char * server; /* Server string */
char * location; /* URL */
LIST_ENTRY(service) entries;
};
LIST_HEAD(servicehead, service) servicelisthead;
/* Process M-SEARCH requests */
static void
processMSEARCH(int s, const char * st, int st_len,
const struct sockaddr * addr)
{
struct service * serv;
#ifdef ENABLE_IPV6
char buf[64];
#endif
if(!st || st_len==0)
return;
#ifdef ENABLE_IPV6
sockaddr_to_string(addr, buf, sizeof(buf));
syslog(LOG_INFO, "SSDP M-SEARCH from %s ST:%.*s",
buf, st_len, st);
#else
syslog(LOG_INFO, "SSDP M-SEARCH from %s:%d ST: %.*s",
inet_ntoa(((const struct sockaddr_in *)addr)->sin_addr),
ntohs(((const struct sockaddr_in *)addr)->sin_port),
st_len, st);
#endif
if(st_len==8 && (0==memcmp(st, "ssdp:all", 8))) {
/* send a response for all services */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, serv->usn,
serv->server, serv->location);
}
} else if(st_len > 5 && (0==memcmp(st, "uuid:", 5))) {
/* find a matching UUID value */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strncmp(serv->usn, st, st_len)) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, serv->usn,
serv->server, serv->location);
}
}
} else {
/* find matching services */
/* remove version at the end of the ST string */
if(st[st_len-2]==':' && isdigit(st[st_len-1]))
st_len -= 2;
/* answer for each matching service */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strncmp(serv->st, st, st_len)) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, serv->usn,
serv->server, serv->location);
}
}
}
}
/**
* helper function.
* reject any non ASCII or non printable character.
*/
static int
containsForbiddenChars(const unsigned char * p, int len)
{
while(len > 0) {
if(*p < ' ' || *p >= '\x7f')
return 1;
p++;
len--;
}
return 0;
}
#define METHOD_MSEARCH 1
#define METHOD_NOTIFY 2
/* ParseSSDPPacket() :
* parse a received SSDP Packet and call
* updateDevice() or removeDevice() as needed
* return value :
* -1 : a device was removed
* 0 : no device removed nor added
* 1 : a device was added. */
static int
ParseSSDPPacket(int s, const char * p, ssize_t n,
const struct sockaddr * addr)
{
const char * linestart;
const char * lineend;
const char * nameend;
const char * valuestart;
struct header headers[3];
int i, r = 0;
int methodlen;
int nts = -1;
int method = -1;
unsigned int lifetime = 180; /* 3 minutes by default */
const char * st = NULL;
int st_len = 0;
memset(headers, 0, sizeof(headers));
for(methodlen = 0;
methodlen < n && (isalpha(p[methodlen]) || p[methodlen]=='-');
methodlen++);
if(methodlen==8 && 0==memcmp(p, "M-SEARCH", 8))
method = METHOD_MSEARCH;
else if(methodlen==6 && 0==memcmp(p, "NOTIFY", 6))
method = METHOD_NOTIFY;
else if(methodlen==4 && 0==memcmp(p, "HTTP", 4)) {
/* answer to a M-SEARCH => process it as a NOTIFY
* with NTS: ssdp:alive */
method = METHOD_NOTIFY;
nts = NTS_SSDP_ALIVE;
}
linestart = p;
while(linestart < p + n - 2) {
/* start parsing the line : detect line end */
lineend = linestart;
while(lineend < p + n && *lineend != '\n' && *lineend != '\r')
lineend++;
/*printf("line: '%.*s'\n", lineend - linestart, linestart);*/
/* detect name end : ':' character */
nameend = linestart;
while(nameend < lineend && *nameend != ':')
nameend++;
/* detect value */
if(nameend < lineend)
valuestart = nameend + 1;
else
valuestart = nameend;
/* trim spaces */
while(valuestart < lineend && isspace(*valuestart))
valuestart++;
/* suppress leading " if needed */
if(valuestart < lineend && *valuestart=='\"')
valuestart++;
if(nameend > linestart && valuestart < lineend) {
int l = nameend - linestart; /* header name length */
int m = lineend - valuestart; /* header value length */
/* suppress tailing spaces */
while(m>0 && isspace(valuestart[m-1]))
m--;
/* suppress tailing ' if needed */
if(m>0 && valuestart[m-1] == '\"')
m--;
i = -1;
/*printf("--%.*s: (%d)%.*s--\n", l, linestart,
m, m, valuestart);*/
if(l==2 && 0==strncasecmp(linestart, "nt", 2))
i = HEADER_NT;
else if(l==3 && 0==strncasecmp(linestart, "usn", 3))
i = HEADER_USN;
else if(l==3 && 0==strncasecmp(linestart, "nts", 3)) {
if(m==10 && 0==strncasecmp(valuestart, "ssdp:alive", 10))
nts = NTS_SSDP_ALIVE;
else if(m==11 && 0==strncasecmp(valuestart, "ssdp:byebye", 11))
nts = NTS_SSDP_BYEBYE;
else if(m==11 && 0==strncasecmp(valuestart, "ssdp:update", 11))
nts = NTS_SSDP_UPDATE;
}
else if(l==8 && 0==strncasecmp(linestart, "location", 8))
i = HEADER_LOCATION;
else if(l==13 && 0==strncasecmp(linestart, "cache-control", 13)) {
/* parse "name1=value1, name_alone, name2=value2" string */
const char * name = valuestart; /* name */
const char * val; /* value */
int rem = m; /* remaining bytes to process */
while(rem > 0) {
val = name;
while(val < name + rem && *val != '=' && *val != ',')
val++;
if(val >= name + rem)
break;
if(*val == '=') {
while(val < name + rem && (*val == '=' || isspace(*val)))
val++;
if(val >= name + rem)
break;
if(0==strncasecmp(name, "max-age", 7))
lifetime = (unsigned int)strtoul(val, 0, 0);
/* move to the next name=value pair */
while(rem > 0 && *name != ',') {
rem--;
name++;
}
/* skip spaces */
while(rem > 0 && (*name == ',' || isspace(*name))) {
rem--;
name++;
}
} else {
rem -= (val - name);
name = val;
while(rem > 0 && (*name == ',' || isspace(*name))) {
rem--;
name++;
}
}
}
/*syslog(LOG_DEBUG, "**%.*s**%u", m, valuestart, lifetime);*/
} else if(l==2 && 0==strncasecmp(linestart, "st", 2)) {
st = valuestart;
st_len = m;
if(method == METHOD_NOTIFY)
i = HEADER_NT; /* it was a M-SEARCH response */
}
if(i>=0) {
headers[i].p = valuestart;
headers[i].l = m;
}
}
linestart = lineend;
while((*linestart == '\n' || *linestart == '\r') && linestart < p + n)
linestart++;
}
#if 0
printf("NTS=%d\n", nts);
for(i=0; i<3; i++) {
if(headers[i].p)
printf("%d-'%.*s'\n", i, headers[i].l, headers[i].p);
}
#endif
syslog(LOG_DEBUG,"SSDP request: '%.*s' (%d) %s %s=%.*s",
methodlen, p, method, nts_to_str(nts),
(method==METHOD_NOTIFY)?"nt":"st",
(method==METHOD_NOTIFY)?headers[HEADER_NT].l:st_len,
(method==METHOD_NOTIFY)?headers[HEADER_NT].p:st);
switch(method) {
case METHOD_NOTIFY:
if(headers[HEADER_NT].p && headers[HEADER_USN].p && headers[HEADER_LOCATION].p) {
if(nts==NTS_SSDP_ALIVE) {
r = updateDevice(headers, time(NULL) + lifetime);
}
else if(nts==NTS_SSDP_BYEBYE) {
r = removeDevice(headers);
}
}
break;
case METHOD_MSEARCH:
processMSEARCH(s, st, st_len, addr);
break;
default:
syslog(LOG_WARNING, "method %.*s, don't know what to do", methodlen, p);
}
return r;
}
/* OpenUnixSocket()
* open the unix socket and call bind() and listen()
* return -1 in case of error */
static int
OpenUnixSocket(const char * path)
{
struct sockaddr_un addr;
int s;
int rv;
s = socket(AF_UNIX, SOCK_STREAM, 0);
if(s < 0)
{
syslog(LOG_ERR, "socket(AF_UNIX): %m");
return -1;
}
/* unlink the socket pseudo file before binding */
rv = unlink(path);
if(rv < 0 && errno != ENOENT)
{
syslog(LOG_ERR, "unlink(unixsocket, \"%s\"): %m", path);
close(s);
return -1;
}
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path));
if(bind(s, (struct sockaddr *)&addr,
sizeof(struct sockaddr_un)) < 0)
{
syslog(LOG_ERR, "bind(unixsocket, \"%s\"): %m", path);
close(s);
return -1;
}
else if(listen(s, 5) < 0)
{
syslog(LOG_ERR, "listen(unixsocket): %m");
close(s);
return -1;
}
/* Change rights so everyone can communicate with us */
if(chmod(path, 0666) < 0)
{
syslog(LOG_WARNING, "chmod(\"%s\"): %m", path);
}
return s;
}
/* processRequest() :
* process the request coming from a unix socket */
void processRequest(struct reqelem * req)
{
ssize_t n;
unsigned int l, m;
unsigned char buf[2048];
const unsigned char * p;
int type;
struct device * d = devlist;
unsigned char rbuf[4096];
unsigned char * rp = rbuf+1;
unsigned char nrep = 0;
time_t t;
struct service * newserv = NULL;
struct service * serv;
n = read(req->socket, buf, sizeof(buf));
if(n<0) {
if(errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
return; /* try again later */
syslog(LOG_ERR, "(s=%d) processRequest(): read(): %m", req->socket);
goto error;
}
if(n==0) {
syslog(LOG_INFO, "(s=%d) request connection closed", req->socket);
goto error;
}
t = time(NULL);
type = buf[0];
p = buf + 1;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(l == 0 && type != 3) {
syslog(LOG_WARNING, "bad request (length=0)");
goto error;
}
syslog(LOG_INFO, "(s=%d) request type=%d str='%.*s'",
req->socket, type, l, p);
switch(type) {
case 1: /* request by type */
case 2: /* request by USN (unique id) */
case 3: /* everything */
while(d && (nrep < 255)) {
if(d->t < t) {
syslog(LOG_INFO, "outdated device");
} else {
/* test if we can put more responses in the buffer */
if(d->headers[HEADER_LOCATION].l + d->headers[HEADER_NT].l
+ d->headers[HEADER_USN].l + 6
+ (rp - rbuf) >= (int)sizeof(rbuf))
break;
if( (type==1 && 0==memcmp(d->headers[HEADER_NT].p, p, l))
||(type==2 && 0==memcmp(d->headers[HEADER_USN].p, p, l))
||(type==3) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = d->headers[HEADER_LOCATION].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_LOCATION].p, d->headers[HEADER_LOCATION].l);
rp += d->headers[HEADER_LOCATION].l;
m = d->headers[HEADER_NT].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_NT].p, d->headers[HEADER_NT].l);
rp += d->headers[HEADER_NT].l;
m = d->headers[HEADER_USN].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_USN].p, d->headers[HEADER_USN].l);
rp += d->headers[HEADER_USN].l;
nrep++;
}
}
d = d->next;
}
/* Also look in service list */
for(serv = servicelisthead.lh_first;
serv && (nrep < 255);
serv = serv->entries.le_next) {
/* test if we can put more responses in the buffer */
if(strlen(serv->location) + strlen(serv->st)
+ strlen(serv->usn) + 6 + (rp - rbuf) >= sizeof(rbuf))
break;
if( (type==1 && 0==strncmp(serv->st, (const char *)p, l))
||(type==2 && 0==strncmp(serv->usn, (const char *)p, l))
||(type==3) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = strlen(serv->location);
CODELENGTH(m, rp);
memcpy(rp, serv->location, m);
rp += m;
m = strlen(serv->st);
CODELENGTH(m, rp);
memcpy(rp, serv->st, m);
rp += m;
m = strlen(serv->usn);
CODELENGTH(m, rp);
memcpy(rp, serv->usn, m);
rp += m;
nrep++;
}
}
rbuf[0] = nrep;
syslog(LOG_DEBUG, "(s=%d) response : %d device%s",
req->socket, nrep, (nrep > 1) ? "s" : "");
if(write(req->socket, rbuf, rp - rbuf) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
break;
case 4: /* submit service */
newserv = malloc(sizeof(struct service));
if(!newserv) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memset(newserv, 0, sizeof(struct service)); /* set pointers to NULL */
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (st contains forbidden chars)");
goto error;
}
newserv->st = malloc(l + 1);
if(!newserv->st) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->st, p, l);
newserv->st[l] = '\0';
p += l;
if(p >= buf + n) {
syslog(LOG_WARNING, "bad request (missing usn)");
goto error;
}
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (usn contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "usn='%.*s'", l, p);
newserv->usn = malloc(l + 1);
if(!newserv->usn) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->usn, p, l);
newserv->usn[l] = '\0';
p += l;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (server contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "server='%.*s'", l, p);
newserv->server = malloc(l + 1);
if(!newserv->server) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->server, p, l);
newserv->server[l] = '\0';
p += l;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (location contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "location='%.*s'", l, p);
newserv->location = malloc(l + 1);
if(!newserv->location) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->location, p, l);
newserv->location[l] = '\0';
/* look in service list for duplicate */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strcmp(newserv->usn, serv->usn)
&& 0 == strcmp(newserv->st, serv->st)) {
syslog(LOG_INFO, "Service allready in the list. Updating...");
free(newserv->st);
free(newserv->usn);
free(serv->server);
serv->server = newserv->server;
free(serv->location);
serv->location = newserv->location;
free(newserv);
newserv = NULL;
return;
}
}
/* Inserting new service */
LIST_INSERT_HEAD(&servicelisthead, newserv, entries);
newserv = NULL;
/*rbuf[0] = '\0';
if(write(req->socket, rbuf, 1) < 0)
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
*/
break;
default:
syslog(LOG_WARNING, "Unknown request type %d", type);
rbuf[0] = '\0';
if(write(req->socket, rbuf, 1) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
}
return;
error:
if(newserv) {
free(newserv->st);
free(newserv->usn);
free(newserv->server);
free(newserv->location);
free(newserv);
newserv = NULL;
}
close(req->socket);
req->socket = -1;
return;
}
static volatile sig_atomic_t quitting = 0;
/* SIGTERM signal handler */
static void
sigterm(int sig)
{
(void)sig;
/*int save_errno = errno;*/
/*signal(sig, SIG_IGN);*/
#if 0
/* calling syslog() is forbidden in a signal handler according to
* signal(3) */
syslog(LOG_NOTICE, "received signal %d, good-bye", sig);
#endif
quitting = 1;
/*errno = save_errno;*/
}
#define PORT 1900
#define XSTR(s) STR(s)
#define STR(s) #s
#define UPNP_MCAST_ADDR "239.255.255.250"
/* for IPv6 */
#define UPNP_MCAST_LL_ADDR "FF02::C" /* link-local */
#define UPNP_MCAST_SL_ADDR "FF05::C" /* site-local */
/* send the M-SEARCH request for all devices */
void ssdpDiscoverAll(int s, int ipv6)
{
static const char MSearchMsgFmt[] =
"M-SEARCH * HTTP/1.1\r\n"
"HOST: %s:" XSTR(PORT) "\r\n"
"ST: ssdp:all\r\n"
"MAN: \"ssdp:discover\"\r\n"
"MX: %u\r\n"
"\r\n";
char bufr[512];
int n;
int mx = 3;
int linklocal = 1;
struct sockaddr_storage sockudp_w;
{
n = snprintf(bufr, sizeof(bufr),
MSearchMsgFmt,
ipv6 ?
(linklocal ? "[" UPNP_MCAST_LL_ADDR "]" : "[" UPNP_MCAST_SL_ADDR "]")
: UPNP_MCAST_ADDR, mx);
memset(&sockudp_w, 0, sizeof(struct sockaddr_storage));
if(ipv6) {
struct sockaddr_in6 * p = (struct sockaddr_in6 *)&sockudp_w;
p->sin6_family = AF_INET6;
p->sin6_port = htons(PORT);
inet_pton(AF_INET6,
linklocal ? UPNP_MCAST_LL_ADDR : UPNP_MCAST_SL_ADDR,
&(p->sin6_addr));
} else {
struct sockaddr_in * p = (struct sockaddr_in *)&sockudp_w;
p->sin_family = AF_INET;
p->sin_port = htons(PORT);
p->sin_addr.s_addr = inet_addr(UPNP_MCAST_ADDR);
}
n = sendto(s, bufr, n, 0, (const struct sockaddr *)&sockudp_w,
ipv6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
if (n < 0) {
/* XXX : EINTR EWOULDBLOCK EAGAIN */
syslog(LOG_ERR, "sendto: %m");
}
}
}
/* main(): program entry point */
int main(int argc, char * * argv)
{
int ret = 0;
int pid;
struct sigaction sa;
char buf[1500];
ssize_t n;
int s_ssdp = -1; /* udp socket receiving ssdp packets */
#ifdef ENABLE_IPV6
int s_ssdp6 = -1; /* udp socket receiving ssdp packets IPv6*/
#else
#define s_ssdp6 (-1)
#endif
int s_unix = -1; /* unix socket communicating with clients */
int s_ifacewatch = -1; /* socket to receive Route / network interface config changes */
int s;
LIST_HEAD(reqstructhead, reqelem) reqlisthead;
struct reqelem * req;
struct reqelem * reqnext;
fd_set readfds;
const char * if_addr[MAX_IF_ADDR];
int n_if_addr = 0;
int i;
const char * sockpath = "/var/run/minissdpd.sock";
const char * pidfilename = "/var/run/minissdpd.pid";
int debug_flag = 0;
int ipv6 = 0;
int deltadev = 0;
struct sockaddr_in sendername;
socklen_t sendername_len;
#ifdef ENABLE_IPV6
struct sockaddr_in6 sendername6;
socklen_t sendername6_len;
#endif
LIST_INIT(&reqlisthead);
LIST_INIT(&servicelisthead);
/* process command line */
for(i=1; i<argc; i++)
{
if(0==strcmp(argv[i], "-i")) {
if(n_if_addr < MAX_IF_ADDR)
if_addr[n_if_addr++] = argv[++i];
else
syslog(LOG_WARNING, "Max number of interface address set to %d, "
"ignoring %s", MAX_IF_ADDR, argv[++i]);
} else if(0==strcmp(argv[i], "-d"))
debug_flag = 1;
else if(0==strcmp(argv[i], "-s"))
sockpath = argv[++i];
else if(0==strcmp(argv[i], "-p"))
pidfilename = argv[++i];
#ifdef ENABLE_IPV6
else if(0==strcmp(argv[i], "-6"))
ipv6 = 1;
#endif
}
if(n_if_addr < 1)
{
fprintf(stderr,
"Usage: %s [-d] [-6] [-s socket] [-p pidfile] "
"-i <interface> [-i <interface2>] ...\n",
argv[0]);
fprintf(stderr,
"\n <interface> is either an IPv4 address such as 192.168.1.42, or an\ninterface name such as eth0.\n");
fprintf(stderr,
"\n By default, socket will be open as %s\n"
"and pid written to file %s\n",
sockpath, pidfilename);
return 1;
}
/* open log */
openlog("minissdpd",
LOG_CONS|LOG_PID|(debug_flag?LOG_PERROR:0),
LOG_MINISSDPD);
if(!debug_flag) /* speed things up and ignore LOG_INFO and LOG_DEBUG */
setlogmask(LOG_UPTO(LOG_NOTICE));
if(checkforrunning(pidfilename) < 0)
{
syslog(LOG_ERR, "MiniSSDPd is already running. EXITING");
return 1;
}
/* set signal handlers */
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sigterm;
if(sigaction(SIGTERM, &sa, NULL))
{
syslog(LOG_ERR, "Failed to set SIGTERM handler. EXITING");
ret = 1;
goto quit;
}
if(sigaction(SIGINT, &sa, NULL))
{
syslog(LOG_ERR, "Failed to set SIGINT handler. EXITING");
ret = 1;
goto quit;
}
/* open route/interface config changes socket */
s_ifacewatch = OpenAndConfInterfaceWatchSocket();
/* open UDP socket(s) for receiving SSDP packets */
s_ssdp = OpenAndConfSSDPReceiveSocket(n_if_addr, if_addr, 0);
if(s_ssdp < 0)
{
syslog(LOG_ERR, "Cannot open socket for receiving SSDP messages, exiting");
ret = 1;
goto quit;
}
#ifdef ENABLE_IPV6
if(ipv6) {
s_ssdp6 = OpenAndConfSSDPReceiveSocket(n_if_addr, if_addr, 1);
if(s_ssdp6 < 0)
{
syslog(LOG_ERR, "Cannot open socket for receiving SSDP messages (IPv6), exiting");
ret = 1;
goto quit;
}
}
#endif
/* Open Unix socket to communicate with other programs on
* the same machine */
s_unix = OpenUnixSocket(sockpath);
if(s_unix < 0)
{
syslog(LOG_ERR, "Cannot open unix socket for communicating with clients. Exiting");
ret = 1;
goto quit;
}
/* drop privileges */
#if 0
/* if we drop privileges, how to unlink(/var/run/minissdpd.sock) ? */
if(getuid() == 0) {
struct passwd * user;
struct group * group;
user = getpwnam("nobody");
if(!user) {
syslog(LOG_ERR, "getpwnam(\"%s\") : %m", "nobody");
ret = 1;
goto quit;
}
group = getgrnam("nogroup");
if(!group) {
syslog(LOG_ERR, "getgrnam(\"%s\") : %m", "nogroup");
ret = 1;
goto quit;
}
if(setgid(group->gr_gid) < 0) {
syslog(LOG_ERR, "setgit(%d) : %m", group->gr_gid);
ret = 1;
goto quit;
}
if(setuid(user->pw_uid) < 0) {
syslog(LOG_ERR, "setuid(%d) : %m", user->pw_uid);
ret = 1;
goto quit;
}
}
#endif
/* daemonize or in any case get pid ! */
if(debug_flag)
pid = getpid();
else {
#ifdef USE_DAEMON
if(daemon(0, 0) < 0)
perror("daemon()");
pid = getpid();
#else
pid = daemonize();
#endif
}
writepidfile(pidfilename, pid);
/* send M-SEARCH ssdp:all Requests */
ssdpDiscoverAll(s_ssdp, 0);
if(s_ssdp6 >= 0)
ssdpDiscoverAll(s_ssdp6, 1);
/* Main loop */
while(!quitting)
{
/* fill readfds fd_set */
FD_ZERO(&readfds);
if(s_ssdp >= 0) {
FD_SET(s_ssdp, &readfds);
}
#ifdef ENABLE_IPV6
if(s_ssdp6 >= 0) {
FD_SET(s_ssdp6, &readfds);
}
#endif
if(s_ifacewatch >= 0) {
FD_SET(s_ifacewatch, &readfds);
}
FD_SET(s_unix, &readfds);
for(req = reqlisthead.lh_first; req; req = req->entries.le_next)
{
if(req->socket >= 0)
FD_SET(req->socket, &readfds);
}
/* select call */
if(select(FD_SETSIZE, &readfds, 0, 0, 0) < 0)
{
if(errno != EINTR)
{
syslog(LOG_ERR, "select: %m");
break; /* quit */
}
continue; /* try again */
}
#ifdef ENABLE_IPV6
if((s_ssdp6 >= 0) && FD_ISSET(s_ssdp6, &readfds))
{
sendername6_len = sizeof(struct sockaddr_in6);
n = recvfrom(s_ssdp6, buf, sizeof(buf), 0,
(struct sockaddr *)&sendername6, &sendername6_len);
if(n<0)
{
/* EAGAIN, EWOULDBLOCK, EINTR : silently ignore (try again next time)
* other errors : log to LOG_ERR */
if(errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
syslog(LOG_ERR, "recvfrom: %m");
}
else
{
/* Parse and process the packet received */
/*printf("%.*s", n, buf);*/
i = ParseSSDPPacket(s_ssdp6, buf, n,
(struct sockaddr *)&sendername6);
syslog(LOG_DEBUG, "** i=%d deltadev=%d **", i, deltadev);
if(i==0 || (i*deltadev < 0))
{
if(deltadev > 0)
syslog(LOG_NOTICE, "%d new devices added", deltadev);
else if(deltadev < 0)
syslog(LOG_NOTICE, "%d devices removed (good-bye!)", -deltadev);
deltadev = i;
}
else if((i*deltadev) >= 0)
{
deltadev += i;
}
}
}
#endif
if(FD_ISSET(s_ssdp, &readfds))
{
sendername_len = sizeof(struct sockaddr_in);
n = recvfrom(s_ssdp, buf, sizeof(buf), 0,
(struct sockaddr *)&sendername, &sendername_len);
if(n<0)
{
/* EAGAIN, EWOULDBLOCK, EINTR : silently ignore (try again next time)
* other errors : log to LOG_ERR */
if(errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
syslog(LOG_ERR, "recvfrom: %m");
}
else
{
/* Parse and process the packet received */
/*printf("%.*s", n, buf);*/
i = ParseSSDPPacket(s_ssdp, buf, n,
(struct sockaddr *)&sendername);
syslog(LOG_DEBUG, "** i=%d deltadev=%d **", i, deltadev);
if(i==0 || (i*deltadev < 0))
{
if(deltadev > 0)
syslog(LOG_NOTICE, "%d new devices added", deltadev);
else if(deltadev < 0)
syslog(LOG_NOTICE, "%d devices removed (good-bye!)", -deltadev);
deltadev = i;
}
else if((i*deltadev) >= 0)
{
deltadev += i;
}
}
}
/* processing unix socket requests */
for(req = reqlisthead.lh_first; req;)
{
reqnext = req->entries.le_next;
if((req->socket >= 0) && FD_ISSET(req->socket, &readfds))
{
processRequest(req);
}
if(req->socket < 0)
{
LIST_REMOVE(req, entries);
free(req);
}
req = reqnext;
}
/* processing new requests */
if(FD_ISSET(s_unix, &readfds))
{
struct reqelem * tmp;
s = accept(s_unix, NULL, NULL);
if(s<0)
{
syslog(LOG_ERR, "accept(s_unix): %m");
}
else
{
syslog(LOG_INFO, "(s=%d) new request connection", s);
if(!set_non_blocking(s))
syslog(LOG_WARNING, "Failed to set new socket non blocking : %m");
tmp = malloc(sizeof(struct reqelem));
if(!tmp)
{
syslog(LOG_ERR, "cannot allocate memory for request");
close(s);
}
else
{
tmp->socket = s;
LIST_INSERT_HEAD(&reqlisthead, tmp, entries);
}
}
}
/* processing route/network interface config changes */
if((s_ifacewatch >= 0) && FD_ISSET(s_ifacewatch, &readfds)) {
ProcessInterfaceWatch(s_ifacewatch, s_ssdp, s_ssdp6, n_if_addr, if_addr);
}
}
/* closing and cleaning everything */
quit:
if(s_ssdp >= 0) {
close(s_ssdp);
s_ssdp = -1;
}
#ifdef ENABLE_IPV6
if(s_ssdp6 >= 0) {
close(s_ssdp6);
s_ssdp6 = -1;
}
#endif
if(s_unix >= 0) {
close(s_unix);
s_unix = -1;
if(unlink(sockpath) < 0)
syslog(LOG_ERR, "unlink(%s): %m", sockpath);
}
if(s_ifacewatch >= 0) {
close(s_ifacewatch);
s_ifacewatch = -1;
}
if(unlink(pidfilename) < 0)
syslog(LOG_ERR, "unlink(%s): %m", pidfilename);
closelog();
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-388/c/good_5008_0 |
crossvul-cpp_data_good_2809_0 | /*****************************************************************
|
| AP4 - Atom Based Sample Tables
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This atom is part of AP4 (MP4 Audio Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the atom COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4AtomSampleTable.h"
#include "Ap4ByteStream.h"
#include "Ap4StsdAtom.h"
#include "Ap4StscAtom.h"
#include "Ap4StcoAtom.h"
#include "Ap4Co64Atom.h"
#include "Ap4StszAtom.h"
#include "Ap4Stz2Atom.h"
#include "Ap4SttsAtom.h"
#include "Ap4CttsAtom.h"
#include "Ap4StssAtom.h"
#include "Ap4Sample.h"
#include "Ap4Atom.h"
/*----------------------------------------------------------------------
| AP4_AtomSampleTable Dynamic Cast Anchor
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AtomSampleTable)
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::AP4_AtomSampleTable
+---------------------------------------------------------------------*/
AP4_AtomSampleTable::AP4_AtomSampleTable(AP4_ContainerAtom* stbl,
AP4_ByteStream& sample_stream) :
m_SampleStream(sample_stream)
{
m_StscAtom = AP4_DYNAMIC_CAST(AP4_StscAtom, stbl->GetChild(AP4_ATOM_TYPE_STSC));
m_StcoAtom = AP4_DYNAMIC_CAST(AP4_StcoAtom, stbl->GetChild(AP4_ATOM_TYPE_STCO));
m_StszAtom = AP4_DYNAMIC_CAST(AP4_StszAtom, stbl->GetChild(AP4_ATOM_TYPE_STSZ));
m_Stz2Atom = AP4_DYNAMIC_CAST(AP4_Stz2Atom, stbl->GetChild(AP4_ATOM_TYPE_STZ2));
m_CttsAtom = AP4_DYNAMIC_CAST(AP4_CttsAtom, stbl->GetChild(AP4_ATOM_TYPE_CTTS));
m_SttsAtom = AP4_DYNAMIC_CAST(AP4_SttsAtom, stbl->GetChild(AP4_ATOM_TYPE_STTS));
m_StssAtom = AP4_DYNAMIC_CAST(AP4_StssAtom, stbl->GetChild(AP4_ATOM_TYPE_STSS));
m_StsdAtom = AP4_DYNAMIC_CAST(AP4_StsdAtom, stbl->GetChild(AP4_ATOM_TYPE_STSD));
m_Co64Atom = AP4_DYNAMIC_CAST(AP4_Co64Atom, stbl->GetChild(AP4_ATOM_TYPE_CO64));
// keep a reference to the sample stream
m_SampleStream.AddReference();
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::~AP4_AtomSampleTable
+---------------------------------------------------------------------*/
AP4_AtomSampleTable::~AP4_AtomSampleTable()
{
m_SampleStream.Release();
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
AP4_Sample& sample)
{
AP4_Result result;
// check that we have an stsc atom
if (!m_StscAtom) {
return AP4_ERROR_INVALID_FORMAT;
}
// check that we have a chunk offset table
if (m_StcoAtom == NULL && m_Co64Atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// MP4 uses 1-based indexes internally, so adjust by one
index++;
// find out in which chunk this sample is located
AP4_Ordinal chunk, skip, desc;
result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);
if (AP4_FAILED(result)) return result;
// check that the result is within bounds
if (skip > index) return AP4_ERROR_INTERNAL;
// get the atom offset for this chunk
AP4_UI64 offset;
if (m_StcoAtom) {
AP4_UI32 offset_32;
result = m_StcoAtom->GetChunkOffset(chunk, offset_32);
offset = offset_32;
} else {
result = m_Co64Atom->GetChunkOffset(chunk, offset);
}
if (AP4_FAILED(result)) return result;
// compute the additional offset inside the chunk
for (unsigned int i = index-skip; i < index; i++) {
AP4_Size size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(i, size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(i, size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
offset += size;
}
// set the description index
sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes
// set the dts and cts
AP4_UI32 cts_offset = 0;
AP4_UI64 dts = 0;
AP4_UI32 duration = 0;
if (m_SttsAtom) {
result = m_SttsAtom->GetDts(index, dts, &duration);
if (AP4_FAILED(result)) return result;
}
sample.SetDuration(duration);
sample.SetDts(dts);
if (m_CttsAtom == NULL) {
sample.SetCts(dts);
} else {
result = m_CttsAtom->GetCtsOffset(index, cts_offset);
if (AP4_FAILED(result)) return result;
sample.SetCtsDelta(cts_offset);
}
// set the size
AP4_Size sample_size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(index, sample_size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(index, sample_size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
sample.SetSize(sample_size);
// set the sync flag
if (m_StssAtom == NULL) {
sample.SetSync(true);
} else {
sample.SetSync(m_StssAtom->IsSampleSync(index));
}
// set the offset
sample.SetOffset(offset);
// set the data stream
sample.SetDataStream(m_SampleStream);
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleCount
+---------------------------------------------------------------------*/
AP4_Cardinal
AP4_AtomSampleTable::GetSampleCount()
{
if (m_StszAtom) {
return m_StszAtom->GetSampleCount();
} else if (m_Stz2Atom) {
return m_Stz2Atom->GetSampleCount();
} else {
return 0;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleDescription
+---------------------------------------------------------------------*/
AP4_SampleDescription*
AP4_AtomSampleTable::GetSampleDescription(AP4_Ordinal index)
{
return m_StsdAtom ? m_StsdAtom->GetSampleDescription(index) : NULL;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleDescriptionCount
+---------------------------------------------------------------------*/
AP4_Cardinal
AP4_AtomSampleTable::GetSampleDescriptionCount()
{
return m_StsdAtom ? m_StsdAtom->GetSampleDescriptionCount() : 0;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleChunkPosition
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
AP4_Ordinal sample_description_index;
return GetChunkForSample(sample_index,
chunk_index,
position_in_chunk,
sample_description_index);
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkForSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetChunkForSample(AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk,
AP4_Ordinal& sample_description_index)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
sample_description_index = 0;
// check that we an stsc atom
if (m_StscAtom == NULL) return AP4_ERROR_INVALID_STATE;
// get the chunk info from the stsc atom
AP4_Ordinal chunk = 0;
AP4_Result result = m_StscAtom->GetChunkForSample(sample_index+1, // the atom API is 1-based
chunk,
position_in_chunk,
sample_description_index);
if (AP4_FAILED(result)) return result;
if (chunk == 0) return AP4_ERROR_INTERNAL;
// the atom sample and chunk indexes are 1-based, so we need to translate
chunk_index = chunk-1;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkOffset
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position& offset)
{
if (m_StcoAtom) {
AP4_UI32 offset_32;
AP4_Result result = m_StcoAtom->GetChunkOffset(chunk_index+1, offset_32);
if (AP4_SUCCEEDED(result)) {
offset = offset_32;
} else {
offset = 0;
}
return result;
} else if (m_Co64Atom) {
return m_Co64Atom->GetChunkOffset(chunk_index+1, offset);
} else {
offset = 0;
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetChunkOffset
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::SetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position offset)
{
if (m_StcoAtom) {
if ((offset >> 32) != 0) return AP4_ERROR_OUT_OF_RANGE;
return m_StcoAtom->SetChunkOffset(chunk_index+1, (AP4_UI32)offset);
} else if (m_Co64Atom) {
return m_Co64Atom->SetChunkOffset(chunk_index+1, offset);
} else {
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetSampleSize
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::SetSampleSize(AP4_Ordinal sample_index, AP4_Size size)
{
if (m_StszAtom) {
return m_StszAtom->SetSampleSize(sample_index+1, size);
} else if (m_Stz2Atom) {
return m_Stz2Atom->SetSampleSize(sample_index+1, size);
} else {
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleIndexForTimeStamp
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 ts,
AP4_Ordinal& sample_index)
{
return m_SttsAtom ? m_SttsAtom->GetSampleIndexForTimeStamp(ts, sample_index)
: AP4_FAILURE;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetNearestSyncSampleIndex
+---------------------------------------------------------------------*/
AP4_Ordinal
AP4_AtomSampleTable::GetNearestSyncSampleIndex(AP4_Ordinal sample_index, bool before)
{
// if we don't have an stss table, all samples match
if (m_StssAtom == NULL) return sample_index;
sample_index += 1; // the table is 1-based
AP4_Cardinal entry_count = m_StssAtom->GetEntries().ItemCount();
if (before) {
AP4_Ordinal cursor = 0;
for (unsigned int i=0; i<entry_count; i++) {
if (m_StssAtom->GetEntries()[i] >= sample_index) return cursor;
if (m_StssAtom->GetEntries()[i]) cursor = m_StssAtom->GetEntries()[i]-1;
}
// not found?
return cursor;
} else {
for (unsigned int i=0; i<entry_count; i++) {
if (m_StssAtom->GetEntries()[i] >= sample_index) {
return m_StssAtom->GetEntries()[i]?m_StssAtom->GetEntries()[i]-1:sample_index-1;
}
}
// not found?
return GetSampleCount();
}
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_2809_0 |
crossvul-cpp_data_good_4038_0 | /*
* Copyright (C) 2004-2020 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Query.h>
using std::set;
using std::map;
using std::vector;
#define CALLMOD(MOD, CLIENT, USER, NETWORK, FUNC) \
{ \
CModule* pModule = nullptr; \
if (NETWORK && (pModule = (NETWORK)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
pModule->SetClient(CLIENT); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(NETWORK)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = (USER)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(USER)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = CZNC::Get().GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
CUser* pOldUser = pModule->GetUser(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->SetUser(USER); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
pModule->SetUser(pOldUser); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
CZNC::Get().GetModules().UnloadModule(MOD); \
} \
} \
} else { \
PutStatus(t_f("No such module {1}")(MOD)); \
} \
}
CClient::~CClient() {
if (m_spAuth) {
CClientAuth* pAuth = (CClientAuth*)&(*m_spAuth);
pAuth->Invalidate();
}
if (m_pUser != nullptr) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CClient::SendRequiredPasswordNotice() {
PutClient(":irc.znc.in 464 " + GetNick() + " :Password required");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"You need to send your password. "
"Configure your client to send a server password.");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"To connect now, you can use /quote PASS <username>:<password>, "
"or /quote PASS <username>/<network>:<password> to connect to a "
"specific network.");
}
void CClient::ReadLine(const CString& sData) {
CLanguageScope user_lang(GetUser() ? GetUser()->GetLanguage() : "");
CString sLine = sData;
sLine.Replace("\n", "");
sLine.Replace("\r", "");
DEBUG("(" << GetFullName() << ") CLI -> ZNC ["
<< CDebug::Filter(sLine) << "]");
bool bReturn = false;
if (IsAttached()) {
NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRaw(this, sLine), &bReturn);
}
if (bReturn) return;
CMessage Message(sLine);
Message.SetClient(this);
if (IsAttached()) {
NETWORKMODULECALL(OnUserRawMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRawMessage(Message), &bReturn);
}
if (bReturn) return;
CString sCommand = Message.GetCommand();
if (!IsAttached()) {
// The following commands happen before authentication with ZNC
if (sCommand.Equals("PASS")) {
m_bGotPass = true;
CString sAuthLine = Message.GetParam(0);
ParsePass(sAuthLine);
AuthUser();
// Don't forward this msg. ZNC has already registered us.
return;
} else if (sCommand.Equals("NICK")) {
CString sNick = Message.GetParam(0);
m_sNick = sNick;
m_bGotNick = true;
AuthUser();
// Don't forward this msg. ZNC will handle nick changes until auth
// is complete
return;
} else if (sCommand.Equals("USER")) {
CString sAuthLine = Message.GetParam(0);
if (m_sUser.empty() && !sAuthLine.empty()) {
ParseUser(sAuthLine);
}
m_bGotUser = true;
if (m_bGotPass) {
AuthUser();
} else if (!m_bInCap) {
SendRequiredPasswordNotice();
}
// Don't forward this msg. ZNC has already registered us.
return;
}
}
if (Message.GetType() == CMessage::Type::Capability) {
HandleCap(Message);
// Don't let the client talk to the server directly about CAP,
// we don't want anything enabled that ZNC does not support.
return;
}
if (!m_pUser) {
// Only CAP, NICK, USER and PASS are allowed before login
return;
}
switch (Message.GetType()) {
case CMessage::Type::Action:
bReturn = OnActionMessage(Message);
break;
case CMessage::Type::CTCP:
bReturn = OnCTCPMessage(Message);
break;
case CMessage::Type::Join:
bReturn = OnJoinMessage(Message);
break;
case CMessage::Type::Mode:
bReturn = OnModeMessage(Message);
break;
case CMessage::Type::Notice:
bReturn = OnNoticeMessage(Message);
break;
case CMessage::Type::Part:
bReturn = OnPartMessage(Message);
break;
case CMessage::Type::Ping:
bReturn = OnPingMessage(Message);
break;
case CMessage::Type::Pong:
bReturn = OnPongMessage(Message);
break;
case CMessage::Type::Quit:
bReturn = OnQuitMessage(Message);
break;
case CMessage::Type::Text:
bReturn = OnTextMessage(Message);
break;
case CMessage::Type::Topic:
bReturn = OnTopicMessage(Message);
break;
default:
bReturn = OnOtherMessage(Message);
break;
}
if (bReturn) return;
PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags));
}
void CClient::SetNick(const CString& s) { m_sNick = s; }
void CClient::SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect,
bool bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientDisconnected(this);
if (bDisconnect) {
ClearServerDependentCaps();
// Tell the client they are no longer in these channels.
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (const CChan* pChan : vChans) {
if (!(pChan->IsDetached())) {
PutClient(":" + m_pNetwork->GetIRCNick().GetNickMask() +
" PART " + pChan->GetName());
}
}
}
} else if (m_pUser) {
m_pUser->UserDisconnected(this);
}
m_pNetwork = pNetwork;
if (bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientConnected(this);
} else if (m_pUser) {
m_pUser->UserConnected(this);
}
}
}
const vector<CClient*>& CClient::GetClients() const {
if (m_pNetwork) {
return m_pNetwork->GetClients();
}
return m_pUser->GetUserClients();
}
const CIRCSock* CClient::GetIRCSock() const {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
CIRCSock* CClient::GetIRCSock() {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
void CClient::StatusCTCP(const CString& sLine) {
CString sCommand = sLine.Token(0);
if (sCommand.Equals("PING")) {
PutStatusNotice("\001PING " + sLine.Token(1, true) + "\001");
} else if (sCommand.Equals("VERSION")) {
PutStatusNotice("\001VERSION " + CZNC::GetTag() + "\001");
}
}
bool CClient::SendMotd() {
const VCString& vsMotd = CZNC::Get().GetMotd();
if (!vsMotd.size()) {
return false;
}
for (const CString& sLine : vsMotd) {
if (m_pNetwork) {
PutStatusNotice(m_pNetwork->ExpandString(sLine));
} else {
PutStatusNotice(m_pUser->ExpandString(sLine));
}
}
return true;
}
void CClient::AuthUser() {
if (!m_bGotNick || !m_bGotUser || !m_bGotPass || m_bInCap || IsAttached())
return;
m_spAuth = std::make_shared<CClientAuth>(this, m_sUser, m_sPass);
CZNC::Get().AuthUser(m_spAuth);
}
CClientAuth::CClientAuth(CClient* pClient, const CString& sUsername,
const CString& sPassword)
: CAuthBase(sUsername, sPassword, pClient), m_pClient(pClient) {}
void CClientAuth::RefusedLogin(const CString& sReason) {
if (m_pClient) {
m_pClient->RefuseLogin(sReason);
}
}
CString CAuthBase::GetRemoteIP() const {
if (m_pSock) return m_pSock->GetRemoteIP();
return "";
}
void CAuthBase::Invalidate() { m_pSock = nullptr; }
void CAuthBase::AcceptLogin(CUser& User) {
if (m_pSock) {
AcceptedLogin(User);
Invalidate();
}
}
void CAuthBase::RefuseLogin(const CString& sReason) {
if (!m_pSock) return;
CUser* pUser = CZNC::Get().FindUser(GetUsername());
// If the username is valid, notify that user that someone tried to
// login. Use sReason because there are other reasons than "wrong
// password" for a login to be rejected (e.g. fail2ban).
if (pUser) {
pUser->PutStatusNotice(t_f(
"A client from {1} attempted to login as you, but was rejected: "
"{2}")(GetRemoteIP(), sReason));
}
GLOBALMODULECALL(OnFailedLogin(GetUsername(), GetRemoteIP()), NOTHING);
RefusedLogin(sReason);
Invalidate();
}
void CClient::RefuseLogin(const CString& sReason) {
PutStatus("Bad username and/or password.");
PutClient(":irc.znc.in 464 " + GetNick() + " :" + sReason);
Close(Csock::CLT_AFTERWRITE);
}
void CClientAuth::AcceptedLogin(CUser& User) {
if (m_pClient) {
m_pClient->AcceptLogin(User);
}
}
void CClient::AcceptLogin(CUser& User) {
m_sPass = "";
m_pUser = &User;
// Set our proper timeout and set back our proper timeout mode
// (constructor set a different timeout and mode)
SetTimeout(User.GetNoTrafficTimeout(), TMO_READ);
SetSockName("USR::" + m_pUser->GetUsername());
SetEncoding(m_pUser->GetClientEncoding());
if (!m_sNetwork.empty()) {
m_pNetwork = m_pUser->FindNetwork(m_sNetwork);
if (!m_pNetwork) {
PutStatus(t_f("Network {1} doesn't exist.")(m_sNetwork));
}
} else if (!m_pUser->GetNetworks().empty()) {
// If a user didn't supply a network, and they have a network called
// "default" then automatically use this network.
m_pNetwork = m_pUser->FindNetwork("default");
// If no "default" network, try "user" network. It's for compatibility
// with early network stuff in ZNC, which converted old configs to
// "user" network.
if (!m_pNetwork) m_pNetwork = m_pUser->FindNetwork("user");
// Otherwise, just try any network of the user.
if (!m_pNetwork) m_pNetwork = *m_pUser->GetNetworks().begin();
if (m_pNetwork && m_pUser->GetNetworks().size() > 1) {
PutStatusNotice(
t_s("You have several networks configured, but no network was "
"specified for the connection."));
PutStatusNotice(
t_f("Selecting network {1}. To see list of all configured "
"networks, use /znc ListNetworks")(m_pNetwork->GetName()));
PutStatusNotice(t_f(
"If you want to choose another network, use /znc JumpNetwork "
"<network>, or connect to ZNC with username {1}/<network> "
"(instead of just {1})")(m_pUser->GetUsername()));
}
} else {
PutStatusNotice(
t_s("You have no networks configured. Use /znc AddNetwork "
"<network> to add one."));
}
SetNetwork(m_pNetwork, false);
SendMotd();
NETWORKMODULECALL(OnClientLogin(), m_pUser, m_pNetwork, this, NOTHING);
}
void CClient::Timeout() { PutClient("ERROR :" + t_s("Closing link: Timeout")); }
void CClient::Connected() { DEBUG(GetSockName() << " == Connected();"); }
void CClient::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
}
void CClient::Disconnected() {
DEBUG(GetSockName() << " == Disconnected()");
CIRCNetwork* pNetwork = m_pNetwork;
SetNetwork(nullptr, false, false);
if (m_pUser) {
NETWORKMODULECALL(OnClientDisconnect(), m_pUser, pNetwork, this,
NOTHING);
}
}
void CClient::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
if (IsAttached()) {
PutClient("ERROR :" + t_s("Closing link: Too long raw line"));
}
Close();
}
void CClient::BouncedOff() {
PutStatusNotice(
t_s("You are being disconnected because another user just "
"authenticated as you."));
Close(Csock::CLT_AFTERWRITE);
}
void CClient::PutIRC(const CString& sLine) {
if (m_pNetwork) {
m_pNetwork->PutIRC(sLine);
}
}
CString CClient::GetFullName() const {
if (!m_pUser) return GetRemoteIP();
CString sFullName = m_pUser->GetUsername();
if (!m_sIdentifier.empty()) sFullName += "@" + m_sIdentifier;
if (m_pNetwork) sFullName += "/" + m_pNetwork->GetName();
return sFullName;
}
void CClient::PutClient(const CString& sLine) {
PutClient(CMessage(sLine));
}
bool CClient::PutClient(const CMessage& Message) {
if (!m_bAwayNotify && Message.GetType() == CMessage::Type::Away) {
return false;
} else if (!m_bAccountNotify &&
Message.GetType() == CMessage::Type::Account) {
return false;
}
CMessage Msg(Message);
const CIRCSock* pIRCSock = GetIRCSock();
if (pIRCSock) {
if (Msg.GetType() == CMessage::Type::Numeric) {
unsigned int uCode = Msg.As<CNumericMessage>().GetCode();
if (uCode == 352) { // RPL_WHOREPLY
if (!m_bNamesx && pIRCSock->HasNamesx()) {
// The server has NAMESX, but the client doesn't, so we need
// to remove extra prefixes
CString sNick = Msg.GetParam(6);
if (sNick.size() > 1 && pIRCSock->IsPermChar(sNick[1])) {
CString sNewNick = sNick;
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNewNick = sNick[0] + sNick.substr(pos);
}
Msg.SetParam(6, sNewNick);
}
}
} else if (uCode == 353) { // RPL_NAMES
if ((!m_bNamesx && pIRCSock->HasNamesx()) ||
(!m_bUHNames && pIRCSock->HasUHNames())) {
// The server has either UHNAMES or NAMESX, but the client
// is missing either or both
CString sNicks = Msg.GetParam(3);
VCString vsNicks;
sNicks.Split(" ", vsNicks, false);
for (CString& sNick : vsNicks) {
if (sNick.empty()) break;
if (!m_bNamesx && pIRCSock->HasNamesx() &&
pIRCSock->IsPermChar(sNick[0])) {
// The server has NAMESX, but the client doesn't, so
// we just use the first perm char
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNick = sNick[0] + sNick.substr(pos);
}
}
if (!m_bUHNames && pIRCSock->HasUHNames()) {
// The server has UHNAMES, but the client doesn't,
// so we strip away ident and host
sNick = sNick.Token(0, false, "!");
}
}
Msg.SetParam(
3, CString(" ").Join(vsNicks.begin(), vsNicks.end()));
}
}
} else if (Msg.GetType() == CMessage::Type::Join) {
if (!m_bExtendedJoin && pIRCSock->HasExtendedJoin()) {
Msg.SetParams({Msg.As<CJoinMessage>().GetTarget()});
}
}
}
MCString mssTags;
for (const auto& it : Msg.GetTags()) {
if (IsTagEnabled(it.first)) {
mssTags[it.first] = it.second;
}
}
if (HasServerTime()) {
// If the server didn't set the time tag, manually set it
mssTags.emplace("time", CUtils::FormatServerTime(Msg.GetTime()));
}
Msg.SetTags(mssTags);
Msg.SetClient(this);
Msg.SetNetwork(m_pNetwork);
bool bReturn = false;
NETWORKMODULECALL(OnSendToClientMessage(Msg), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
return PutClientRaw(Msg.ToString());
}
bool CClient::PutClientRaw(const CString& sLine) {
CString sCopy = sLine;
bool bReturn = false;
NETWORKMODULECALL(OnSendToClient(sCopy, *this), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
DEBUG("(" << GetFullName() << ") ZNC -> CLI ["
<< CDebug::Filter(sCopy) << "]");
Write(sCopy + "\r\n");
return true;
}
void CClient::PutStatusNotice(const CString& sLine) {
PutModNotice("status", sLine);
}
unsigned int CClient::PutStatus(const CTable& table) {
unsigned int idx = 0;
CString sLine;
while (table.GetLine(idx++, sLine)) PutStatus(sLine);
return idx - 1;
}
void CClient::PutStatus(const CString& sLine) { PutModule("status", sLine); }
void CClient::PutModNotice(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in NOTICE " << GetNick() << " :" << sLine
<< "]");
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) + "!znc@znc.in NOTICE " +
GetNick() + " :" + sLine + "\r\n");
}
void CClient::PutModule(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " << GetNick() << " :" << sLine
<< "]");
VCString vsLines;
sLine.Split("\n", vsLines);
for (const CString& s : vsLines) {
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " + GetNick() + " :" + s + "\r\n");
}
}
CString CClient::GetNick(bool bAllowIRCNick) const {
CString sRet;
const CIRCSock* pSock = GetIRCSock();
if (bAllowIRCNick && pSock && pSock->IsAuthed()) {
sRet = pSock->GetNick();
}
return (sRet.empty()) ? m_sNick : sRet;
}
CString CClient::GetNickMask() const {
if (GetIRCSock() && GetIRCSock()->IsAuthed()) {
return GetIRCSock()->GetNickMask();
}
CString sHost =
m_pNetwork ? m_pNetwork->GetBindHost() : m_pUser->GetBindHost();
if (sHost.empty()) {
sHost = "irc.znc.in";
}
return GetNick() + "!" +
(m_pNetwork ? m_pNetwork->GetIdent() : m_pUser->GetIdent()) + "@" +
sHost;
}
bool CClient::IsValidIdentifier(const CString& sIdentifier) {
// ^[-\w]+$
if (sIdentifier.empty()) {
return false;
}
const char* p = sIdentifier.c_str();
while (*p) {
if (*p != '_' && *p != '-' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
void CClient::RespondCap(const CString& sResponse) {
PutClient(":irc.znc.in CAP " + GetNick() + " " + sResponse);
}
void CClient::HandleCap(const CMessage& Message) {
CString sSubCmd = Message.GetParam(0);
if (sSubCmd.Equals("LS")) {
SCString ssOfferCaps;
for (const auto& it : m_mCoreCaps) {
bool bServerDependent = std::get<0>(it.second);
if (!bServerDependent ||
m_ssServerDependentCaps.count(it.first) > 0)
ssOfferCaps.insert(it.first);
}
GLOBALMODULECALL(OnClientCapLs(this, ssOfferCaps), NOTHING);
CString sRes =
CString(" ").Join(ssOfferCaps.begin(), ssOfferCaps.end());
RespondCap("LS :" + sRes);
m_bInCap = true;
if (Message.GetParam(1).ToInt() >= 302) {
m_bCapNotify = true;
}
} else if (sSubCmd.Equals("END")) {
m_bInCap = false;
if (!IsAttached()) {
if (!m_pUser && m_bGotUser && !m_bGotPass) {
SendRequiredPasswordNotice();
} else {
AuthUser();
}
}
} else if (sSubCmd.Equals("REQ")) {
VCString vsTokens;
Message.GetParam(1).Split(" ", vsTokens, false);
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
bool bAccepted = false;
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
bAccepted = !bServerDependent ||
m_ssServerDependentCaps.count(sCap) > 0;
}
GLOBALMODULECALL(IsClientCapSupported(this, sCap, bVal),
&bAccepted);
if (!bAccepted) {
// Some unsupported capability is requested
RespondCap("NAK :" + Message.GetParam(1));
return;
}
}
// All is fine, we support what was requested
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
auto handler_it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != handler_it) {
const auto& handler = std::get<1>(handler_it->second);
handler(bVal);
}
GLOBALMODULECALL(OnClientCapRequest(this, sCap, bVal), NOTHING);
if (bVal) {
m_ssAcceptedCaps.insert(sCap);
} else {
m_ssAcceptedCaps.erase(sCap);
}
}
RespondCap("ACK :" + Message.GetParam(1));
} else if (sSubCmd.Equals("LIST")) {
CString sList =
CString(" ").Join(m_ssAcceptedCaps.begin(), m_ssAcceptedCaps.end());
RespondCap("LIST :" + sList);
} else {
PutClient(":irc.znc.in 410 " + GetNick() + " " + sSubCmd +
" :Invalid CAP subcommand");
}
}
void CClient::ParsePass(const CString& sAuthLine) {
// [user[@identifier][/network]:]password
const size_t uColon = sAuthLine.find(":");
if (uColon != CString::npos) {
m_sPass = sAuthLine.substr(uColon + 1);
ParseUser(sAuthLine.substr(0, uColon));
} else {
m_sPass = sAuthLine;
}
}
void CClient::ParseUser(const CString& sAuthLine) {
// user[@identifier][/network]
const size_t uSlash = sAuthLine.rfind("/");
if (uSlash != CString::npos) {
m_sNetwork = sAuthLine.substr(uSlash + 1);
ParseIdentifier(sAuthLine.substr(0, uSlash));
} else {
ParseIdentifier(sAuthLine);
}
}
void CClient::ParseIdentifier(const CString& sAuthLine) {
// user[@identifier]
const size_t uAt = sAuthLine.rfind("@");
if (uAt != CString::npos) {
const CString sId = sAuthLine.substr(uAt + 1);
if (IsValidIdentifier(sId)) {
m_sIdentifier = sId;
m_sUser = sAuthLine.substr(0, uAt);
} else {
m_sUser = sAuthLine;
}
} else {
m_sUser = sAuthLine;
}
}
void CClient::SetTagSupport(const CString& sTag, bool bState) {
if (bState) {
m_ssSupportedTags.insert(sTag);
} else {
m_ssSupportedTags.erase(sTag);
}
}
void CClient::NotifyServerDependentCaps(const SCString& ssCaps) {
for (const CString& sCap : ssCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
if (bServerDependent) {
m_ssServerDependentCaps.insert(sCap);
}
}
}
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " NEW :" + sCaps);
}
}
void CClient::ClearServerDependentCaps() {
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " DEL :" + sCaps);
for (const CString& sCap : m_ssServerDependentCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
const auto& handler = std::get<1>(it->second);
handler(false);
}
}
}
m_ssServerDependentCaps.clear();
}
template <typename T>
void CClient::AddBuffer(const T& Message) {
const CString sTarget = Message.GetTarget();
T Format;
Format.Clone(Message);
Format.SetNick(CNick(_NAMEDFMT(GetNickMask())));
Format.SetTarget(_NAMEDFMT(sTarget));
Format.SetText("{text}");
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline()) {
pChan->AddBuffer(Format, Message.GetText());
}
} else if (Message.GetType() != CMessage::Type::Notice) {
if (!m_pUser->AutoClearQueryBuffer() || !m_pNetwork->IsUserOnline()) {
CQuery* pQuery = m_pNetwork->AddQuery(sTarget);
if (pQuery) {
pQuery->AddBuffer(Format, Message.GetText());
}
}
}
}
void CClient::EchoMessage(const CMessage& Message) {
CMessage EchoedMessage = Message;
for (CClient* pClient : GetClients()) {
if (pClient->HasEchoMessage() ||
(pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) ||
pClient->HasSelfMessage()))) {
EchoedMessage.SetNick(GetNickMask());
pClient->PutClient(EchoedMessage);
}
}
}
set<CChan*> CClient::MatchChans(const CString& sPatterns) const {
VCString vsPatterns;
sPatterns.Replace_n(",", " ")
.Split(" ", vsPatterns, false, "", "", true, true);
set<CChan*> sChans;
for (const CString& sPattern : vsPatterns) {
vector<CChan*> vChans = m_pNetwork->FindChans(sPattern);
sChans.insert(vChans.begin(), vChans.end());
}
return sChans;
}
unsigned int CClient::AttachChans(const std::set<CChan*>& sChans) {
unsigned int uAttached = 0;
for (CChan* pChan : sChans) {
if (!pChan->IsDetached()) continue;
uAttached++;
pChan->AttachUser();
}
return uAttached;
}
unsigned int CClient::DetachChans(const std::set<CChan*>& sChans) {
unsigned int uDetached = 0;
for (CChan* pChan : sChans) {
if (pChan->IsDetached()) continue;
uDetached++;
pChan->DetachUser();
}
return uDetached;
}
bool CClient::OnActionMessage(CActionMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserActionMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnCTCPMessage(CCTCPMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
if (Message.IsReply()) {
CString sCTCP = Message.GetText();
if (sCTCP.Token(0) == "VERSION") {
// There are 2 different scenarios:
//
// a) CTCP reply for VERSION is not set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC forwards CTCP VERSION to client
// 3. Client replies with something
// 4. ZNC adds itself to the reply
// 5. ZNC sends the modified reply to whoever asked
//
// b) CTCP reply for VERSION is set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC replies with the configured reply (or just drops it if
// empty), without forwarding anything to client
// 3. Client does not see any CTCP request, and does not reply
//
// So, if user doesn't want "via ZNC" in CTCP VERSION reply, they
// can set custom reply.
//
// See more bikeshedding at github issues #820 and #1012
Message.SetText(sCTCP + " via " + CZNC::GetTag(false));
}
}
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
if (Message.IsReply()) {
NETWORKMODULECALL(OnUserCTCPReplyMessage(Message), m_pUser,
m_pNetwork, this, &bContinue);
} else {
NETWORKMODULECALL(OnUserCTCPMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
}
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(t_f(
"Your CTCP to {1} got lost, you are not connected to IRC!")(
Message.GetTarget()));
continue;
}
if (m_pNetwork) {
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnJoinMessage(CJoinMessage& Message) {
CString sChans = Message.GetTarget();
CString sKeys = Message.GetKey();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
VCString vsKeys;
sKeys.Split(",", vsKeys, true);
sKeys.clear();
for (unsigned int a = 0; a < vsChans.size(); a++) {
Message.SetTarget(vsChans[a]);
Message.SetKey((a < vsKeys.size()) ? vsKeys[a] : "");
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(vsChans[a]));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserJoinMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
CString sChannel = Message.GetTarget();
CString sKey = Message.GetKey();
if (m_pNetwork) {
CChan* pChan = m_pNetwork->FindChan(sChannel);
if (pChan) {
if (pChan->IsDetached())
pChan->AttachUser(this);
else
pChan->JoinUser(sKey);
continue;
} else if (!sChannel.empty()) {
pChan = new CChan(sChannel, m_pNetwork, false);
if (m_pNetwork->AddChan(pChan)) {
pChan->SetKey(sKey);
}
}
}
if (!sChannel.empty()) {
sChans += (sChans.empty()) ? sChannel : CString("," + sChannel);
if (!vsKeys.empty()) {
sKeys += (sKeys.empty()) ? sKey : CString("," + sKey);
}
}
}
Message.SetTarget(sChans);
Message.SetKey(sKeys);
return sChans.empty();
}
bool CClient::OnModeMessage(CModeMessage& Message) {
CString sTarget = Message.GetTarget();
if (m_pNetwork && m_pNetwork->IsChan(sTarget) && !Message.HasModes()) {
// If we are on that channel and already received a
// /mode reply from the server, we can answer this
// request ourself.
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan && pChan->IsOn() && !pChan->GetModeString().empty()) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 324 " + GetNick() +
" " + sTarget + " " + pChan->GetModeString());
if (pChan->GetCreationDate() > 0) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 329 " +
GetNick() + " " + sTarget + " " +
CString(pChan->GetCreationDate()));
}
return true;
}
}
return false;
}
bool CClient::OnNoticeMessage(CNoticeMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
if (!sTarget.Equals("status")) {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModNotice(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserNoticeMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your notice to {1} got lost, you are not connected to "
"IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnPartMessage(CPartMessage& Message) {
CString sChans = Message.GetTarget();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
for (CString& sChan : vsChans) {
bool bContinue = false;
Message.SetTarget(sChan);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
NETWORKMODULECALL(OnUserPartMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
sChan = Message.GetTarget();
CChan* pChan = m_pNetwork ? m_pNetwork->FindChan(sChan) : nullptr;
if (pChan && !pChan->IsOn()) {
PutStatusNotice(t_f("Removing channel {1}")(sChan));
m_pNetwork->DelChan(sChan);
} else {
sChans += (sChans.empty()) ? sChan : CString("," + sChan);
}
}
if (sChans.empty()) {
return true;
}
Message.SetTarget(sChans);
return false;
}
bool CClient::OnPingMessage(CMessage& Message) {
// All PONGs are generated by ZNC. We will still forward this to
// the ircd, but all PONGs from irc will be blocked.
if (!Message.GetParams().empty())
PutClient(":irc.znc.in PONG irc.znc.in " + Message.GetParamsColon(0));
else
PutClient(":irc.znc.in PONG irc.znc.in");
return false;
}
bool CClient::OnPongMessage(CMessage& Message) {
// Block PONGs, we already responded to the pings
return true;
}
bool CClient::OnQuitMessage(CQuitMessage& Message) {
bool bReturn = false;
NETWORKMODULECALL(OnUserQuitMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
if (!bReturn) {
Close(Csock::CLT_AFTERWRITE); // Treat a client quit as a detach
}
// Don't forward this msg. We don't want the client getting us
// disconnected.
return true;
}
bool CClient::OnTextMessage(CTextMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
EchoMessage(Message);
if (sTarget.Equals("status")) {
CString sMsg = Message.GetText();
UserCommand(sMsg);
} else {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a PRIVMSG to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your message to {1} got lost, you are not connected "
"to IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnTopicMessage(CTopicMessage& Message) {
bool bReturn = false;
CString sChan = Message.GetTarget();
CString sTopic = Message.GetTopic();
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
if (!sTopic.empty()) {
NETWORKMODULECALL(OnUserTopicMessage(Message), m_pUser, m_pNetwork,
this, &bReturn);
} else {
NETWORKMODULECALL(OnUserTopicRequest(sChan), m_pUser, m_pNetwork, this,
&bReturn);
Message.SetTarget(sChan);
}
return bReturn;
}
bool CClient::OnOtherMessage(CMessage& Message) {
const CString& sCommand = Message.GetCommand();
if (sCommand.Equals("ZNC")) {
CString sTarget = Message.GetParam(0);
CString sModCommand;
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
sModCommand = Message.GetParamsColon(1);
} else {
sTarget = "status";
sModCommand = Message.GetParamsColon(0);
}
if (sTarget.Equals("status")) {
if (sModCommand.empty())
PutStatus(t_s("Hello. How may I help you?"));
else
UserCommand(sModCommand);
} else {
if (sModCommand.empty())
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
PutModule(t_s("Hello. How may I help you?")))
else
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(sModCommand))
}
return true;
} else if (sCommand.Equals("ATTACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /attach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uAttachedChans = AttachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Attached {1} channel", "Attached {1} channels",
uAttachedChans)(uAttachedChans));
return true;
} else if (sCommand.Equals("DETACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /detach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uDetached = DetachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Detached {1} channel", "Detached {1} channels",
uDetached)(uDetached));
return true;
} else if (sCommand.Equals("PROTOCTL")) {
for (const CString& sParam : Message.GetParams()) {
if (sParam == "NAMESX") {
m_bNamesx = true;
} else if (sParam == "UHNAMES") {
m_bUHNames = true;
}
}
return true; // If the server understands it, we already enabled namesx
// / uhnames
}
return false;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_4038_0 |
crossvul-cpp_data_good_4038_1 | /*
* Copyright (C) 2004-2020 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gmock/gmock.h>
#include "znctest.h"
using testing::HasSubstr;
namespace znc_inttest {
namespace {
TEST(Config, AlreadyExists) {
QTemporaryDir dir;
WriteConfig(dir.path());
Process p(ZNC_BIN_DIR "/znc", QStringList() << "--debug"
<< "--datadir" << dir.path()
<< "--makeconf");
p.ReadUntil("already exists");
p.CanDie();
}
TEST_F(ZNCTest, Connect) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.ReadUntil("CAP LS");
auto client = ConnectClient();
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
client.ReadUntil("Welcome");
client.Close();
client = ConnectClient();
client.Write("PASS :user:hunter2");
client.Write("NICK nick");
client.Write("USER u x x x");
client.ReadUntil("Welcome");
client.Close();
client = ConnectClient();
client.Write("NICK nick");
client.Write("USER user x x x");
client.ReadUntil("Configure your client to send a server password");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("WHO");
}
TEST_F(ZNCTest, Channel) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.ReadUntil("Welcome");
client.Write("JOIN #znc");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc");
ircd.Write(":nick JOIN :#znc");
ircd.Write(":server 353 nick #znc :nick");
ircd.Write(":server 366 nick #znc :End of /NAMES list");
ircd.Write(":server PING :1");
ircd.ReadUntil("PONG 1");
client = LoginClient();
client.ReadUntil(":nick JOIN :#znc");
}
TEST_F(ZNCTest, HTTP) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto reply = HttpGet(QNetworkRequest(QUrl("http://127.0.0.1:12345/")));
EXPECT_THAT(reply->rawHeader("Server").toStdString(), HasSubstr("ZNC"));
}
TEST_F(ZNCTest, FixCVE20149403) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.Write(":server 005 nick CHANTYPES=# :supports");
ircd.Write(":server PING :1");
ircd.ReadUntil("PONG 1");
QNetworkRequest request;
request.setRawHeader("Authorization",
"Basic " + QByteArray("user:hunter2").toBase64());
request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
HttpPost(request, {
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "znc"},
{"enabled", "1"},
});
EXPECT_THAT(HttpPost(request,
{
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "znc"},
{"enabled", "1"},
})
->readAll()
.toStdString(),
HasSubstr("Channel [#znc] already exists"));
}
TEST_F(ZNCTest, FixFixOfCVE20149403) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.Write(":nick JOIN @#znc");
ircd.ReadUntil("MODE @#znc");
ircd.Write(":server 005 nick STATUSMSG=@ :supports");
ircd.Write(":server PING :12345");
ircd.ReadUntil("PONG 12345");
QNetworkRequest request;
request.setRawHeader("Authorization",
"Basic " + QByteArray("user:hunter2").toBase64());
request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
auto reply = HttpPost(request, {
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "@#znc"},
{"enabled", "1"},
});
EXPECT_THAT(reply->readAll().toStdString(),
HasSubstr("Could not add channel [@#znc]"));
}
TEST_F(ZNCTest, InvalidConfigInChan) {
QFile conf(m_dir.path() + "/configs/znc.conf");
ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
QTextStream out(&conf);
out << R"(
<User foo>
<Network bar>
<Chan #baz>
Invalid = Line
</Chan>
</Network>
</User>
)";
out.flush();
auto znc = Run();
znc->ShouldFinishItself(1);
}
TEST_F(ZNCTest, Encoding) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
ircd.Write(":server 001 nick :hello");
// legacy
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xE6world");
client.Write("PRIVMSG *controlpanel :SetNetwork Encoding $me $net UTF-8");
client.ReadUntil("Encoding = UTF-8");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xEF\xBF\xBDworld");
client.Write(
"PRIVMSG *controlpanel :SetNetwork Encoding $me $net ^CP-1251");
client.ReadUntil("Encoding = ^CP-1251");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xD0\xB6world");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xD0\xB6world");
client.ReadUntil("Hello\xD0\xB6world");
}
TEST_F(ZNCTest, BuildMod) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
QTemporaryDir srcd;
QDir srcdir(srcd.path());
QFile file(srcdir.filePath("testmod.cpp"));
ASSERT_TRUE(file.open(QIODevice::WriteOnly | QIODevice::Text));
QTextStream out(&file);
out << R"(
#include <znc/Modules.h>
class TestModule : public CModule {
public:
MODCONSTRUCTOR(TestModule) {}
void OnModCommand(const CString& sLine) override {
PutModule("Lorem ipsum");
}
};
MODULEDEFS(TestModule, "Test")
)";
file.close();
QDir dir(m_dir.path());
EXPECT_TRUE(dir.mkdir("modules"));
EXPECT_TRUE(dir.cd("modules"));
{
Process p(ZNC_BIN_DIR "/znc-buildmod",
QStringList() << srcdir.filePath("file-not-found.cpp"),
[&](QProcess* proc) {
proc->setWorkingDirectory(dir.absolutePath());
proc->setProcessChannelMode(QProcess::ForwardedChannels);
});
p.ShouldFinishItself(1);
p.ShouldFinishInSec(300);
}
{
Process p(ZNC_BIN_DIR "/znc-buildmod",
QStringList() << srcdir.filePath("testmod.cpp"),
[&](QProcess* proc) {
proc->setWorkingDirectory(dir.absolutePath());
proc->setProcessChannelMode(QProcess::ForwardedChannels);
});
p.ShouldFinishItself();
p.ShouldFinishInSec(300);
}
client.Write("znc loadmod testmod");
client.Write("PRIVMSG *testmod :hi");
client.ReadUntil("Lorem ipsum");
}
TEST_F(ZNCTest, AwayNotify) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = ConnectClient();
client.Write("CAP LS");
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
QByteArray cap_ls;
client.ReadUntilAndGet(" LS :", cap_ls);
ASSERT_THAT(cap_ls.toStdString(),
AllOf(HasSubstr("cap-notify"), Not(HasSubstr("away-notify"))));
client.Write("CAP REQ :cap-notify");
client.ReadUntil("ACK :cap-notify");
client.Write("CAP END");
client.ReadUntil(" 001 ");
ircd.ReadUntil("USER");
ircd.Write("CAP user LS :away-notify");
ircd.ReadUntil("CAP REQ :away-notify");
ircd.Write("CAP user ACK :away-notify");
ircd.ReadUntil("CAP END");
ircd.Write(":server 001 user :welcome");
client.ReadUntil("CAP user NEW :away-notify");
client.Write("CAP REQ :away-notify");
client.ReadUntil("ACK :away-notify");
ircd.Write(":x!y@z AWAY :reason");
client.ReadUntil(":x!y@z AWAY :reason");
ircd.Close();
client.ReadUntil("DEL :away-notify");
}
TEST_F(ZNCTest, JoinKey) {
QFile conf(m_dir.path() + "/configs/znc.conf");
ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
QTextStream(&conf) << "ServerThrottle = 1\n";
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
ircd.Write(":server 001 nick :Hello");
client.Write("JOIN #znc secret");
ircd.ReadUntil("JOIN #znc secret");
ircd.Write(":nick JOIN :#znc");
client.ReadUntil("JOIN :#znc");
ircd.Close();
ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc secret");
}
TEST_F(ZNCTest, StatusEchoMessage) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("CAP REQ :echo-message");
client.Write("PRIVMSG *status :blah");
client.ReadUntil(":nick!user@irc.znc.in PRIVMSG *status :blah");
client.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command");
}
} // namespace
} // namespace znc_inttest
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_4038_1 |
crossvul-cpp_data_good_2609_0 | /*****************************************************************
|
| AP4 - Atom Based Sample Tables
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This atom is part of AP4 (MP4 Audio Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the atom COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4AtomSampleTable.h"
#include "Ap4ByteStream.h"
#include "Ap4StsdAtom.h"
#include "Ap4StscAtom.h"
#include "Ap4StcoAtom.h"
#include "Ap4Co64Atom.h"
#include "Ap4StszAtom.h"
#include "Ap4Stz2Atom.h"
#include "Ap4SttsAtom.h"
#include "Ap4CttsAtom.h"
#include "Ap4StssAtom.h"
#include "Ap4Sample.h"
#include "Ap4Atom.h"
/*----------------------------------------------------------------------
| AP4_AtomSampleTable Dynamic Cast Anchor
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AtomSampleTable)
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::AP4_AtomSampleTable
+---------------------------------------------------------------------*/
AP4_AtomSampleTable::AP4_AtomSampleTable(AP4_ContainerAtom* stbl,
AP4_ByteStream& sample_stream) :
m_SampleStream(sample_stream)
{
m_StscAtom = AP4_DYNAMIC_CAST(AP4_StscAtom, stbl->GetChild(AP4_ATOM_TYPE_STSC));
m_StcoAtom = AP4_DYNAMIC_CAST(AP4_StcoAtom, stbl->GetChild(AP4_ATOM_TYPE_STCO));
m_StszAtom = AP4_DYNAMIC_CAST(AP4_StszAtom, stbl->GetChild(AP4_ATOM_TYPE_STSZ));
m_Stz2Atom = AP4_DYNAMIC_CAST(AP4_Stz2Atom, stbl->GetChild(AP4_ATOM_TYPE_STZ2));
m_CttsAtom = AP4_DYNAMIC_CAST(AP4_CttsAtom, stbl->GetChild(AP4_ATOM_TYPE_CTTS));
m_SttsAtom = AP4_DYNAMIC_CAST(AP4_SttsAtom, stbl->GetChild(AP4_ATOM_TYPE_STTS));
m_StssAtom = AP4_DYNAMIC_CAST(AP4_StssAtom, stbl->GetChild(AP4_ATOM_TYPE_STSS));
m_StsdAtom = AP4_DYNAMIC_CAST(AP4_StsdAtom, stbl->GetChild(AP4_ATOM_TYPE_STSD));
m_Co64Atom = AP4_DYNAMIC_CAST(AP4_Co64Atom, stbl->GetChild(AP4_ATOM_TYPE_CO64));
// keep a reference to the sample stream
m_SampleStream.AddReference();
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::~AP4_AtomSampleTable
+---------------------------------------------------------------------*/
AP4_AtomSampleTable::~AP4_AtomSampleTable()
{
m_SampleStream.Release();
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
AP4_Sample& sample)
{
AP4_Result result;
// check that we have an stsc atom
if (!m_StscAtom) {
return AP4_ERROR_INVALID_FORMAT;
}
// check that we have a chunk offset table
if (m_StcoAtom == NULL && m_Co64Atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// MP4 uses 1-based indexes internally, so adjust by one
index++;
// find out in which chunk this sample is located
AP4_Ordinal chunk, skip, desc;
result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);
if (AP4_FAILED(result)) return result;
// check that the result is within bounds
if (skip > index) return AP4_ERROR_INTERNAL;
// get the atom offset for this chunk
AP4_UI64 offset;
if (m_StcoAtom) {
AP4_UI32 offset_32;
result = m_StcoAtom->GetChunkOffset(chunk, offset_32);
offset = offset_32;
} else {
result = m_Co64Atom->GetChunkOffset(chunk, offset);
}
if (AP4_FAILED(result)) return result;
// compute the additional offset inside the chunk
for (unsigned int i = index-skip; i < index; i++) {
AP4_Size size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(i, size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(i, size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
offset += size;
}
// set the description index
sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes
// set the dts and cts
AP4_UI32 cts_offset = 0;
AP4_UI64 dts = 0;
AP4_UI32 duration = 0;
result = m_SttsAtom->GetDts(index, dts, &duration);
if (AP4_FAILED(result)) return result;
sample.SetDuration(duration);
sample.SetDts(dts);
if (m_CttsAtom == NULL) {
sample.SetCts(dts);
} else {
result = m_CttsAtom->GetCtsOffset(index, cts_offset);
if (AP4_FAILED(result)) return result;
sample.SetCtsDelta(cts_offset);
}
// set the size
AP4_Size sample_size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(index, sample_size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(index, sample_size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
sample.SetSize(sample_size);
// set the sync flag
if (m_StssAtom == NULL) {
sample.SetSync(true);
} else {
sample.SetSync(m_StssAtom->IsSampleSync(index));
}
// set the offset
sample.SetOffset(offset);
// set the data stream
sample.SetDataStream(m_SampleStream);
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleCount
+---------------------------------------------------------------------*/
AP4_Cardinal
AP4_AtomSampleTable::GetSampleCount()
{
if (m_StszAtom) {
return m_StszAtom->GetSampleCount();
} else if (m_Stz2Atom) {
return m_Stz2Atom->GetSampleCount();
} else {
return 0;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleDescription
+---------------------------------------------------------------------*/
AP4_SampleDescription*
AP4_AtomSampleTable::GetSampleDescription(AP4_Ordinal index)
{
return m_StsdAtom ? m_StsdAtom->GetSampleDescription(index) : NULL;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleDescriptionCount
+---------------------------------------------------------------------*/
AP4_Cardinal
AP4_AtomSampleTable::GetSampleDescriptionCount()
{
return m_StsdAtom ? m_StsdAtom->GetSampleDescriptionCount() : 0;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleChunkPosition
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
AP4_Ordinal sample_description_index;
return GetChunkForSample(sample_index,
chunk_index,
position_in_chunk,
sample_description_index);
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkForSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetChunkForSample(AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk,
AP4_Ordinal& sample_description_index)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
sample_description_index = 0;
// check that we an stsc atom
if (m_StscAtom == NULL) return AP4_ERROR_INVALID_STATE;
// get the chunk info from the stsc atom
AP4_Ordinal chunk = 0;
AP4_Result result = m_StscAtom->GetChunkForSample(sample_index+1, // the atom API is 1-based
chunk,
position_in_chunk,
sample_description_index);
if (AP4_FAILED(result)) return result;
if (chunk == 0) return AP4_ERROR_INTERNAL;
// the atom sample and chunk indexes are 1-based, so we need to translate
chunk_index = chunk-1;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkOffset
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position& offset)
{
if (m_StcoAtom) {
AP4_UI32 offset_32;
AP4_Result result = m_StcoAtom->GetChunkOffset(chunk_index+1, offset_32);
if (AP4_SUCCEEDED(result)) {
offset = offset_32;
} else {
offset = 0;
}
return result;
} else if (m_Co64Atom) {
return m_Co64Atom->GetChunkOffset(chunk_index+1, offset);
} else {
offset = 0;
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetChunkOffset
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::SetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position offset)
{
if (m_StcoAtom) {
if ((offset >> 32) != 0) return AP4_ERROR_OUT_OF_RANGE;
return m_StcoAtom->SetChunkOffset(chunk_index+1, (AP4_UI32)offset);
} else if (m_Co64Atom) {
return m_Co64Atom->SetChunkOffset(chunk_index+1, offset);
} else {
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetSampleSize
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::SetSampleSize(AP4_Ordinal sample_index, AP4_Size size)
{
if (m_StszAtom) {
return m_StszAtom->SetSampleSize(sample_index+1, size);
} else if (m_Stz2Atom) {
return m_Stz2Atom->SetSampleSize(sample_index+1, size);
} else {
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleIndexForTimeStamp
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 ts,
AP4_Ordinal& sample_index)
{
return m_SttsAtom ? m_SttsAtom->GetSampleIndexForTimeStamp(ts, sample_index)
: AP4_FAILURE;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetNearestSyncSampleIndex
+---------------------------------------------------------------------*/
AP4_Ordinal
AP4_AtomSampleTable::GetNearestSyncSampleIndex(AP4_Ordinal sample_index, bool before)
{
// if we don't have an stss table, all samples match
if (m_StssAtom == NULL) return sample_index;
sample_index += 1; // the table is 1-based
AP4_Cardinal entry_count = m_StssAtom->GetEntries().ItemCount();
if (before) {
AP4_Ordinal cursor = 0;
for (unsigned int i=0; i<entry_count; i++) {
if (m_StssAtom->GetEntries()[i] >= sample_index) return cursor;
if (m_StssAtom->GetEntries()[i]) cursor = m_StssAtom->GetEntries()[i]-1;
}
// not found?
return cursor;
} else {
for (unsigned int i=0; i<entry_count; i++) {
if (m_StssAtom->GetEntries()[i] >= sample_index) {
return m_StssAtom->GetEntries()[i]?m_StssAtom->GetEntries()[i]-1:sample_index-1;
}
}
// not found?
return GetSampleCount();
}
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_2609_0 |
crossvul-cpp_data_bad_4244_0 | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
//
// Add a preview image to an OpenEXR file.
//
//----------------------------------------------------------------------------
#include "makePreview.h"
#include <ImfInputFile.h>
#include <ImfOutputFile.h>
#include <ImfTiledOutputFile.h>
#include <ImfRgbaFile.h>
#include <ImfPreviewImage.h>
#include <ImfArray.h>
#include <ImathMath.h>
#include <ImathFun.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <OpenEXRConfig.h>
using namespace OPENEXR_IMF_NAMESPACE;
using namespace IMATH_NAMESPACE;
using namespace std;
namespace {
float
knee (float x, float f)
{
return log (x * f + 1) / f;
}
unsigned char
gamma (half h, float m)
{
//
// Conversion from half to unsigned char pixel data,
// with gamma correction. The conversion is the same
// as in the exrdisplay program's ImageView class,
// except with defog, kneeLow, and kneeHigh fixed
// at 0.0, 0.0, and 5.0 respectively.
//
float x = max (0.f, h * m);
if (x > 1)
x = 1 + knee (x - 1, 0.184874f);
return (unsigned char) (IMATH_NAMESPACE::clamp (Math<float>::pow (x, 0.4545f) * 84.66f,
0.f,
255.f));
}
void
generatePreview (const char inFileName[],
float exposure,
int previewWidth,
int &previewHeight,
Array2D <PreviewRgba> &previewPixels)
{
//
// Read the input file
//
RgbaInputFile in (inFileName);
Box2i dw = in.dataWindow();
float a = in.pixelAspectRatio();
int w = dw.max.x - dw.min.x + 1;
int h = dw.max.y - dw.min.y + 1;
Array2D <Rgba> pixels (h, w);
in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);
in.readPixels (dw.min.y, dw.max.y);
//
// Make a preview image
//
previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);
previewPixels.resizeErase (previewHeight, previewWidth);
float fx = (previewWidth > 0)? (float (w - 1) / (previewWidth - 1)): 1;
float fy = (previewHeight > 0)? (float (h - 1) / (previewHeight - 1)): 1;
float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));
for (int y = 0; y < previewHeight; ++y)
{
for (int x = 0; x < previewWidth; ++x)
{
PreviewRgba &preview = previewPixels[y][x];
const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];
preview.r = gamma (pixel.r, m);
preview.g = gamma (pixel.g, m);
preview.b = gamma (pixel.b, m);
preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);
}
}
}
} // namespace
void
makePreview (const char inFileName[],
const char outFileName[],
int previewWidth,
float exposure,
bool verbose)
{
if (verbose)
cout << "generating preview image" << endl;
Array2D <PreviewRgba> previewPixels;
int previewHeight;
generatePreview (inFileName,
exposure,
previewWidth,
previewHeight,
previewPixels);
InputFile in (inFileName);
Header header = in.header();
header.setPreviewImage
(PreviewImage (previewWidth, previewHeight, &previewPixels[0][0]));
if (verbose)
cout << "copying " << inFileName << " to " << outFileName << endl;
if (header.hasTileDescription())
{
TiledOutputFile out (outFileName, header);
out.copyPixels (in);
}
else
{
OutputFile out (outFileName, header);
out.copyPixels (in);
}
if (verbose)
cout << "done." << endl;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_4244_0 |
crossvul-cpp_data_good_2811_0 | /*****************************************************************
|
| AP4 - hdlr Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4HdlrAtom.h"
#include "Ap4AtomFactory.h"
#include "Ap4Utils.h"
/*----------------------------------------------------------------------
| dynamic cast support
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_HdlrAtom)
/*----------------------------------------------------------------------
| AP4_HdlrAtom::Create
+---------------------------------------------------------------------*/
AP4_HdlrAtom*
AP4_HdlrAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI08 version;
AP4_UI32 flags;
if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
if (version != 0) return NULL;
return new AP4_HdlrAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_HdlrAtom::AP4_HdlrAtom
+---------------------------------------------------------------------*/
AP4_HdlrAtom::AP4_HdlrAtom(AP4_Atom::Type hdlr_type, const char* hdlr_name) :
AP4_Atom(AP4_ATOM_TYPE_HDLR, AP4_FULL_ATOM_HEADER_SIZE, 0, 0),
m_HandlerType(hdlr_type),
m_HandlerName(hdlr_name)
{
m_Size32 += 20+m_HandlerName.GetLength()+1;
m_Reserved[0] = m_Reserved[1] = m_Reserved[2] = 0;
}
/*----------------------------------------------------------------------
| AP4_HdlrAtom::AP4_HdlrAtom
+---------------------------------------------------------------------*/
AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)
{
AP4_UI32 predefined;
stream.ReadUI32(predefined);
stream.ReadUI32(m_HandlerType);
stream.ReadUI32(m_Reserved[0]);
stream.ReadUI32(m_Reserved[1]);
stream.ReadUI32(m_Reserved[2]);
// read the name unless it is empty
if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return;
AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);
char* name = new char[name_size+1];
if (name == NULL) return;
stream.Read(name, name_size);
name[name_size] = '\0'; // force a null termination
// handle a special case: the Quicktime files have a pascal
// string here, but ISO MP4 files have a C string.
// we try to detect a pascal encoding and correct it.
if (name[0] == name_size-1) {
m_HandlerName = name+1;
} else {
m_HandlerName = name;
}
delete[] name;
}
/*----------------------------------------------------------------------
| AP4_HdlrAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_HdlrAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
// write the data
result = stream.WriteUI32(0); // predefined
if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_HandlerType);
if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved[0]);
if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved[1]);
if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved[2]);
if (AP4_FAILED(result)) return result;
AP4_UI08 name_size = (AP4_UI08)m_HandlerName.GetLength();
if (AP4_FULL_ATOM_HEADER_SIZE+20+name_size > m_Size32) {
name_size = (AP4_UI08)(m_Size32-AP4_FULL_ATOM_HEADER_SIZE+20);
}
if (name_size) {
result = stream.Write(m_HandlerName.GetChars(), name_size);
if (AP4_FAILED(result)) return result;
}
// pad with zeros if necessary
AP4_Size padding = m_Size32-(AP4_FULL_ATOM_HEADER_SIZE+20+name_size);
while (padding--) stream.WriteUI08(0);
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_HdlrAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_HdlrAtom::InspectFields(AP4_AtomInspector& inspector)
{
char type[5];
AP4_FormatFourChars(type, m_HandlerType);
inspector.AddField("handler_type", type);
inspector.AddField("handler_name", m_HandlerName.GetChars());
return AP4_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_2811_0 |
crossvul-cpp_data_bad_3266_0 | /*
*
* (C) 2013-17 - ntop.org
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include "ntop_includes.h"
#ifndef _GETOPT_H
#define _GETOPT_H
#endif
#ifndef LIB_VERSION
#define LIB_VERSION "1.4.7"
#endif
extern "C" {
#include "rrd.h"
#ifdef HAVE_GEOIP
extern const char * GeoIP_lib_version(void);
#endif
#include "../third-party/snmp/snmp.c"
#include "../third-party/snmp/asn1.c"
#include "../third-party/snmp/net.c"
};
#include "../third-party/lsqlite3/lsqlite3.c"
struct keyval string_to_replace[MAX_NUM_HTTP_REPLACEMENTS] = { { NULL, NULL } };
/* ******************************* */
Lua::Lua() {
L = luaL_newstate();
if(L == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "Unable to create Lua interpreter");
return;
}
}
/* ******************************* */
Lua::~Lua() {
if(L) lua_close(L);
}
/* ******************************* */
/**
* @brief Check the expected type of lua function.
* @details Find in the lua stack the function and check the function parameters types.
*
* @param vm The lua state.
* @param func The function name.
* @param pos Index of lua stack.
* @param expected_type Index of expected type.
* @return @ref CONST_LUA_ERROR if the expected type is equal to function type, @ref CONST_LUA_PARAM_ERROR otherwise.
*/
int ntop_lua_check(lua_State* vm, const char* func, int pos, int expected_type) {
if(lua_type(vm, pos) != expected_type) {
ntop->getTrace()->traceEvent(TRACE_ERROR,
"%s : expected %s, got %s", func,
lua_typename(vm, expected_type),
lua_typename(vm, lua_type(vm,pos)));
return(CONST_LUA_PARAM_ERROR);
}
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static void get_host_vlan_info(char* lua_ip, char** host_ip,
u_int16_t* vlan_id,
char *buf, u_int buf_len) {
char *where, *vlan = NULL;
snprintf(buf, buf_len, "%s", lua_ip);
if(((*host_ip) = strtok_r(buf, "@", &where)) != NULL)
vlan = strtok_r(NULL, "@", &where);
if(vlan)
(*vlan_id) = (u_int16_t)atoi(vlan);
}
/* ****************************************** */
static NetworkInterface* handle_null_interface(lua_State* vm) {
char allowed_ifname[MAX_INTERFACE_NAME_LEN];
ntop->getTrace()->traceEvent(TRACE_INFO, "NULL interface: did you restart ntopng in the meantime?");
if(ntop->getInterfaceAllowed(vm, allowed_ifname)) {
return ntop->getNetworkInterface(allowed_ifname);
}
return(ntop->getInterfaceAtId(0));
}
/* ****************************************** */
static int ntop_dump_file(lua_State* vm) {
char *fname;
FILE *fd;
struct mg_connection *conn;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, CONST_HTTP_CONN);
if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection");
return(CONST_LUA_ERROR);
}
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((fname = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->fixPath(fname);
if((fd = fopen(fname, "r")) != NULL) {
char tmp[1024];
ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] Serving file %s", fname);
while((fgets(tmp, sizeof(tmp)-256 /* To make sure we have room for replacements */, fd)) != NULL) {
for(int i=0; string_to_replace[i].key != NULL; i++)
Utils::replacestr(tmp, string_to_replace[i].key, string_to_replace[i].val);
mg_printf(conn, "%s", tmp);
}
fclose(fd);
return(CONST_LUA_OK);
} else {
ntop->getTrace()->traceEvent(TRACE_INFO, "Unable to read file %s", fname);
return(CONST_LUA_ERROR);
}
}
/* ****************************************** */
/**
* @brief Get default interface name.
* @details Push the default interface name of ntop into the lua stack.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK.
*/
static int ntop_get_default_interface_name(lua_State* vm) {
char ifname[MAX_INTERFACE_NAME_LEN];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop->getInterfaceAllowed(vm, ifname)) {
// if there is an allowed interface for the user
// we return that interface
lua_pushstring(vm,
ntop->getNetworkInterface(ifname)->get_name());
} else {
lua_pushstring(vm, ntop->getInterfaceAtId(NULL, /* no need to check as there is no constaint */
0)->get_name());
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Set the name of active interface id into lua stack.
*
* @param vm The lua stack.
* @return @ref CONST_LUA_OK.
*/
static int ntop_set_active_interface_id(lua_State* vm) {
NetworkInterface *iface;
int id;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
id = (u_int32_t)lua_tonumber(vm, 1);
iface = ntop->getNetworkInterface(vm, id);
ntop->getTrace()->traceEvent(TRACE_INFO, "Index: %d, Name: %s", id, iface ? iface->get_name() : "<unknown>");
if(iface != NULL)
lua_pushstring(vm, iface->get_name());
else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the ntopng interface names.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK.
*/
static int ntop_get_interface_names(lua_State* vm) {
lua_newtable(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
for(int i=0; i<ntop->get_num_interfaces(); i++) {
NetworkInterface *iface;
if((iface = ntop->getInterfaceAtId(vm, i)) != NULL) {
char num[8];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "Returning name %s", iface->get_name());
snprintf(num, sizeof(num), "%d", i);
lua_push_str_table_entry(vm, num, iface->get_name());
}
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static AddressTree* get_allowed_nets(lua_State* vm) {
AddressTree *ptree;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, CONST_ALLOWED_NETS);
ptree = (AddressTree*)lua_touserdata(vm, lua_gettop(vm));
//ntop->getTrace()->traceEvent(TRACE_WARNING, "GET %p", ptree);
return(ptree);
}
/* ****************************************** */
static NetworkInterface* getCurrentInterface(lua_State* vm) {
NetworkInterface *ntop_interface;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, "ntop_interface");
if((ntop_interface = (NetworkInterface*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop_interface = handle_null_interface(vm);
}
return(ntop_interface);
}
/* ****************************************** */
/**
* @brief Find the network interface and set it as global variable to lua.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_select_interface(lua_State* vm) {
char *ifname;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TNIL)
ifname = (char*)"any";
else {
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
ifname = (char*)lua_tostring(vm, 1);
}
lua_pushlightuserdata(vm, (char*)ntop->getNetworkInterface(vm, ifname));
lua_setglobal(vm, "ntop_interface");
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the nDPI statistics of interface.
* @details Get the ntop interface global variable of lua, get nDpistats of interface and push it into lua stack.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_ndpi_interface_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
char *host_ip = NULL;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
/* Optional host */
if(lua_type(vm, 1) == LUA_TSTRING) get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if(ntop_interface) {
ntop_interface->getnDPIStats(&stats, get_allowed_nets(vm), host_ip, vlan_id);
lua_newtable(vm);
stats.lua(ntop_interface, vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
#ifdef NTOPNG_PRO
/**
* @brief Get the Host Pool statistics of interface.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_host_pool_interface_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface && ntop_interface->getHostPools()) {
ntop_interface->luaHostPoolsStats(vm);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/**
* @brief Get the Host Pool volatile members
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_host_pool_volatile_members(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface && ntop_interface->getHostPools()) {
ntop_interface->luaHostPoolsVolatileMembers(vm);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
#endif
/* ****************************************** */
/**
* @brief Get the ndpi flows count of interface.
* @details Get the ntop interface global variable of lua, get nDpi flow count of interface and push it into lua stack.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_ndpi_interface_flows_count(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) {
lua_newtable(vm);
ntop_interface->getnDPIFlowsCount(vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the flow status for flows in cache
* @details Get the ntop interface global variable of lua, get flow stats of interface and push it into lua stack.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_ndpi_interface_flows_status(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) {
lua_newtable(vm);
ntop_interface->getFlowsStatus(vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the ndpi protocol name of protocol id of network interface.
* @details Get the ntop interface global variable of lua. Once do that, get the protocol id of lua stack and return into lua stack "Host-to-Host Contact" if protocol id is equal to host family id; the protocol name or null otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_ndpi_protocol_name(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
int proto;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
proto = (u_int32_t)lua_tonumber(vm, 1);
if(proto == HOST_FAMILY_ID)
lua_pushstring(vm, "Host-to-Host Contact");
else {
if(ntop_interface)
lua_pushstring(vm, ntop_interface->get_ndpi_proto_name(proto));
else
lua_pushnil(vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_ndpi_protocol_id(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
char *proto;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
proto = (char*)lua_tostring(vm, 1);
if(ntop_interface && proto)
lua_pushnumber(vm, ntop_interface->get_ndpi_proto_id(proto));
else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_ndpi_protocol_category(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int proto;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
proto = (u_int)lua_tonumber(vm, 1);
if(ntop_interface) {
ndpi_protocol_category_t category = ntop_interface->get_ndpi_proto_category(proto);
lua_newtable(vm);
lua_push_int32_table_entry(vm, "id", category);
lua_push_str_table_entry(vm, "name", (char*)ndpi_category_str(category));
} else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Same as ntop_get_ndpi_protocol_name() with the exception that the protocol breed is returned
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_ndpi_protocol_breed(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
int proto;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
proto = (u_int32_t)lua_tonumber(vm, 1);
if(proto == HOST_FAMILY_ID)
lua_pushstring(vm, "Unrated-to-Host Contact");
else {
if(ntop_interface)
lua_pushstring(vm, ntop_interface->get_ndpi_proto_breed_name(proto));
else
lua_pushnil(vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_hosts(lua_State* vm, LocationPolicy location) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool show_details = true;
char *sortColumn = (char*)"column_ip", *country = NULL, *os_filter = NULL, *mac_filter = NULL;
bool a2zSortOrder = true;
u_int16_t vlan_filter, *vlan_filter_ptr = NULL;
u_int32_t asn_filter, *asn_filter_ptr = NULL;
int16_t network_filter, *network_filter_ptr = NULL;
u_int16_t pool_filter, *pool_filter_ptr = NULL;
u_int32_t toSkip = 0, maxHits = CONST_MAX_NUM_HITS;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TBOOLEAN) show_details = lua_toboolean(vm, 1) ? true : false;
if(lua_type(vm, 2) == LUA_TSTRING) sortColumn = (char*)lua_tostring(vm, 2);
if(lua_type(vm, 3) == LUA_TNUMBER) maxHits = (u_int16_t)lua_tonumber(vm, 3);
if(lua_type(vm, 4) == LUA_TNUMBER) toSkip = (u_int16_t)lua_tonumber(vm, 4);
if(lua_type(vm, 5) == LUA_TBOOLEAN) a2zSortOrder = lua_toboolean(vm, 5) ? true : false;
if(lua_type(vm, 6) == LUA_TSTRING) country = (char*)lua_tostring(vm, 6);
if(lua_type(vm, 7) == LUA_TSTRING) os_filter = (char*)lua_tostring(vm, 7);
if(lua_type(vm, 8) == LUA_TNUMBER) vlan_filter = (u_int16_t)lua_tonumber(vm, 8), vlan_filter_ptr = &vlan_filter;
if(lua_type(vm, 9) == LUA_TNUMBER) asn_filter = (u_int32_t)lua_tonumber(vm, 9), asn_filter_ptr = &asn_filter;
if(lua_type(vm,10) == LUA_TNUMBER) network_filter = (int16_t)lua_tonumber(vm, 10), network_filter_ptr = &network_filter;
if(lua_type(vm,11) == LUA_TSTRING) mac_filter = (char*)lua_tostring(vm, 11);
if(lua_type(vm,12) == LUA_TNUMBER) pool_filter = (u_int16_t)lua_tonumber(vm, 12), pool_filter_ptr = &pool_filter;
if(!ntop_interface ||
ntop_interface->getActiveHostsList(vm, get_allowed_nets(vm),
show_details, location,
country, mac_filter,
vlan_filter_ptr, os_filter, asn_filter_ptr,
network_filter_ptr, pool_filter_ptr,
sortColumn, maxHits,
toSkip, a2zSortOrder) < 0)
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_latest_activity_hosts_info(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->getLatestActivityHostsList(vm, get_allowed_nets(vm));
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the host information of network interface grouped according to the criteria.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null or the host is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_grouped_interface_hosts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool show_details = true, hostsOnly = true;
char *country = NULL, *os_filter = NULL;
char *groupBy = (char*)"column_ip";
u_int16_t vlan_filter, *vlan_filter_ptr = NULL;
u_int32_t asn_filter, *asn_filter_ptr = NULL;
u_int16_t pool_filter, *pool_filter_ptr = NULL;
int16_t network_filter, *network_filter_ptr = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TBOOLEAN) show_details = lua_toboolean(vm, 1) ? true : false;
if(lua_type(vm, 2) == LUA_TSTRING) groupBy = (char*)lua_tostring(vm, 2);
if(lua_type(vm, 3) == LUA_TSTRING) country = (char*)lua_tostring(vm, 3);
if(lua_type(vm, 4) == LUA_TSTRING) os_filter = (char*)lua_tostring(vm, 4);
if(lua_type(vm, 5) == LUA_TNUMBER) vlan_filter = (u_int16_t)lua_tonumber(vm, 5), vlan_filter_ptr = &vlan_filter;
if(lua_type(vm, 6) == LUA_TNUMBER) asn_filter = (u_int32_t)lua_tonumber(vm, 6), asn_filter_ptr = &asn_filter;
if(lua_type(vm, 7) == LUA_TNUMBER) network_filter = (int16_t)lua_tonumber(vm, 7), network_filter_ptr = &network_filter;
if(lua_type(vm, 8) == LUA_TBOOLEAN) hostsOnly = lua_toboolean(vm, 8) ? true : false;
if(lua_type(vm, 9) == LUA_TNUMBER) pool_filter = (u_int16_t)lua_tonumber(vm, 9), pool_filter_ptr = &pool_filter;
if((!ntop_interface)
|| ntop_interface->getActiveHostsGroup(vm, get_allowed_nets(vm),
show_details, location_all,
country,
vlan_filter_ptr, os_filter,
asn_filter_ptr, network_filter_ptr,
pool_filter_ptr,
hostsOnly, groupBy) < 0)
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the hosts information of network interface.
* @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the host information.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_hosts_info(lua_State* vm) {
return(ntop_get_interface_hosts(vm, location_all));
}
/* ****************************************** */
static int ntop_get_interface_macs_info(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *sortColumn = (char*)"column_mac";
u_int32_t toSkip = 0, maxHits = CONST_MAX_NUM_HITS;
u_int16_t vlan_id = 0;
bool a2zSortOrder = true,
skipSpecialMacs = false, hostMacsOnly = false;
if(lua_type(vm, 1) == LUA_TSTRING) {
sortColumn = (char*)lua_tostring(vm, 1);
if(lua_type(vm, 2) == LUA_TNUMBER) {
maxHits = (u_int16_t)lua_tonumber(vm, 2);
if(lua_type(vm, 3) == LUA_TNUMBER) {
toSkip = (u_int16_t)lua_tonumber(vm, 3);
if(lua_type(vm, 4) == LUA_TBOOLEAN) {
a2zSortOrder = lua_toboolean(vm, 4) ? true : false;
if(lua_type(vm, 5) == LUA_TNUMBER) {
vlan_id = (u_int16_t)lua_tonumber(vm, 5);
if(lua_type(vm, 6) == LUA_TBOOLEAN) {
skipSpecialMacs = lua_toboolean(vm, 6) ? true : false;
}
if(lua_type(vm, 7) == LUA_TBOOLEAN) {
hostMacsOnly = lua_toboolean(vm, 7) ? true : false;
}
}
}
}
}
}
if(!ntop_interface ||
ntop_interface->getActiveMacList(vm, vlan_id, skipSpecialMacs,
hostMacsOnly,
sortColumn, maxHits,
toSkip, a2zSortOrder) < 0)
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_mac_info(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *mac = NULL;
u_int16_t vlan_id = 0;
if(lua_type(vm, 1) == LUA_TSTRING) {
mac = (char*)lua_tostring(vm, 1);
if(lua_type(vm, 2) == LUA_TNUMBER) {
vlan_id = (u_int16_t)lua_tonumber(vm, 2);
}
}
if((!ntop_interface)
|| (!mac)
|| (!ntop_interface->getMacInfo(vm, mac, vlan_id)))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_mac_manufacturer(lua_State* vm) {
const char *mac = NULL;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
mac = (char*)lua_tostring(vm, 1);
ntop->getMacManufacturer(mac, vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_site_categories(lua_State* vm) {
Flashstart *flash = ntop->get_flashstart();
if (!flash)
lua_pushnil(vm);
else
flash->lua(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get local hosts information of network interface.
* @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the local host information.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_local_hosts_info(lua_State* vm) {
return(ntop_get_interface_hosts(vm, location_local_only));
}
/* ****************************************** */
/**
* @brief Get remote hosts information of network interface.
* @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the remote host information.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_remote_hosts_info(lua_State* vm) {
return(ntop_get_interface_hosts(vm, location_remote_only));
}
/* ****************************************** */
/**
* @brief Get local hosts activity information.
* @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the local host activities.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null or host is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_host_activity(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
const char * host = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if (lua_type(vm, 1) == LUA_TSTRING)
host = lua_tostring(vm, 1);
if (ntop_interface == NULL || host == NULL)
return CONST_LUA_ERROR;
ntop_interface->getLocalHostActivity(vm, host);
return CONST_LUA_OK;
}
/* ****************************************** */
/**
* @brief Check if the specified path is a directory and it exists.
* @details True if if the specified path is a directory and it exists, false otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_OK
*/
static int ntop_is_dir(lua_State* vm) {
char *path;
struct stat buf;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
rc = ((stat(path, &buf) != 0) || (!S_ISDIR(buf.st_mode))) ? 0 : 1;
lua_pushboolean(vm, rc);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if the file is exists and is not empty
* @details Simple check for existance + non empty file
*
* @param vm The lua state.
* @return CONST_LUA_OK
*/
static int ntop_is_not_empty_file(lua_State* vm) {
char *path;
struct stat buf;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
rc = (stat(path, &buf) != 0) ? 0 : 1;
if(rc && (buf.st_size == 0)) rc = 0;
lua_pushboolean(vm, rc);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if the file or directory exists.
* @details Get the path of file/directory from to lua stack and push true into lua stack if it exists, false otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_OK
*/
static int ntop_get_file_dir_exists(lua_State* vm) {
char *path;
struct stat buf;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
rc = (stat(path, &buf) != 0) ? 0 : 1;
// ntop->getTrace()->traceEvent(TRACE_ERROR, "%s: %d", path, rc);
lua_pushboolean(vm, rc);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Return the epoch of the file last change
* @details This function return that time (epoch) of the last chnge on a file, or -1 if the file does not exist.
*
* @param vm The lua state.
* @return CONST_LUA_OK
*/
static int ntop_get_file_last_change(lua_State* vm) {
char *path;
struct stat buf;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
if(stat(path, &buf) == 0)
lua_pushnumber(vm, (lua_Number)buf.st_mtime);
else
lua_pushnumber(vm, -1); /* not found */
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if ntop has seen VLAN tagged packets on this interface.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_has_vlans(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface)
lua_pushboolean(vm, ntop_interface->hasSeenVlanTaggedPackets());
else
lua_pushboolean(vm, 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if ntop has loaded ASN information (via GeoIP)
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_has_geoip(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm, ntop->getGeolocation() ? 1 : 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if ntop is running on windows.
* @details Push into lua stack 1 if ntop is running on windows, 0 otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_is_windows(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm,
#ifdef WIN32
1
#else
0
#endif
);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_allocHostBlacklist(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->allocHostBlacklist();
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_swapHostBlacklist(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->swapHostBlacklist();
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_addToHostBlacklist(lua_State* vm) {
char *net;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
net = (char*)lua_tostring(vm, 1);
ntop->addToHostBlacklist(net);
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Wrapper for the libc call getservbyport()
* @details Wrapper for the libc call getservbyport()
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_getservbyport(lua_State* vm) {
int port;
char *proto;
struct servent *s = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
port = (int)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
proto = (char*)lua_tostring(vm, 2);
if((port > 0) && (proto != NULL))
s = getservbyport(htons(port), proto);
if(s && s->s_name)
lua_pushstring(vm, s->s_name);
else {
char buf[32];
snprintf(buf, sizeof(buf), "%d", port);
lua_pushstring(vm, buf);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Scan the input directory and return the list of files.
* @details Get the path from the lua stack and push into a new hashtable the files name existing in the directory.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_list_dir_files(lua_State* vm) {
char *path;
DIR *dirp;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
ntop->fixPath(path);
lua_newtable(vm);
if((dirp = opendir(path)) != NULL) {
struct dirent *dp;
while ((dp = readdir(dirp)) != NULL)
if((dp->d_name[0] != '\0')
&& (dp->d_name[0] != '.')) {
lua_push_str_table_entry(vm, dp->d_name, dp->d_name);
}
(void)closedir(dirp);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/* Adapted from http://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c */
static int remove_recursively(const char * path) {
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;
size_t len;
char *buf;
if (d) {
struct dirent *p;
r = 0;
while ((r==0) && (p=readdir(d))) {
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
continue;
len = path_len + strlen(p->d_name) + 2;
buf = (char *) malloc(len);
if (buf) {
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (stat(buf, &statbuf) == 0) {
if (S_ISDIR(statbuf.st_mode))
r = remove_recursively(buf);
else
r = unlink(buf);
}
free(buf);
}
}
closedir(d);
}
if (r == 0)
r = rmdir(path);
return r;
}
/**
* @brief Scan the input directory, removes it and its contets.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_remove_dir_recursively(lua_State* vm) {
char *path;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
ntop->fixPath(path);
remove_recursively(path);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the system time and push it into the lua stack.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_gettimemsec(lua_State* vm) {
struct timeval tp;
double ret;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
gettimeofday(&tp, NULL);
ret = (((double)tp.tv_usec) / (double)1000) + tp.tv_sec;
lua_pushnumber(vm, ret);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Lua-equivaled ot C inet_ntoa
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_inet_ntoa(lua_State* vm) {
u_int32_t ip;
struct in_addr in;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TSTRING)
ip = atol((char*)lua_tostring(vm, 1));
else if(lua_type(vm, 1) == LUA_TNUMBER)
ip = (u_int32_t)lua_tonumber(vm, 1);
else
return(CONST_LUA_ERROR);
in.s_addr = htonl(ip);
lua_pushstring(vm, inet_ntoa(in));
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_zmq_connect(lua_State* vm) {
char *endpoint, *topic;
void *context, *subscriber;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((endpoint = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((topic = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
context = zmq_ctx_new(), subscriber = zmq_socket(context, ZMQ_SUB);
if(zmq_connect(subscriber, endpoint) != 0) {
zmq_close(subscriber);
zmq_ctx_destroy(context);
return(CONST_LUA_PARAM_ERROR);
}
if(zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, topic, strlen(topic)) != 0) {
zmq_close(subscriber);
zmq_ctx_destroy(context);
return -1;
}
lua_pushlightuserdata(vm, context);
lua_setglobal(vm, "zmq_context");
lua_pushlightuserdata(vm, subscriber);
lua_setglobal(vm, "zmq_subscriber");
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Delete the specified member(field) from the redis hash stored at key.
* @details Get the key parameter from the lua stack and delete it from redis.
*
* @param vm The lua stack.
* @return CONST_LUA_OK.
*/
static int ntop_delete_redis_key(lua_State* vm) {
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->getRedis()->del(key);
return(CONST_LUA_OK);
}
/* ****************************************** */
/* ****************************************** */
/**
* @brief Add a member to the a redis set.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_add_set_member_redis(lua_State* vm) {
char *key, *value;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if (ntop->getRedis()->sadd(key, value) == 0)
return(CONST_LUA_OK);
else
return(CONST_LUA_ERROR);
}
/**
* @brief Removes a member from a redis set.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_del_set_member_redis(lua_State* vm) {
char *key, *value;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if (ntop->getRedis()->srem(key, value) == 0)
return(CONST_LUA_OK);
else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
/**
* @brief Get the members of a redis set.
* @details Get the set key form the lua stack and push the mambers name into lua stack.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_get_set_members_redis(lua_State* vm) {
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->getRedis()->smembers(vm, key);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Delete the specified member(field) from the redis hash stored at key.
* @details Get the member name and the hash key form the lua stack and remove the specified member.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_delete_hash_redis_key(lua_State* vm) {
char *key, *member;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->getRedis()->hashDel(key, member);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_zmq_disconnect(lua_State* vm) {
void *context, *subscriber;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, "zmq_context");
if((context = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL context");
return(CONST_LUA_ERROR);
}
lua_getglobal(vm, "zmq_subscriber");
if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber");
return(CONST_LUA_ERROR);
}
zmq_close(subscriber);
zmq_ctx_destroy(context);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_zmq_receive(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
void *subscriber;
int size;
struct zmq_msg_hdr h;
char *payload;
int payload_len;
zmq_pollitem_t item;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, "zmq_subscriber");
if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber");
return(CONST_LUA_ERROR);
}
item.socket = subscriber;
item.events = ZMQ_POLLIN;
do {
rc = zmq_poll(&item, 1, 1000);
if(rc < 0 || !ntop_interface->isRunning()) /* CHECK */
return(CONST_LUA_PARAM_ERROR);
} while (rc == 0);
size = zmq_recv(subscriber, &h, sizeof(h), 0);
if(size != sizeof(h) || h.version != ZMQ_MSG_VERSION) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unsupported publisher version [%d]", h.version);
return -1;
}
payload_len = h.size + 1;
if((payload = (char*)malloc(payload_len)) != NULL) {
size = zmq_recv(subscriber, payload, payload_len, 0);
payload[h.size] = '\0';
if(size > 0) {
enum json_tokener_error jerr = json_tokener_success;
json_object *o = json_tokener_parse_verbose(payload, &jerr);
if(o != NULL) {
struct json_object_iterator it = json_object_iter_begin(o);
struct json_object_iterator itEnd = json_object_iter_end(o);
while (!json_object_iter_equal(&it, &itEnd)) {
char *key = (char*)json_object_iter_peek_name(&it);
const char *value = json_object_get_string(json_object_iter_peek_value(&it));
ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%s]=[%s]", key, value);
json_object_iter_next(&it);
}
json_object_put(o);
} else
ntop->getTrace()->traceEvent(TRACE_WARNING, "JSON Parse error [%s]: %s",
json_tokener_error_desc(jerr),
payload);
lua_pushfstring(vm, "%s", payload);
ntop->getTrace()->traceEvent(TRACE_INFO, "[%u] %s", h.size, payload);
free(payload);
return(CONST_LUA_OK);
} else {
free(payload);
return(CONST_LUA_PARAM_ERROR);
}
} else
return(CONST_LUA_PARAM_ERROR);
}
/* ****************************************** */
static int ntop_get_local_networks(lua_State* vm) {
lua_newtable(vm);
ntop->getLocalNetworks(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_reload_preferences(lua_State* vm) {
lua_newtable(vm);
ntop->getPrefs()->reloadPrefsFromRedis();
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if the trace level of ntop is verbose.
* @details Push true into the lua stack if the trace level of ntop is set to MAX_TRACE_LEVEL, false otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_verbose_trace(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm, (ntop->getTrace()->get_trace_level() == MAX_TRACE_LEVEL) ? true : false);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_send_udp_data(lua_State* vm) {
int rc, port, sockfd = ntop->getUdpSock();
char *host, *data;
if(sockfd == -1)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
host = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
port = (u_int16_t)lua_tonumber(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
data = (char*)lua_tostring(vm, 3);
if(strchr(host, ':') != NULL) {
struct sockaddr_in6 server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin6_family = AF_INET6;
inet_pton(AF_INET6, host, &server_addr.sin6_addr);
server_addr.sin6_port = htons(port);
rc = sendto(sockfd, data, strlen(data),0,
(struct sockaddr *)&server_addr,
sizeof(server_addr));
} else {
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(host); /* FIX: add IPv6 support */
server_addr.sin_port = htons(port);
rc = sendto(sockfd, data, strlen(data),0,
(struct sockaddr *)&server_addr,
sizeof(server_addr));
}
if(rc == -1)
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_flows(lua_State* vm, LocationPolicy location) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char buf[64];
char *host_ip = NULL;
u_int16_t vlan_id = 0;
Host *host = NULL;
Paginator *p = NULL;
int numFlows = -1;
if(!ntop_interface)
return(CONST_LUA_ERROR);
if((p = new(std::nothrow) Paginator()) == NULL)
return(CONST_LUA_ERROR);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TSTRING) {
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
host = ntop_interface->getHost(host_ip, vlan_id);
}
if(lua_type(vm, 2) == LUA_TTABLE)
p->readOptions(vm, 2);
if(ntop_interface)
numFlows = ntop_interface->getFlows(vm, get_allowed_nets(vm), location, host, p);
if(p) delete p;
return numFlows < 0 ? CONST_LUA_ERROR : CONST_LUA_OK;
}
static int ntop_get_interface_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_all)); }
static int ntop_get_interface_local_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_local_only)); }
static int ntop_get_interface_remote_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_remote_only)); }
/* ****************************************** */
/**
* @brief Get nDPI stats for flows
* @details Compute nDPI flow statistics
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_get_interface_flows_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) ntop_interface->getFlowsStats(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get interface stats for local networks
* @details Returns traffic statistics per local network
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_get_interface_networks_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) ntop_interface->getNetworksStats(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the host information of network interface.
* @details Get the ntop interface global variable of lua, the host ip and optional the VLAN id form the lua stack and push a new hash table of hash tables containing the host information into lua stack.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null or the host is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_host_info(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface) || !ntop_interface->getHostInfo(vm, get_allowed_nets(vm), host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
#ifdef NOTUSED
static int ntop_get_grouped_interface_host(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *country_s = NULL, *os_s = NULL;
u_int16_t vlan_n, *vlan_ptr = NULL;
u_int32_t as_n, *as_ptr = NULL;
int16_t network_n, *network_ptr = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TNUMBER) vlan_n = (u_int16_t)lua_tonumber(vm, 1), vlan_ptr = &vlan_n;
if(lua_type(vm, 2) == LUA_TNUMBER) as_n = (u_int32_t)lua_tonumber(vm, 2), as_ptr = &as_n;
if(lua_type(vm, 3) == LUA_TNUMBER) network_n = (int16_t)lua_tonumber(vm, 3), network_ptr = &network_n;
if(lua_type(vm, 4) == LUA_TSTRING) country_s = (char*)lua_tostring(vm, 4);
if(lua_type(vm, 5) == LUA_TSTRING) os_s = (char*)lua_tostring(vm, 5);
if(!ntop_interface || ntop_interface->getActiveHostsGroup(vm, get_allowed_nets(vm), false, false, country_s, vlan_ptr, os_s, as_ptr,
network_ptr, (char*)"column_ip", (char*)"country", CONST_MAX_NUM_HITS, 0 /* toSkip */, true /* a2zSortOrder */) < 0)
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
#endif
/* ****************************************** */
static int ntop_getflowdevices(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
else {
ntop_interface->getFlowDevices(vm);
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_getflowdeviceinfo(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *device_ip;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
device_ip = (char*)lua_tostring(vm, 1);
if(!ntop_interface)
return(CONST_LUA_ERROR);
else {
in_addr_t addr = inet_addr(device_ip);
ntop_interface->getFlowDeviceInfo(vm, ntohl(addr));
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_interface_load_host_alert_prefs(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface) || !ntop_interface->loadHostAlertPrefs(vm, get_allowed_nets(vm), host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_host_reset_periodic_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->resetPeriodicStats();
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_host_trigger_alerts(lua_State* vm, bool trigger) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER)
vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
if(trigger)
h->enableAlerts();
else
h->disableAlerts();
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_host_enable_alerts(lua_State* vm) {
return ntop_interface_host_trigger_alerts(vm, true);
}
/* ****************************************** */
static int ntop_interface_host_disable_alerts(lua_State* vm) {
return ntop_interface_host_trigger_alerts(vm, false);
}
/* ****************************************** */
static int ntop_interface_refresh_num_alerts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
AlertsManager *am;
Host *h;
char *host_ip;
u_int16_t vlan_id = 0;
u_int32_t num_alerts;
char buf[128];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if((!ntop_interface))
return(CONST_LUA_ERROR);
if(lua_type(vm, 1) == LUA_TSTRING) {
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((h = ntop_interface->getHost(host_ip, vlan_id))) {
if(lua_type(vm, 3) == LUA_TNUMBER) {
num_alerts = (u_int32_t)lua_tonumber(vm, 3);
h->setNumAlerts(num_alerts);
} else {
h->getNumAlerts(true /* From AlertsManager re-reads the values */);
}
}
} else {
if((am = ntop_interface->getAlertsManager()) == NULL)
return(CONST_LUA_ERROR);
am->refreshCachedNumAlerts();
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_correalate_host_activity(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface) || !ntop_interface->correlateHostActivity(vm, get_allowed_nets(vm), host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_similar_host_activity(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface) || !ntop_interface->similarHostActivity(vm, get_allowed_nets(vm), host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_host_activitymap(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
GenericHost *h;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
h = ntop_interface->getHost(host_ip, vlan_id);
if(h == NULL)
return(CONST_LUA_ERROR);
else {
if(h->match(get_allowed_nets(vm))) {
char *json = h->getJsonActivityMap();
lua_pushfstring(vm, "%s", json);
free(json);
}
return(CONST_LUA_OK);
}
}
/* ****************************************** */
/**
* @brief Restore the host of network interface.
* @details Get the ntop interface global variable of lua and the IP address of host form the lua stack and restore the host into hash host of network interface.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null or if is impossible to restore the host, CONST_LUA_OK otherwise.
*/
static int ntop_restore_interface_host(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
bool skip_privileges_check = false;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* make sure skip privileges check cannot be set from the web interface */
if(lua_type(vm, 2) == LUA_TBOOLEAN) skip_privileges_check = lua_toboolean(vm, 2);
if(!skip_privileges_check && !Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if((!ntop_interface) || !ntop_interface->restoreHost(host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_flow_key(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
Host *cli, *srv;
char *cli_name = NULL; u_int16_t cli_vlan = 0; u_int16_t cli_port = 0;
char *srv_name = NULL; u_int16_t srv_vlan = 0; u_int16_t srv_port = 0;
u_int16_t protocol;
char cli_buf[256], srv_buf[256];
if(!ntop_interface)
return(CONST_LUA_ERROR);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING) /* cli_host@cli_vlan */
|| ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER) /* cli port */
|| ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING) /* srv_host@srv_vlan */
|| ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER) /* srv port */
|| ntop_lua_check(vm, __FUNCTION__, 5, LUA_TNUMBER) /* protocol */
) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &cli_name, &cli_vlan, cli_buf, sizeof(cli_buf));
cli_port = htons((u_int16_t)lua_tonumber(vm, 2));
get_host_vlan_info((char*)lua_tostring(vm, 3), &srv_name, &srv_vlan, srv_buf, sizeof(srv_buf));
srv_port = htons((u_int16_t)lua_tonumber(vm, 4));
protocol = (u_int16_t)lua_tonumber(vm, 5);
if(cli_vlan != srv_vlan) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "Client and Server vlans don't match.");
return(CONST_LUA_ERROR);
}
if(cli_name == NULL || srv_name == NULL
||(cli = ntop_interface->getHost(cli_name, cli_vlan)) == NULL
||(srv = ntop_interface->getHost(srv_name, srv_vlan)) == NULL) {
lua_pushnil(vm);
} else {
lua_pushnumber(vm, Flow::key(cli, cli_port, srv, srv_port, cli_vlan, protocol));
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_flow_by_key(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t key;
Flow *f;
AddressTree *ptree = get_allowed_nets(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
key = (u_int32_t)lua_tonumber(vm, 1);
if(!ntop_interface) return(false);
f = ntop_interface->findFlowByKey(key, ptree);
if(f == NULL)
return(CONST_LUA_ERROR);
else {
f->lua(vm, ptree, details_high, false);
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_drop_flow_traffic(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t key;
Flow *f;
AddressTree *ptree = get_allowed_nets(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
key = (u_int32_t)lua_tonumber(vm, 1);
if(!ntop_interface) return(false);
f = ntop_interface->findFlowByKey(key, ptree);
if(f == NULL)
return(CONST_LUA_ERROR);
else {
f->setDropVerdict();
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_dump_flow_traffic(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t key, what;
Flow *f;
AddressTree *ptree = get_allowed_nets(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
key = (u_int32_t)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
what = (u_int32_t)lua_tonumber(vm, 2);
if(!ntop_interface) return(false);
f = ntop_interface->findFlowByKey(key, ptree);
if(f == NULL)
return(CONST_LUA_ERROR);
else {
f->setDumpFlowTraffic(what ? true : false);
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_dump_local_hosts_2_redis(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
ntop_interface->dumpLocalHosts2redis(true /* must disable purge as we are called from lua */);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_user_flows(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
key = (char*)lua_tostring(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findUserFlows(vm, key);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_pid_flows(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t pid;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
pid = (u_int32_t)lua_tonumber(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findPidFlows(vm, pid);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_father_pid_flows(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t father_pid;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
father_pid = (u_int32_t)lua_tonumber(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findFatherPidFlows(vm, father_pid);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_proc_name_flows(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *proc_name;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
proc_name = (char*)lua_tostring(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findProcNameFlows(vm, proc_name);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_list_http_hosts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
if(lua_type(vm, 1) != LUA_TSTRING) /* Optional */
key = NULL;
else
key = (char*)lua_tostring(vm, 1);
ntop_interface->listHTTPHosts(vm, key);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_host(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
key = (char*)lua_tostring(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findHostsByName(vm, get_allowed_nets(vm), key);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_update_host_traffic_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->updateHostTrafficPolicy(host_ip);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_update_host_alert_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->readAlertPrefs();
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_set_second_traffic(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->updateSecondTraffic(time(NULL));
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_set_host_dump_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
bool dump_traffic_to_disk;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR);
dump_traffic_to_disk = lua_toboolean(vm, 1) ? true : false;
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->setDumpTrafficPolicy(dump_traffic_to_disk);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_host_hit_rate(lua_State* vm) {
#ifdef NOTUSED
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
u_int32_t peer_key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
peer_key = (u_int32_t)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->getPeerBytes(vm, peer_key);
return(CONST_LUA_OK);
#else
return(CONST_LUA_ERROR); // not supported
#endif
}
/* ****************************************** */
static int ntop_set_host_quota(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
u_int32_t quota;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
quota = (u_int32_t)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->setQuota(quota);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_tap_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool dump_traffic_to_tap;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
dump_traffic_to_tap = ntop_interface->getDumpTrafficTapPolicy();
lua_pushboolean(vm, dump_traffic_to_tap ? 1 : 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_tap_name(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
lua_pushstring(vm, ntop_interface->getDumpTrafficTapName());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_disk_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool dump_traffic_to_disk;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
dump_traffic_to_disk = ntop_interface->getDumpTrafficDiskPolicy();
lua_pushboolean(vm, dump_traffic_to_disk ? 1 : 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_max_pkts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int max_pkts;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
max_pkts = ntop_interface->getDumpTrafficMaxPktsPerFile();
lua_pushnumber(vm, max_pkts);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_max_sec(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int max_sec;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
max_sec = ntop_interface->getDumpTrafficMaxSecPerFile();
lua_pushnumber(vm, max_sec);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_max_files(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int max_files;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
max_files = ntop_interface->getDumpTrafficMaxFiles();
lua_pushnumber(vm, max_files);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_pkts_dumped_file(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int num_pkts;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
PacketDumper *dumper = ntop_interface->getPacketDumper();
if(!dumper)
return(CONST_LUA_ERROR);
num_pkts = dumper->get_num_dumped_packets();
lua_pushnumber(vm, num_pkts);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_pkts_dumped_tap(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int num_pkts;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
PacketDumperTuntap *dumper = ntop_interface->getPacketDumperTap();
if(!dumper)
return(CONST_LUA_ERROR);
num_pkts = dumper->get_num_dumped_packets();
lua_pushnumber(vm, num_pkts);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_endpoint(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int8_t id;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) != LUA_TNUMBER) /* Optional */
id = 0;
else
id = (u_int8_t)lua_tonumber(vm, 1);
if(ntop_interface) {
char *endpoint = ntop_interface->getEndpoint(id); /* CHECK */
lua_pushfstring(vm, "%s", endpoint ? endpoint : "");
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_is_packet_interface(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
lua_pushboolean(vm, ntop_interface->isPacketInterface());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_is_bridge_interface(lua_State* vm) {
int ifid;
NetworkInterface *iface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if((lua_type(vm, 1) == LUA_TNUMBER)) {
ifid = lua_tointeger(vm, 1);
if(ifid < 0 || !(iface = ntop->getNetworkInterface(ifid)))
return (CONST_LUA_ERROR);
}
lua_pushboolean(vm, iface->is_bridge_interface());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_is_pcap_dump_interface(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
const char *interface_type;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface
|| ((interface_type = ntop_interface->get_type()) == NULL))
return(CONST_LUA_ERROR);
lua_pushboolean(vm, strcmp(interface_type, CONST_INTERFACE_TYPE_PCAP_DUMP) == 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_is_running(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
return(ntop_interface->isRunning());
}
/* ****************************************** */
static int ntop_interface_is_idle(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
return(ntop_interface->idle());
}
/* ****************************************** */
static int ntop_interface_set_idle(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool state;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR);
state = lua_toboolean(vm, 1) ? true : false;
ntop_interface->setIdleState(state);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_name2id(lua_State* vm) {
char *if_name;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TNIL)
if_name = NULL;
else {
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if_name = (char*)lua_tostring(vm, 1);
}
lua_pushinteger(vm, ntop->getInterfaceIdByName(if_name));
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_ndpi_protocols(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ndpi_protocol_category_t category_filter;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if((lua_type(vm, 1) == LUA_TNUMBER)) {
category_filter = (ndpi_protocol_category_t)lua_tointeger(vm, 1);
if(category_filter >= NDPI_PROTOCOL_NUM_CATEGORIES)
return (CONST_LUA_ERROR);
ntop_interface->getnDPIProtocols(vm, category_filter);
} else
ntop_interface->getnDPIProtocols(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_ndpi_categories(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_newtable(vm);
for (int i=0; i < NDPI_PROTOCOL_NUM_CATEGORIES; i++) {
char buf[8];
snprintf(buf, sizeof(buf), "%d", i);
lua_push_str_table_entry(vm, ndpi_category_str((ndpi_protocol_category_t)i), buf);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_load_dump_prefs(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop_interface->loadDumpPrefs();
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_load_scaling_factor_prefs(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop_interface->loadScalingFactorPrefs();
return(CONST_LUA_OK);
}
/* ****************************************** */
/*
Code partially taken from third-party/rrdtool-1.4.7/bindings/lua/rrdlua.c
and made reentrant
*/
static void reset_rrd_state(void) {
optind = 0;
opterr = 0;
rrd_clear_error();
}
/* ****************************************** */
static const char **make_argv(lua_State * vm, u_int offset) {
const char **argv;
int i;
int argc = lua_gettop(vm) - offset;
if(!(argv = (const char**)calloc(argc, sizeof (char *))))
/* raise an error and never return */
luaL_error(vm, "Can't allocate memory for arguments array");
/* fprintf(stderr, "%s\n", argv[0]); */
for(i=0; i<argc; i++) {
u_int idx = i + offset;
/* accepts string or number */
if(lua_isstring(vm, idx) || lua_isnumber(vm, idx)) {
if(!(argv[i] = (char*)lua_tostring (vm, idx))) {
/* raise an error and never return */
luaL_error(vm, "Error duplicating string area for arg #%d", i);
}
} else {
/* raise an error and never return */
luaL_error(vm, "Invalid arg #%d: args must be strings or numbers", i);
}
// ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%d] %s", i, argv[i]);
}
return(argv);
}
/* ****************************************** */
static int ntop_rrd_create(lua_State* vm) {
const char *filename;
unsigned long pdp_step;
const char **argv;
int argc, status, offset = 3;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
pdp_step = (unsigned long)lua_tonumber(vm, 2);
ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename);
argc = lua_gettop(vm) - offset;
argv = make_argv(vm, offset);
reset_rrd_state();
status = rrd_create_r(filename, pdp_step, time(NULL)-86400 /* 1 day */, argc, argv);
free(argv);
if(status != 0) {
char *err = rrd_get_error();
if(err != NULL) {
luaL_error(vm, err);
return(CONST_LUA_ERROR);
}
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_rrd_update(lua_State* vm) {
const char *filename, *update_arg;
int status;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((update_arg = (const char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s(%s) %s", __FUNCTION__, filename, update_arg);
reset_rrd_state();
status = rrd_update_r(filename, NULL, 1, &update_arg);
if(status != 0) {
char *err = rrd_get_error();
if(err != NULL) {
luaL_error(vm, err);
return(CONST_LUA_ERROR);
}
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_rrd_lastupdate(lua_State* vm) {
const char *filename;
time_t last_update;
char **ds_names;
char **last_ds;
unsigned long ds_count, i;
int status;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
status = rrd_lastupdate_r(filename, &last_update, &ds_count, &ds_names, &last_ds);
if(status != 0) {
return(CONST_LUA_ERROR);
} else {
for(i = 0; i < ds_count; i++)
free(last_ds[i]), free(ds_names[i]);
free(last_ds), free(ds_names);
lua_pushnumber(vm, last_update);
lua_pushnumber(vm, ds_count);
return(2 /* 2 values returned */);
}
}
/* ****************************************** */
/* positional 1:4 parameters for ntop_rrd_fetch */
static int __ntop_rrd_args (lua_State* vm, char **filename, char **cf, time_t *start, time_t *end) {
char *start_s, *end_s, *err;
rrd_time_value_t start_tv, end_tv;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((*filename = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((*cf = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((lua_type(vm, 3) == LUA_TNUMBER) && (lua_type(vm, 4) == LUA_TNUMBER))
*start = (time_t)lua_tonumber(vm, 3), *end = (time_t)lua_tonumber(vm, 4);
else {
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((start_s = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((err = rrd_parsetime(start_s, &start_tv)) != NULL) {
luaL_error(vm, err);
return(CONST_LUA_PARAM_ERROR);
}
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((end_s = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((err = rrd_parsetime(end_s, &end_tv)) != NULL) {
luaL_error(vm, err);
return(CONST_LUA_PARAM_ERROR);
}
if(rrd_proc_start_end(&start_tv, &end_tv, start, end) == -1)
return(CONST_LUA_PARAM_ERROR);
}
return(CONST_LUA_OK);
}
static int __ntop_rrd_status(lua_State* vm, int status, char *filename, char *cf) {
char * err;
if(status != 0) {
err = rrd_get_error();
if(err != NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR,
"Error '%s' while calling rrd_fetch_r(%s, %s): is the RRD corrupted perhaps?",
err, filename, cf);
lua_pushnil(vm);
lua_pushnil(vm);
lua_pushnil(vm);
lua_pushnil(vm);
return(CONST_LUA_ERROR);
}
}
return(CONST_LUA_OK);
}
/* Fetches data from RRD by rows */
static int ntop_rrd_fetch(lua_State* vm) {
unsigned long i, j, step = 0, ds_cnt = 0;
rrd_value_t *data, *p;
char **names;
char *filename, *cf;
time_t t, start, end;
int status;
if ((status = __ntop_rrd_args(vm, &filename, &cf, &start, &end)) != CONST_LUA_OK) return status;
ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename);
reset_rrd_state();
if ((status = __ntop_rrd_status(vm, rrd_fetch_r(filename, cf, &start, &end, &step, &ds_cnt, &names, &data), filename, cf)) != CONST_LUA_OK) return status;
lua_pushnumber(vm, (lua_Number) start);
lua_pushnumber(vm, (lua_Number) step);
/* fprintf(stderr, "%lu, %lu, %lu, %lu\n", start, end, step, num_points); */
/* create the ds names array */
lua_newtable(vm);
for(i=0; i<ds_cnt; i++) {
lua_pushstring(vm, names[i]);
lua_rawseti(vm, -2, i+1);
rrd_freemem(names[i]);
}
rrd_freemem(names);
/* create the data points array */
lua_newtable(vm);
p = data;
for(t=start+1, i=0; t<end; t+=step, i++) {
lua_newtable(vm);
for(j=0; j<ds_cnt; j++) {
rrd_value_t value = *p++;
if(value != DNAN /* Skip NaN */) {
lua_pushnumber(vm, (lua_Number)value);
lua_rawseti(vm, -2, j+1);
// ntop->getTrace()->traceEvent(TRACE_NORMAL, "%u / %.f", t, value);
}
}
lua_rawseti(vm, -2, i+1);
}
rrd_freemem(data);
/* return the end as the last value */
lua_pushnumber(vm, (lua_Number) end);
/* number of return values: start, step, names, data, end */
return(5);
}
/* ****************************************** */
/*
* Similar to ntop_rrd_fetch, but data series oriented (reads RRD by columns)
*
* Positional parameters:
* filename: RRD file path
* cf: RRD cf
* start: the start time you wish to query
* end: the end time you wish to query
*
* Positional return values:
* start: the time of the first data in the series
* step: the fetched data step
* data: a table, where each key is an RRD name, and the value is its series data
* end: the time of the last data in each series
* npoints: the number of points in each series
*/
static int ntop_rrd_fetch_columns(lua_State* vm) {
char *filename, *cf;
time_t start, end;
int status;
unsigned int npoints = 0, i, j;
char **names;
unsigned long step = 0, ds_cnt = 0;
rrd_value_t *data, *p;
if ((status = __ntop_rrd_args(vm, &filename, &cf, &start, &end)) != CONST_LUA_OK) return status;
ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename);
reset_rrd_state();
if ((status = __ntop_rrd_status(vm, rrd_fetch_r(filename, cf, &start, &end, &step, &ds_cnt, &names, &data), filename, cf)) != CONST_LUA_OK) return status;
npoints = (end - start) / step;
lua_pushnumber(vm, (lua_Number) start);
lua_pushnumber(vm, (lua_Number) step);
/* create the data series table */
lua_createtable(vm, 0, ds_cnt);
for(i=0; i<ds_cnt; i++) {
/* a single serie table, preallocated */
lua_createtable(vm, npoints, 0);
p = data + i;
for(j=0; j<npoints; j++) {
rrd_value_t value = *p;
/* we are accessing data table by columns */
p = p + ds_cnt;
lua_pushnumber(vm, (lua_Number)value);
lua_rawseti(vm, -2, j+1);
}
/* add the single serie to the series table */
lua_setfield(vm, -2, names[i]);
rrd_freemem(names[i]);
}
rrd_freemem(names);
rrd_freemem(data);
/* end and npoints as last values */
lua_pushnumber(vm, (lua_Number) end);
lua_pushnumber(vm, (lua_Number) npoints);
/* number of return values */
return(5);
}
/* ****************************************** */
static int ntop_http_redirect(lua_State* vm) {
char *url, str[512];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((url = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
snprintf(str, sizeof(str), "HTTP/1.1 302 Found\r\n"
"Location: %s\r\n\r\n"
"<html>\n"
"<head>\n"
"<title>Moved</title>\n"
"</head>\n"
"<body>\n"
"<h1>Moved</h1>\n"
"<p>This page has moved to <a href=\"%s\">%s</a>.</p>\n"
"</body>\n"
"</html>\n", url, url, url);
lua_pushstring(vm, str);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_http_get(lua_State* vm) {
char *url, *username = NULL, *pwd = NULL;
int timeout = 30;
bool return_content = true;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((url = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 2) == LUA_TSTRING) {
username = (char*)lua_tostring(vm, 2);
if(lua_type(vm, 3) == LUA_TSTRING) {
pwd = (char*)lua_tostring(vm, 3);
if(lua_type(vm, 4) == LUA_TNUMBER) {
timeout = lua_tointeger(vm, 4);
if(timeout < 1) timeout = 1;
/*
This optional parameter specifies if the result of HTTP GET has to be returned
to LUA or not. Usually the content has to be returned, but in some causes
it just matters to time (for instance when use for testing HTTP services)
*/
if(lua_type(vm, 4) == LUA_TBOOLEAN) {
return_content = lua_toboolean(vm, 5) ? true : false;
}
}
}
}
if(Utils::httpGet(vm, url, username, pwd, timeout, return_content))
return(CONST_LUA_OK);
else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_http_get_prefix(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushstring(vm, ntop->getPrefs()->get_http_prefix());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_prefs(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->getPrefs()->lua(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_nologin_username(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushstring(vm, NTOP_NOLOGIN_USER);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_users(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->getUsers(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_user_group(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->getUserGroup(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_allowed_networks(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->getAllowedNetworks(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_reset_user_password(lua_State* vm) {
char *who, *username, *old_password, *new_password;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
/* Username who requested the password change */
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((who = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((old_password = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((new_password = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((!Utils::isUserAdministrator(vm)) && (strcmp(who, username)))
return(CONST_LUA_ERROR);
return(ntop->resetUserPassword(username, old_password, new_password));
}
/* ****************************************** */
static int ntop_change_user_role(lua_State* vm) {
char *username, *user_role;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((user_role = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->changeUserRole(username, user_role);
}
/* ****************************************** */
static int ntop_change_allowed_nets(lua_State* vm) {
char *username, *allowed_nets;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((allowed_nets = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->changeAllowedNets(username, allowed_nets);
}
/* ****************************************** */
static int ntop_change_allowed_ifname(lua_State* vm) {
char *username, *allowed_ifname;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((allowed_ifname = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->changeAllowedIfname(username, allowed_ifname);
}
/* ****************************************** */
static int ntop_change_user_host_pool(lua_State* vm) {
char *username, *host_pool_id;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((host_pool_id = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->changeUserHostPool(username, host_pool_id);
}
/* ****************************************** */
static int ntop_post_http_json_data(lua_State* vm) {
char *username, *password, *url, *json;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((password = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((url = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((json = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(Utils::postHTTPJsonData(username, password, url, json))
return(CONST_LUA_OK);
else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_add_user(lua_State* vm) {
char *username, *full_name, *password, *host_role, *allowed_networks, *allowed_interface, *host_pool_id = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((full_name = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((password = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((host_role = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((allowed_networks = (char*)lua_tostring(vm, 5)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 6, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((allowed_interface = (char*)lua_tostring(vm, 6)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 7) == LUA_TSTRING)
if((host_pool_id = (char*)lua_tostring(vm, 7)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->addUser(username, full_name, password, host_role,
allowed_networks, allowed_interface, host_pool_id);
}
/* ****************************************** */
static int ntop_add_user_lifetime(lua_State* vm) {
char *username;
int32_t num_secs;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_PARAM_ERROR);
num_secs = (int32_t)lua_tonumber(vm, 2);
if(num_secs > 0)
return ntop->addUserLifetime(username, num_secs) ? CONST_LUA_OK : CONST_LUA_ERROR;
return CONST_LUA_OK; /* Negative or zero lifetimes means unlimited */
}
/* ****************************************** */
static int ntop_clear_user_lifetime(lua_State* vm) {
char *username;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->clearUserLifetime(username) ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_delete_user(lua_State* vm) {
char *username;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->deleteUser(username);
}
/* ****************************************** */
static int ntop_resolve_address(lua_State* vm) {
char *numIP, symIP[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((numIP = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->resolveHostName(numIP, symIP, sizeof(symIP));
lua_pushstring(vm, symIP);
return(CONST_LUA_OK);
}
/* ****************************************** */
void lua_push_str_table_entry(lua_State *L, const char *key, char *value) {
if(L) {
lua_pushstring(L, key);
lua_pushstring(L, value);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_nil_table_entry(lua_State *L, const char *key) {
if(L) {
lua_pushstring(L, key);
lua_pushnil(L);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_bool_table_entry(lua_State *L, const char *key, bool value) {
if(L) {
lua_pushstring(L, key);
lua_pushboolean(L, value ? 1 : 0);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_int_table_entry(lua_State *L, const char *key, u_int64_t value) {
if(L) {
lua_pushstring(L, key);
/* using LUA_NUMBER (double: 64 bit) in place of LUA_INTEGER (ptrdiff_t: 32 or 64 bit
* according to the platform, as defined in luaconf.h) to handle big counters */
lua_pushnumber(L, (lua_Number)value);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_int32_table_entry(lua_State *L, const char *key, int32_t value) {
if(L) {
lua_pushstring(L, key);
lua_pushnumber(L, (lua_Number)value);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_float_table_entry(lua_State *L, const char *key, float value) {
if(L) {
lua_pushstring(L, key);
lua_pushnumber(L, value);
lua_settable(L, -3);
}
}
/* ****************************************** */
static int ntop_get_interface_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
/*
ntop_interface->getAlertsManager()->engageAlert(alert_entity_host, "127.0.0.1",
"min_bytes",
alert_threshold_exceeded,
alert_level_warning,
"miao");
ntop_interface->getAlertsManager()->releaseAlert(alert_entity_host, "127.0.0.1",
"min_bytes",
alert_threshold_exceeded,
alert_level_warning,
"miao");
*/
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) ntop_interface->lua(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_reset_counters(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool only_drops = true;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TBOOLEAN)
only_drops = lua_toboolean(vm, 1) ? true : false;
if(!ntop_interface)
return(CONST_LUA_ERROR);
ntop_interface->checkPointCounters(only_drops);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_is_pro(lua_State *vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm, ntop->getPrefs()->is_pro_edition());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_is_enterprise(lua_State *vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm, ntop->getPrefs()->is_enterprise_edition());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_reload_host_pools(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) {
ntop_interface->getHostPools()->reloadPools();
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
#ifdef NTOPNG_PRO
static int ntop_purge_expired_host_pools_members(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface && ntop_interface->getHostPools()) {
ntop_interface->getHostPools()->purgeExpiredVolatileMembers();
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
static int ntop_remove_volatile_member_from_pool(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_or_mac;
u_int16_t pool_id;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((host_or_mac = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_PARAM_ERROR);
pool_id = (u_int16_t)lua_tonumber(vm, 2);
if(ntop_interface && ntop_interface->getHostPools()) {
ntop_interface->getHostPools()->removeVolatileMemberFromPool(host_or_mac, pool_id);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
#endif
/* ****************************************** */
static int ntop_reload_l7_rules(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_PARAM_ERROR);
if(ntop_interface) {
#ifdef NTOPNG_PRO
u_int16_t host_pool_id = (u_int16_t)lua_tonumber(vm, 1);
#ifdef SHAPER_DEBUG
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s(%i)", __FUNCTION__, host_pool_id);
#endif
ntop_interface->refreshL7Rules();
ntop_interface->updateHostsL7Policy(host_pool_id);
ntop_interface->updateFlowsL7Policy();
#endif
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_reload_shapers(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) {
#ifdef NTOPNG_PRO
ntop_interface->refreshShapers();
#endif
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_interface_exec_sql_query(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool limit_rows = true; // honour the limit by default
bool wait_for_db_created = true;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
else {
char *sql;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((sql = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 2) == LUA_TBOOLEAN) {
limit_rows = lua_toboolean(vm, 2) ? true : false;
}
if(lua_type(vm, 3) == LUA_TBOOLEAN) {
wait_for_db_created = lua_toboolean(vm, 3) ? true : false;
}
if(ntop_interface->exec_sql_query(vm, sql, limit_rows, wait_for_db_created) < 0)
lua_pushnil(vm);
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_get_dirs(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_newtable(vm);
lua_push_str_table_entry(vm, "installdir", ntop->get_install_dir());
lua_push_str_table_entry(vm, "workingdir", ntop->get_working_dir());
lua_push_str_table_entry(vm, "scriptdir", ntop->getPrefs()->get_scripts_dir());
lua_push_str_table_entry(vm, "httpdocsdir", ntop->getPrefs()->get_docs_dir());
lua_push_str_table_entry(vm, "callbacksdir", ntop->getPrefs()->get_callbacks_dir());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_uptime(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushinteger(vm, ntop->getGlobals()->getUptime());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_check_license(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
#ifdef NTOPNG_PRO
ntop->getPro()->check_license();
#endif
lua_pushinteger(vm,1);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_info(lua_State* vm) {
char rsp[256];
int major, minor, patch;
bool verbose = true;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TBOOLEAN)
verbose = lua_toboolean(vm, 1) ? true : false;
lua_newtable(vm);
lua_push_str_table_entry(vm, "product", (char*)"ntopng");
lua_push_str_table_entry(vm, "copyright", (char*)"© 1998-17 - ntop.org");
lua_push_str_table_entry(vm, "authors", (char*)"The ntop.org team");
lua_push_str_table_entry(vm, "license", (char*)"GNU GPLv3");
lua_push_str_table_entry(vm, "version", (char*)PACKAGE_VERSION);
lua_push_str_table_entry(vm, "git", (char*)NTOPNG_GIT_RELEASE);
snprintf(rsp, sizeof(rsp), "%s [%s][%s]",
PACKAGE_OSNAME, PACKAGE_MACHINE, PACKAGE_OS);
lua_push_str_table_entry(vm, "platform", rsp);
lua_push_str_table_entry(vm, "OS",
#ifdef WIN32
(char*)"Windows"
#else
(char*)PACKAGE_OS
#endif
);
lua_push_int_table_entry(vm, "bits", (sizeof(void*) == 4) ? 32 : 64);
lua_push_int_table_entry(vm, "uptime", ntop->getGlobals()->getUptime());
lua_push_str_table_entry(vm, "command_line", ntop->getPrefs()->get_command_line());
if(verbose) {
lua_push_str_table_entry(vm, "version.rrd", rrd_strversion());
lua_push_str_table_entry(vm, "version.redis", ntop->getRedis()->getVersion(rsp, sizeof(rsp)));
lua_push_str_table_entry(vm, "version.httpd", (char*)mg_version());
lua_push_str_table_entry(vm, "version.git", (char*)NTOPNG_GIT_RELEASE);
lua_push_str_table_entry(vm, "version.luajit", (char*)LUAJIT_VERSION);
#ifdef HAVE_GEOIP
lua_push_str_table_entry(vm, "version.geoip", (char*)GeoIP_lib_version());
#endif
lua_push_str_table_entry(vm, "version.ndpi", ndpi_revision());
lua_push_bool_table_entry(vm, "version.enterprise_edition", ntop->getPrefs()->is_enterprise_edition());
lua_push_bool_table_entry(vm, "version.embedded_edition", ntop->getPrefs()->is_embedded_edition());
lua_push_bool_table_entry(vm, "pro.release", ntop->getPrefs()->is_pro_edition());
lua_push_int_table_entry(vm, "pro.demo_ends_at", ntop->getPrefs()->pro_edition_demo_ends_at());
#ifdef NTOPNG_PRO
lua_push_str_table_entry(vm, "pro.license", ntop->getPro()->get_license());
lua_push_bool_table_entry(vm, "pro.use_redis_license", ntop->getPro()->use_redis_license());
lua_push_str_table_entry(vm, "pro.systemid", ntop->getPro()->get_system_id());
#endif
#if 0
ntop->getRedis()->get((char*)CONST_STR_NTOPNG_LICENSE, rsp, sizeof(rsp));
lua_push_str_table_entry(vm, "ntopng.license", rsp);
#endif
zmq_version(&major, &minor, &patch);
snprintf(rsp, sizeof(rsp), "%d.%d.%d", major, minor, patch);
lua_push_str_table_entry(vm, "version.zmq", rsp);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_resolved_address(lua_State* vm) {
char *key, *tmp,rsp[256],value[64];
Redis *redis = ntop->getRedis();
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &key, &vlan_id, buf, sizeof(buf));
if(key == NULL)
return(CONST_LUA_ERROR);
if(redis->getAddress(key, rsp, sizeof(rsp), true) == 0)
tmp = rsp;
else
tmp = key;
if(vlan_id != 0)
snprintf(value, sizeof(value), "%s@%u", tmp, vlan_id);
else
snprintf(value, sizeof(value), "%s", tmp);
#if 0
if(!strcmp(value, key)) {
char rsp[64];
if((ntop->getRedis()->hashGet((char*)HOST_LABEL_NAMES, key, rsp, sizeof(rsp)) == 0)
&& (rsp[0] !='\0'))
lua_pushfstring(vm, "%s", rsp);
else
lua_pushfstring(vm, "%s", value);
} else
lua_pushfstring(vm, "%s", value);
#else
lua_pushfstring(vm, "%s", value);
#endif
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_snmp_get_fctn(lua_State* vm, int operation) {
char *agent_host, *oid, *community;
u_int agent_port = 161, timeout = 5, request_id = (u_int)time(NULL);
int sock, i = 0, rc = CONST_LUA_OK;
SNMPMessage *message;
int len;
unsigned char *buf;
bool debug = false;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
agent_host = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
community = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
oid = (char*)lua_tostring(vm, 3);
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sock < 0) return(CONST_LUA_ERROR);
message = snmp_create_message();
snmp_set_version(message, 0);
snmp_set_community(message, community);
snmp_set_pdu_type(message, operation);
snmp_set_request_id(message, request_id);
snmp_set_error(message, 0);
snmp_set_error_index(message, 0);
snmp_add_varbind_null(message, oid);
/* Add additional OIDs */
i = 4;
while(lua_type(vm, i) == LUA_TSTRING) {
snmp_add_varbind_null(message, (char*)lua_tostring(vm, i));
i++;
}
len = snmp_message_length(message);
buf = (unsigned char*)malloc(len);
snmp_render_message(message, buf);
snmp_destroy_message(message);
send_udp_datagram(buf, len, sock, agent_host, agent_port);
free(buf);
if(debug)
ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP %s %s@%s %s",
(operation == SNMP_GET_REQUEST_TYPE) ? "Get" : "GetNext",
agent_host, community, oid);
if(input_timeout(sock, timeout) == 0) {
/* Timeout */
if(debug)
ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP Timeout %s@%s %s", agent_host, community, oid);
rc = CONST_LUA_ERROR;
lua_pushnil(vm);
} else {
char buf[BUFLEN];
SNMPMessage *message;
char *sender_host, *oid_str, *value_str;
int sender_port, added = 0, len;
len = receive_udp_datagram(buf, BUFLEN, sock, &sender_host, &sender_port);
message = snmp_parse_message(buf, len);
i = 0;
while(snmp_get_varbind_as_string(message, i, &oid_str, NULL, &value_str)) {
if(!added) lua_newtable(vm), added = 1;
lua_push_str_table_entry(vm, oid_str, value_str);
if(debug)
ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP OK %s@%s %s=%s", agent_host, community, oid_str, value_str);
i++;
}
snmp_destroy_message(message);
if(!added) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "SNMP Error %s@%s", agent_host, community);
lua_pushnil(vm), rc = CONST_LUA_ERROR;
}
}
closesocket(sock);
return(rc);
}
/* ****************************************** */
static int ntop_snmpget(lua_State* vm) { return(ntop_snmp_get_fctn(vm, SNMP_GET_REQUEST_TYPE)); }
static int ntop_snmpgetnext(lua_State* vm) { return(ntop_snmp_get_fctn(vm, SNMP_GETNEXT_REQUEST_TYPE)); }
/* ****************************************** */
/**
* @brief Send a message to the system syslog
* @details Send a message to the syslog syslog: callers can specify if it is an error or informational message
*
* @param vm The lua state.
* @return @ref CONST_LUA_ERROR if the expected type is equal to function type, @ref CONST_LUA_PARAM_ERROR otherwise.
*/
static int ntop_syslog(lua_State* vm) {
#ifndef WIN32
char *msg;
bool is_error;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
is_error = lua_toboolean(vm, 1) ? true : false;
msg = (char*)lua_tostring(vm, 2);
syslog(is_error ? LOG_ERR : LOG_INFO, "%s", msg);
#endif
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Generate a random value to prevent CSRF and XSRF attacks
* @details See http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
*
* @param vm The lua state.
* @return The random value just generated
*/
static int ntop_generate_csrf_value(lua_State* vm) {
char random_a[32], random_b[32], csrf[33], user[64] = { '\0' };
Redis *redis = ntop->getRedis();
struct mg_connection *conn;
lua_getglobal(vm, CONST_HTTP_CONN);
if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection");
return(CONST_LUA_OK);
}
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
#ifdef __OpenBSD__
snprintf(random_a, sizeof(random_a), "%d", arc4random());
snprintf(random_b, sizeof(random_b), "%lu", time(NULL)*arc4random());
#else
snprintf(random_a, sizeof(random_a), "%d", rand());
snprintf(random_b, sizeof(random_b), "%lu", time(NULL)*rand());
#endif
mg_get_cookie(conn, "user", user, sizeof(user));
mg_md5(csrf, random_a, random_b, NULL);
redis->set(csrf, (char*)user, MAX_CSRF_DURATION);
lua_pushfstring(vm, "%s", csrf);
return(CONST_LUA_OK);
}
/* ****************************************** */
struct ntopng_sqlite_state {
lua_State* vm;
u_int num_rows;
};
static int sqlite_callback(void *data, int argc,
char **argv, char **azColName) {
struct ntopng_sqlite_state *s = (struct ntopng_sqlite_state*)data;
lua_newtable(s->vm);
for(int i=0; i<argc; i++)
lua_push_str_table_entry(s->vm, (const char*)azColName[i],
(char*)(argv[i] ? argv[i] : "NULL"));
lua_pushinteger(s->vm, ++s->num_rows);
lua_insert(s->vm, -2);
lua_settable(s->vm, -3);
return(0);
}
/* ****************************************** */
/**
* @brief Exec SQL query
* @details Execute the specified query and return the results
*
* @param vm The lua state.
* @return @ref CONST_LUA_ERROR in case of error, CONST_LUA_OK otherwise.
*/
static int ntop_sqlite_exec_query(lua_State* vm) {
char *db_path, *db_query;
sqlite3 *db;
char *zErrMsg = 0;
struct ntopng_sqlite_state state;
struct stat buf;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
db_path = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
db_query = (char*)lua_tostring(vm, 2);
if(stat(db_path, &buf) != 0) {
ntop->getTrace()->traceEvent(TRACE_INFO, "Not found database %s",
db_path);
return(CONST_LUA_ERROR);
}
if(sqlite3_open(db_path, &db)) {
ntop->getTrace()->traceEvent(TRACE_INFO, "Unable to open %s: %s",
db_path, sqlite3_errmsg(db));
return(CONST_LUA_ERROR);
}
state.vm = vm, state.num_rows = 0;
lua_newtable(vm);
if(sqlite3_exec(db, db_query, sqlite_callback, (void*)&state, &zErrMsg)) {
ntop->getTrace()->traceEvent(TRACE_INFO, "SQL Error: %s", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return(CONST_LUA_OK);
}
/**
* @brief Insert a new minute sampling in the historical database
* @details Given a certain sampling point, store statistics for said
* sampling point.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_insert_minute_sampling(lua_State *vm) {
char *sampling;
time_t rawtime;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
time(&rawtime);
if(sm->insertMinuteSampling(rawtime, sampling))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Insert a new hour sampling in the historical database
* @details Given a certain sampling point, store statistics for said
* sampling point.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_insert_hour_sampling(lua_State *vm) {
char *sampling;
time_t rawtime;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
time(&rawtime);
rawtime -= (rawtime % 60);
if(sm->insertHourSampling(rawtime, sampling))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Insert a new day sampling in the historical database
* @details Given a certain sampling point, store statistics for said
* sampling point.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_insert_day_sampling(lua_State *vm) {
char *sampling;
time_t rawtime;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
time(&rawtime);
rawtime -= (rawtime % 60);
if(sm->insertDaySampling(rawtime, sampling))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Get a minute sampling from the historical database
* @details Given a certain sampling point, get statistics for said
* sampling point.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_minute_sampling(lua_State *vm) {
time_t epoch;
string sampling;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch = (time_t)lua_tointeger(vm, 2);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->getMinuteSampling(epoch, &sampling))
return(CONST_LUA_ERROR);
lua_pushstring(vm, sampling.c_str());
return(CONST_LUA_OK);
}
/**
* @brief Delete minute stats older than a certain number of days.
* @details Given a number of days, delete stats for the current interface that
* are older than a certain number of days.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_delete_minute_older_than(lua_State *vm) {
int num_days;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_days = lua_tointeger(vm, 2);
if(num_days < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->deleteMinuteStatsOlderThan(num_days))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Delete hour stats older than a certain number of days.
* @details Given a number of days, delete stats for the current interface that
* are older than a certain number of days.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_delete_hour_older_than(lua_State *vm) {
int num_days;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_days = lua_tointeger(vm, 2);
if(num_days < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->deleteHourStatsOlderThan(num_days))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Delete day stats older than a certain number of days.
* @details Given a number of days, delete stats for the current interface that
* are older than a certain number of days.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_delete_day_older_than(lua_State *vm) {
int num_days;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_days = lua_tointeger(vm, 2);
if(num_days < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->deleteDayStatsOlderThan(num_days))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Get an interval of minute stats samplings from the historical database
* @details Given a certain interval of sampling points, get statistics for said
* sampling points.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_minute_samplings_interval(lua_State *vm) {
time_t epoch_start, epoch_end;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
struct statsManagerRetrieval retvals;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_start = lua_tointeger(vm, 2);
if(epoch_start < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 3);
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->retrieveMinuteStatsInterval(epoch_start, epoch_end, &retvals))
return(CONST_LUA_ERROR);
lua_newtable(vm);
for (unsigned i = 0 ; i < retvals.rows.size() ; i++)
lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)"");
return(CONST_LUA_OK);
}
/**
* @brief Given an epoch, get minute stats for the latest n minutes
* @details Given a certain sampling point, get statistics for that point and
* for all timepoints spanning an interval of a given number of
* minutes.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_samplings_of_minutes_from_epoch(lua_State *vm) {
time_t epoch_start, epoch_end;
int num_minutes;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
struct statsManagerRetrieval retvals;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 2);
epoch_end -= (epoch_end % 60);
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_minutes = lua_tointeger(vm, 3);
if(num_minutes < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
epoch_start = epoch_end - (60 * num_minutes);
if(sm->retrieveMinuteStatsInterval(epoch_start, epoch_end, &retvals))
return(CONST_LUA_ERROR);
lua_newtable(vm);
for (unsigned i = 0 ; i < retvals.rows.size() ; i++)
lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)"");
return(CONST_LUA_OK);
}
/**
* @brief Given an epoch, get hour stats for the latest n hours
* @details Given a certain sampling point, get statistics for that point and
* for all timepoints spanning an interval of a given number of
* hours.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_samplings_of_hours_from_epoch(lua_State *vm) {
time_t epoch_start, epoch_end;
int num_hours;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
struct statsManagerRetrieval retvals;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 2);
epoch_end -= (epoch_end % 60);
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_hours = lua_tointeger(vm, 3);
if(num_hours < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
epoch_start = epoch_end - (num_hours * 60 * 60);
if(sm->retrieveHourStatsInterval(epoch_start, epoch_end, &retvals))
return(CONST_LUA_ERROR);
lua_newtable(vm);
for (unsigned i = 0 ; i < retvals.rows.size() ; i++)
lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)"");
return(CONST_LUA_OK);
}
/**
* @brief Given an epoch, get hour stats for the latest n days
* @details Given a certain sampling point, get statistics for that point and
* for all timepoints spanning an interval of a given number of
* days.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_samplings_of_days_from_epoch(lua_State *vm) {
time_t epoch_start, epoch_end;
int num_days;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
struct statsManagerRetrieval retvals;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 2);
epoch_end -= (epoch_end % 60);
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_days = lua_tointeger(vm, 3);
if(num_days < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
epoch_start = epoch_end - (num_days * 24 * 60 * 60);
if(sm->retrieveDayStatsInterval(epoch_start, epoch_end, &retvals))
return(CONST_LUA_ERROR);
lua_newtable(vm);
for (unsigned i = 0 ; i < retvals.rows.size() ; i++)
lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)"");
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_delete_dump_files(lua_State *vm) {
int ifid;
char pcap_path[MAX_PATH];
NetworkInterface *iface;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
if((ifid = lua_tointeger(vm, 1)) < 0) return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid))) return(CONST_LUA_ERROR);
snprintf(pcap_path, sizeof(pcap_path), "%s/%d/pcap/",
ntop->get_working_dir(), ifid);
ntop->fixPath(pcap_path);
if(Utils::discardOldFilesExceeding(pcap_path, iface->getDumpTrafficMaxFiles()))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_mkdir_tree(lua_State* vm) {
char *dir;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((dir = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(dir[0] == '\0') return(CONST_LUA_OK); /* Nothing to do */
return(Utils::mkdir_tree(dir));
}
/* ****************************************** */
static int ntop_list_reports(lua_State* vm) {
DIR *dir;
char fullpath[MAX_PATH];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_newtable(vm);
snprintf(fullpath, sizeof(fullpath), "%s/%s", ntop->get_working_dir(), "reports");
ntop->fixPath(fullpath);
if((dir = opendir(fullpath)) != NULL) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
char filepath[MAX_PATH];
snprintf(filepath, sizeof(filepath), "%s/%s", fullpath, ent->d_name);
ntop->fixPath(filepath);
struct stat buf;
if(!stat(filepath, &buf) && !S_ISDIR(buf.st_mode))
lua_push_str_table_entry(vm, ent->d_name, (char*)"");
}
closedir(dir);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_redis(lua_State* vm) {
char *key, *rsp;
u_int rsp_len = 32768;
Redis *redis = ntop->getRedis();
bool cache_it = false;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
/* Optional cache_it */
if(lua_type(vm, 2) == LUA_TBOOLEAN) cache_it = lua_toboolean(vm, 2);
if((rsp = (char*)malloc(rsp_len)) != NULL) {
lua_pushfstring(vm, "%s", (redis->get(key, rsp, rsp_len, cache_it) == 0) ? rsp : (char*)"");
free(rsp);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_get_hash_redis(lua_State* vm) {
char *key, *member, rsp[CONST_MAX_LEN_REDIS_VALUE];
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
lua_pushfstring(vm, "%s", (redis->hashGet(key, member, rsp, sizeof(rsp)) == 0) ? rsp : (char*)"");
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_set_hash_redis(lua_State* vm) {
char *key, *member, *value;
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((value = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
redis->hashSet(key, member, value);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_del_hash_redis(lua_State* vm) {
char *key, *member;
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
redis->hashDel(key, member);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_hash_keys_redis(lua_State* vm) {
char *key, **vals;
Redis *redis = ntop->getRedis();
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
rc = redis->hashKeys(key, &vals);
if(rc > 0) {
lua_newtable(vm);
for(int i = 0; i < rc; i++) {
lua_push_str_table_entry(vm, vals[i] ? vals[i] : "", (char*)"");
if(vals[i]) free(vals[i]);
}
free(vals);
} else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_keys_redis(lua_State* vm) {
char *pattern, **keys;
Redis *redis = ntop->getRedis();
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((pattern = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
rc = redis->keys(pattern, &keys);
if(rc > 0) {
lua_newtable(vm);
for(int i = 0; i < rc; i++) {
lua_push_str_table_entry(vm, keys[i] ? keys[i] : "", (char*)"");
if(keys[i]) free(keys[i]);
}
free(keys);
} else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_lrange_redis(lua_State* vm) {
char *l_name, **l_elements;
Redis *redis = ntop->getRedis();
int start_offset = 0, end_offset = -1;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((l_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 2) == LUA_TNUMBER) {
start_offset = lua_tointeger(vm, 2);
}
if(lua_type(vm, 3) == LUA_TNUMBER) {
end_offset = lua_tointeger(vm, 3);
}
rc = redis->lrange(l_name, &l_elements, start_offset, end_offset);
if(rc > 0) {
lua_newtable(vm);
for(int i = 0; i < rc; i++) {
lua_push_str_table_entry(vm, l_elements[i] ? l_elements[i] : "", (char*)"");
if(l_elements[i]) free(l_elements[i]);
}
free(l_elements);
} else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_redis_set_pop(lua_State* vm) {
char *set_name, rsp[CONST_MAX_LEN_REDIS_VALUE];
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((set_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
lua_pushfstring(vm, "%s", redis->popSet(set_name, rsp, sizeof(rsp)));
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_list_index_redis(lua_State* vm) {
char *index_name, rsp[CONST_MAX_LEN_REDIS_VALUE];
Redis *redis = ntop->getRedis();
int idx;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((index_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
idx = lua_tointeger(vm, 2);
if(redis->lindex(index_name, idx, rsp, sizeof(rsp)) != 0)
return(CONST_LUA_ERROR);
lua_pushfstring(vm, "%s", rsp);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_lpop_redis(lua_State* vm) {
char msg[1024], *list_name;
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((list_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(redis->lpop(list_name, msg, sizeof(msg)) == 0) {
lua_pushfstring(vm, "%s", msg);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_lpush_redis(lua_State* vm) {
char *list_name, *value;
u_int list_trim_size = 0; // default 0 = no trim
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((list_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
/* Optional trim list up to the specified number of elements */
if(lua_type(vm, 3) == LUA_TNUMBER)
list_trim_size = (u_int)lua_tonumber(vm, 3);
if(redis->lpush(list_name, value, list_trim_size) == 0) {
return(CONST_LUA_OK);
}else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_redis_get_host_id(lua_State* vm) {
char *host_name;
Redis *redis = ntop->getRedis();
char daybuf[32];
time_t when = time(NULL);
bool new_key;
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((host_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
strftime(daybuf, sizeof(daybuf), CONST_DB_DAY_FORMAT, localtime(&when));
lua_pushinteger(vm, redis->host_to_id(ntop_interface, daybuf, host_name, &new_key)); /* CHECK */
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_redis_get_id_to_host(lua_State* vm) {
char *host_idx, rsp[CONST_MAX_LEN_REDIS_VALUE];
Redis *redis = ntop->getRedis();
char daybuf[32];
time_t when = time(NULL);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((host_idx = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
strftime(daybuf, sizeof(daybuf), CONST_DB_DAY_FORMAT, localtime(&when));
lua_pushfstring(vm, "%d", redis->id_to_host(daybuf, host_idx, rsp, sizeof(rsp)));
return(CONST_LUA_OK);
}
/* ****************************************** */
#ifdef NOTUSED
static int ntop_interface_store_alert(lua_State* vm) {
int ifid;
NetworkInterface* iface;
AlertsManager *am;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TTABLE)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(vm, ifid)) ||
!(am = iface->getAlertsManager()))
return (CONST_LUA_ERROR);
return am->storeAlert(vm, 2) ? CONST_LUA_ERROR : CONST_LUA_OK;
}
#endif
/* ****************************************** */
static int ntop_interface_engage_release_host_alert(lua_State* vm, bool engage) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
int alert_severity;
int alert_type;
char *alert_json, *engaged_alert_id;
AlertsManager *am;
int ret;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
engaged_alert_id = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_type = (int)lua_tonumber(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_severity = (int)lua_tonumber(vm, 4);
if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_json = (char*)lua_tostring(vm, 5);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
if(engage)
ret = am->engageHostAlert(h, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
else
ret = am->releaseHostAlert(h, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_interface_engage_release_network_alert(lua_State* vm, bool engage) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *cidr;
int alert_severity;
int alert_type;
char *alert_json, *engaged_alert_id;
AlertsManager *am;
int ret;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
cidr = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
engaged_alert_id = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_type = (int)lua_tonumber(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_severity = (int)lua_tonumber(vm, 4);
if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_json = (char*)lua_tostring(vm, 5);
if((!ntop_interface)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
if(engage)
ret = am->engageNetworkAlert(cidr, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
else
ret = am->releaseNetworkAlert(cidr, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_interface_engage_release_interface_alert(lua_State* vm, bool engage) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int alert_severity;
int alert_type;
char *alert_json, *engaged_alert_id;
AlertsManager *am;
int ret;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
engaged_alert_id = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_type = (int)lua_tonumber(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_severity = (int)lua_tonumber(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_json = (char*)lua_tostring(vm, 4);
if((!ntop_interface)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
if(engage)
ret = am->engageInterfaceAlert(ntop_interface, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
else
ret = am->releaseInterfaceAlert(ntop_interface, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_interface_engage_host_alert(lua_State* vm) {
return ntop_interface_engage_release_host_alert(vm, true /* engage */);
}
/* ****************************************** */
static int ntop_interface_release_host_alert(lua_State* vm) {
return ntop_interface_engage_release_host_alert(vm, false /* release */);
}
/* ****************************************** */
static int ntop_interface_engage_network_alert(lua_State* vm) {
return ntop_interface_engage_release_network_alert(vm, true /* engage */);
}
/* ****************************************** */
static int ntop_interface_release_network_alert(lua_State* vm) {
return ntop_interface_engage_release_network_alert(vm, false /* release */);
}
/* ****************************************** */
static int ntop_interface_engage_interface_alert(lua_State* vm) {
return ntop_interface_engage_release_interface_alert(vm, true /* engage */);
}
/* ****************************************** */
static int ntop_interface_release_interface_alert(lua_State* vm) {
return ntop_interface_engage_release_interface_alert(vm, false /* release */);
}
/* ****************************************** */
static int ntop_interface_get_cached_num_alerts(lua_State* vm) {
NetworkInterface *iface = getCurrentInterface(vm);
AlertsManager *am;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!iface || !(am = iface->getAlertsManager()))
return (CONST_LUA_ERROR);
return (!am->getCachedNumAlerts(vm)) ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_interface_make_room_alerts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int alert_entity;
char *alert_entity_value, *table_name;
AlertsManager *am;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_entity = (int)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_entity_value = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
table_name = (char*)lua_tostring(vm, 3);
if((!ntop_interface)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
am->makeRoom((AlertEntity)alert_entity, alert_entity_value, table_name);
return CONST_LUA_OK;
}
/* ****************************************** */
static int ntop_interface_make_room_requested(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
AlertsManager *am;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if((!ntop_interface)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
lua_pushboolean(vm, am->makeRoomRequested());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_query_alerts_raw(lua_State* vm) {
NetworkInterface *iface = getCurrentInterface(vm);
AlertsManager *am;
bool engaged = false;
char *selection = NULL, *clauses = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!iface || !(am = iface->getAlertsManager()))
return (CONST_LUA_ERROR);
if(lua_type(vm, 1) == LUA_TBOOLEAN)
engaged = lua_toboolean(vm, 1);
if(lua_type(vm, 2) == LUA_TSTRING)
if((selection = (char*)lua_tostring(vm, 2)) == NULL)
return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 3) == LUA_TSTRING)
if((clauses = (char*)lua_tostring(vm, 3)) == NULL)
return(CONST_LUA_PARAM_ERROR);
if(am->queryAlertsRaw(vm, engaged, selection, clauses))
return(CONST_LUA_ERROR);
return (CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_query_flow_alerts_raw(lua_State* vm) {
NetworkInterface *iface = getCurrentInterface(vm);
AlertsManager *am;
char *selection = NULL, *clauses = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!iface || !(am = iface->getAlertsManager()))
return (CONST_LUA_ERROR);
if(lua_type(vm, 1) == LUA_TSTRING)
if((selection = (char*)lua_tostring(vm, 1)) == NULL)
return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 2) == LUA_TSTRING)
if((clauses = (char*)lua_tostring(vm, 2)) == NULL)
return(CONST_LUA_PARAM_ERROR);
if(am->queryFlowAlertsRaw(vm, selection, clauses))
return(CONST_LUA_ERROR);
return (CONST_LUA_OK);
}
/* ****************************************** */
#if NTOPNG_PRO
static int ntop_nagios_reload_config(lua_State* vm) {
NagiosManager *nagios = ntop->getNagios();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!nagios) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "%s(): unable to get the nagios manager",
__FUNCTION__);
return(CONST_LUA_ERROR);
}
nagios->loadConfig();
lua_pushnil(vm);
return(CONST_LUA_OK);
}
static int ntop_nagios_send_alert(lua_State* vm) {
NagiosManager *nagios = ntop->getNagios();
char *alert_source;
char *timespan;
char *alarmed_metric;
char *alert_msg;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_source = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
timespan = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
alarmed_metric = (char*)lua_tostring(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_msg = (char*)lua_tostring(vm, 4);
nagios->sendAlert(alert_source, timespan, alarmed_metric, alert_msg);
lua_pushnil(vm);
return(CONST_LUA_OK);
}
static int ntop_nagios_withdraw_alert(lua_State* vm) {
NagiosManager *nagios = ntop->getNagios();
char *alert_source;
char *timespan;
char *alarmed_metric;
char *alert_msg;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_source = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
timespan = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
alarmed_metric = (char*)lua_tostring(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_msg = (char*)lua_tostring(vm, 4);
nagios->withdrawAlert(alert_source, timespan, alarmed_metric, alert_msg);
lua_pushnil(vm);
return(CONST_LUA_OK);
}
#endif
/* ****************************************** */
#ifdef NTOPNG_PRO
static int ntop_check_profile_syntax(lua_State* vm) {
char *filter;
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
filter = (char*)lua_tostring(vm, 1);
lua_pushboolean(vm, ntop_interface ? ntop_interface->checkProfileSyntax(filter) : false);
return(CONST_LUA_OK);
}
#endif
/* ****************************************** */
#ifdef NTOPNG_PRO
static int ntop_reload_traffic_profiles(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface)
ntop_interface->updateFlowProfiles(); /* Reload profiles in memory */
lua_pushnil(vm);
return(CONST_LUA_OK);
}
#endif
/* ****************************************** */
static int ntop_set_redis(lua_State* vm) {
char *key, *value;
u_int expire_secs = 0; // default 0 = no expiration
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
/* Optional key expiration in SECONDS */
if(lua_type(vm, 3) == LUA_TNUMBER)
expire_secs = (u_int)lua_tonumber(vm, 3);
if(redis->set(key, value, expire_secs) == 0) {
return(CONST_LUA_OK);
}else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_set_redis_preference(lua_State* vm) {
char *key, *value;
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(redis->set(key, value) ||
ntop->getPrefs()->refresh(key, value))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_lua_http_print(lua_State* vm) {
struct mg_connection *conn;
char *printtype;
int t;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, CONST_HTTP_CONN);
if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection");
return(CONST_LUA_OK);
}
/* Handle binary blob */
if(lua_type(vm, 2) == LUA_TSTRING &&
(printtype = (char*)lua_tostring(vm, 2)) != NULL)
if(!strncmp(printtype, "blob", 4)) {
char *str = NULL;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return (CONST_LUA_ERROR);
if((str = (char*)lua_tostring(vm, 1)) != NULL) {
int len = strlen(str);
if(len <= 1)
mg_printf(conn, "%c", str[0]);
else
return (CONST_LUA_PARAM_ERROR);
}
return (CONST_LUA_OK);
}
switch(t = lua_type(vm, 1)) {
case LUA_TNIL:
mg_printf(conn, "%s", "nil");
break;
case LUA_TBOOLEAN:
{
int v = lua_toboolean(vm, 1);
mg_printf(conn, "%s", v ? "true" : "false");
}
break;
case LUA_TSTRING:
{
char *str = (char*)lua_tostring(vm, 1);
if(str && (strlen(str) > 0))
mg_printf(conn, "%s", str);
}
break;
case LUA_TNUMBER:
{
char str[64];
snprintf(str, sizeof(str), "%f", (float)lua_tonumber(vm, 1));
mg_printf(conn, "%s", str);
}
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "%s(): Lua type %d is not handled",
__FUNCTION__, t);
return(CONST_LUA_ERROR);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
int ntop_lua_cli_print(lua_State* vm) {
int t;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
switch(t = lua_type(vm, 1)) {
case LUA_TSTRING:
{
char *str = (char*)lua_tostring(vm, 1);
if(str && (strlen(str) > 0))
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s", str);
}
break;
case LUA_TNUMBER:
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%f", (float)lua_tonumber(vm, 1));
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "%s(): Lua type %d is not handled",
__FUNCTION__, t);
return(CONST_LUA_ERROR);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
#ifdef NTOPNG_PRO
static int __ntop_lua_handlefile(lua_State* L, char *script_path, bool ex)
{
int rc;
LuaHandler *lh = new LuaHandler(L, script_path);
rc = lh->luaL_dofileM(ex);
delete lh;
return rc;
}
/* This function is called by Lua scripts when the call require(...) */
static int ntop_lua_require(lua_State* L)
{
char *script_name;
if(lua_type(L, 1) != LUA_TSTRING ||
(script_name = (char*)lua_tostring(L, 1)) == NULL)
return 0;
lua_getglobal( L, "package" );
lua_getfield( L, -1, "path" );
string cur_path = lua_tostring( L, -1 ), parsed, script_path = "";
stringstream input_stringstream(cur_path);
while(getline(input_stringstream, parsed, ';')) {
/* Example: package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path */
unsigned found = parsed.find_last_of("?");
if(found) {
string s = parsed.substr(0, found) + script_name + ".lua";
if(Utils::file_exists(s.c_str())) {
script_path = s;
break;
}
}
}
if(script_path == "" ||
__ntop_lua_handlefile(L, (char *)script_path.c_str(), false))
return 0;
return 1;
}
static int ntop_lua_dofile(lua_State* L)
{
char *script_path;
if(lua_type(L, 1) != LUA_TSTRING ||
(script_path = (char*)lua_tostring(L, 1)) == NULL ||
__ntop_lua_handlefile(L, script_path, true))
return 0;
return 1;
}
#endif
/* ****************************************** */
/**
* @brief Return true if login has been disabled
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK and push the return code into the Lua stack
*/
static int ntop_is_login_disabled(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
bool ret = ntop->getPrefs()->is_localhost_users_login_disabled()
|| !ntop->getPrefs()->is_users_login_enabled();
lua_pushboolean(vm, ret);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Convert the network Id to a symbolic name (network/mask)
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK and push the return code into the Lua stack
*/
static int ntop_network_name_by_id(lua_State* vm) {
int id;
char *name;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
id = (u_int32_t)lua_tonumber(vm, 1);
name = ntop->getLocalNetworkName(id);
lua_pushstring(vm, name ? name : "");
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_set_logging_level(lua_State* vm) {
char *lvlStr;
ntop->getTrace()->traceEvent(TRACE_INFO, "%s() called", __FUNCTION__);
if(ntop->getPrefs()->hasCmdlTraceLevel()) return(CONST_LUA_OK);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
lvlStr = (char*)lua_tostring(vm, 1);
if(!strcmp(lvlStr, "trace")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_TRACE);
}
else if(!strcmp(lvlStr, "debug")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_DEBUG);
}
else if(!strcmp(lvlStr, "info")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_INFO);
}
else if(!strcmp(lvlStr, "normal")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_NORMAL);
}
else if(!strcmp(lvlStr, "warning")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_WARNING);
}
else if(!strcmp(lvlStr, "error")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_ERROR);
}
else{
return(CONST_LUA_ERROR);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static const luaL_Reg ntop_interface_reg[] = {
{ "getDefaultIfName", ntop_get_default_interface_name },
{ "setActiveInterfaceId", ntop_set_active_interface_id },
{ "getIfNames", ntop_get_interface_names },
{ "select", ntop_select_interface },
{ "getStats", ntop_get_interface_stats },
{ "resetCounters", ntop_interface_reset_counters },
{ "getnDPIStats", ntop_get_ndpi_interface_stats },
{ "getnDPIProtoName", ntop_get_ndpi_protocol_name },
{ "getnDPIProtoId", ntop_get_ndpi_protocol_id },
{ "getnDPIProtoCategory", ntop_get_ndpi_protocol_category },
{ "getnDPIFlowsCount", ntop_get_ndpi_interface_flows_count },
{ "getFlowsStatus", ntop_get_ndpi_interface_flows_status },
{ "getnDPIProtoBreed", ntop_get_ndpi_protocol_breed },
{ "getnDPIProtocols", ntop_get_ndpi_protocols },
{ "getnDPICategories", ntop_get_ndpi_categories },
{ "getHostsInfo", ntop_get_interface_hosts_info },
{ "getLocalHostsInfo", ntop_get_interface_local_hosts_info },
{ "getRemoteHostsInfo", ntop_get_interface_remote_hosts_info },
{ "getHostActivity", ntop_get_interface_host_activity },
{ "getHostInfo", ntop_get_interface_host_info },
{ "getGroupedHosts", ntop_get_grouped_interface_hosts },
{ "getNetworksStats", ntop_get_interface_networks_stats },
{ "resetPeriodicStats", ntop_host_reset_periodic_stats },
{ "correlateHostActivity", ntop_correalate_host_activity },
{ "similarHostActivity", ntop_similar_host_activity },
{ "getHostActivityMap", ntop_get_interface_host_activitymap },
{ "restoreHost", ntop_restore_interface_host },
{ "getFlowsInfo", ntop_get_interface_flows_info },
{ "getLocalFlowsInfo", ntop_get_interface_local_flows_info },
{ "getRemoteFlowsInfo", ntop_get_interface_remote_flows_info },
{ "getFlowsStats", ntop_get_interface_flows_stats },
{ "getFlowKey", ntop_get_interface_flow_key },
{ "findFlowByKey", ntop_get_interface_find_flow_by_key },
{ "dropFlowTraffic", ntop_drop_flow_traffic },
{ "dumpFlowTraffic", ntop_dump_flow_traffic },
{ "dumpLocalHosts2redis", ntop_dump_local_hosts_2_redis },
{ "findUserFlows", ntop_get_interface_find_user_flows },
{ "findPidFlows", ntop_get_interface_find_pid_flows },
{ "findFatherPidFlows", ntop_get_interface_find_father_pid_flows },
{ "findNameFlows", ntop_get_interface_find_proc_name_flows },
{ "listHTTPhosts", ntop_list_http_hosts },
{ "findHost", ntop_get_interface_find_host },
{ "updateHostTrafficPolicy", ntop_update_host_traffic_policy },
{ "updateHostAlertPolicy", ntop_update_host_alert_policy },
{ "setSecondTraffic", ntop_set_second_traffic },
{ "setHostDumpPolicy", ntop_set_host_dump_policy },
{ "setHostQuota", ntop_set_host_quota },
{ "getPeerHitRate", ntop_get_host_hit_rate },
{ "getLatestActivityHostsInfo", ntop_get_interface_latest_activity_hosts_info },
{ "getInterfaceDumpDiskPolicy", ntop_get_interface_dump_disk_policy },
{ "getInterfaceDumpTapPolicy", ntop_get_interface_dump_tap_policy },
{ "getInterfaceDumpTapName", ntop_get_interface_dump_tap_name },
{ "getInterfaceDumpMaxPkts", ntop_get_interface_dump_max_pkts },
{ "getInterfaceDumpMaxSec", ntop_get_interface_dump_max_sec },
{ "getInterfaceDumpMaxFiles", ntop_get_interface_dump_max_files },
{ "getInterfacePacketsDumpedFile", ntop_get_interface_pkts_dumped_file },
{ "getInterfacePacketsDumpedTap", ntop_get_interface_pkts_dumped_tap },
{ "getEndpoint", ntop_get_interface_endpoint },
{ "isPacketInterface", ntop_interface_is_packet_interface },
{ "isBridgeInterface", ntop_interface_is_bridge_interface },
{ "isPcapDumpInterface", ntop_interface_is_pcap_dump_interface },
{ "isRunning", ntop_interface_is_running },
{ "isIdle", ntop_interface_is_idle },
{ "setInterfaceIdleState", ntop_interface_set_idle },
{ "name2id", ntop_interface_name2id },
{ "loadDumpPrefs", ntop_load_dump_prefs },
{ "loadScalingFactorPrefs", ntop_load_scaling_factor_prefs },
{ "loadHostAlertPrefs", ntop_interface_load_host_alert_prefs },
/* Mac */
{ "getMacsInfo", ntop_get_interface_macs_info },
{ "getMacInfo", ntop_get_interface_mac_info },
/* L7 */
{ "reloadL7Rules", ntop_reload_l7_rules },
{ "reloadShapers", ntop_reload_shapers },
/* Host pools */
{ "reloadHostPools", ntop_reload_host_pools },
#ifdef NTOPNG_PRO
{ "getHostPoolsStats", ntop_get_host_pool_interface_stats },
{ "getHostPoolsVolatileMembers", ntop_get_host_pool_volatile_members },
{ "purgeExpiredPoolsMembers", ntop_purge_expired_host_pools_members },
{ "removeVolatileMemberFromPool", ntop_remove_volatile_member_from_pool },
#endif
/* DB */
{ "execSQLQuery", ntop_interface_exec_sql_query },
/* Flows */
{ "getFlowDevices", ntop_getflowdevices },
{ "getFlowDeviceInfo", ntop_getflowdeviceinfo },
/* New generation alerts */
{ "getCachedNumAlerts", ntop_interface_get_cached_num_alerts },
{ "queryAlertsRaw", ntop_interface_query_alerts_raw },
{ "queryFlowAlertsRaw", ntop_interface_query_flow_alerts_raw },
{ "engageHostAlert", ntop_interface_engage_host_alert },
{ "releaseHostAlert", ntop_interface_release_host_alert },
{ "engageNetworkAlert", ntop_interface_engage_network_alert },
{ "releaseNetworkAlert", ntop_interface_release_network_alert },
{ "engageInterfaceAlert", ntop_interface_engage_interface_alert },
{ "releaseInterfaceAlert",ntop_interface_release_interface_alert },
{ "enableHostAlerts", ntop_interface_host_enable_alerts },
{ "disableHostAlerts", ntop_interface_host_disable_alerts },
{ "refreshNumAlerts", ntop_interface_refresh_num_alerts },
{ "makeRoomAlerts", ntop_interface_make_room_alerts },
{ "makeRoomRequested", ntop_interface_make_room_requested },
{ NULL, NULL }
};
/* **************************************************************** */
static const luaL_Reg ntop_reg[] = {
{ "getDirs", ntop_get_dirs },
{ "getInfo", ntop_get_info },
{ "getUptime", ntop_get_uptime },
{ "dumpFile", ntop_dump_file },
{ "checkLicense", ntop_check_license },
/* Redis */
{ "getCache", ntop_get_redis },
{ "setCache", ntop_set_redis },
{ "delCache", ntop_delete_redis_key },
{ "listIndexCache", ntop_list_index_redis },
{ "lpushCache", ntop_lpush_redis },
{ "lpopCache", ntop_lpop_redis },
{ "lrangeCache", ntop_lrange_redis },
{ "setMembersCache", ntop_add_set_member_redis },
{ "delMembersCache", ntop_del_set_member_redis },
{ "getMembersCache", ntop_get_set_members_redis },
{ "getHashCache", ntop_get_hash_redis },
{ "setHashCache", ntop_set_hash_redis },
{ "delHashCache", ntop_del_hash_redis },
{ "getHashKeysCache",ntop_get_hash_keys_redis },
{ "getKeysCache", ntop_get_keys_redis },
{ "delHashCache", ntop_delete_hash_redis_key },
{ "setPopCache", ntop_get_redis_set_pop },
{ "getHostId", ntop_redis_get_host_id },
{ "getIdToHost", ntop_redis_get_id_to_host },
/* Redis Preferences */
{ "setPref", ntop_set_redis_preference },
{ "getPref", ntop_get_redis },
{ "isdir", ntop_is_dir },
{ "mkdir", ntop_mkdir_tree },
{ "notEmptyFile", ntop_is_not_empty_file },
{ "exists", ntop_get_file_dir_exists },
{ "listReports", ntop_list_reports },
{ "fileLastChange", ntop_get_file_last_change },
{ "readdir", ntop_list_dir_files },
{ "rmdir", ntop_remove_dir_recursively },
{ "zmq_connect", ntop_zmq_connect },
{ "zmq_disconnect", ntop_zmq_disconnect },
{ "zmq_receive", ntop_zmq_receive },
{ "getLocalNetworks", ntop_get_local_networks },
{ "reloadPreferences", ntop_reload_preferences },
#ifdef NTOPNG_PRO
{ "sendNagiosAlert", ntop_nagios_send_alert },
{ "withdrawNagiosAlert", ntop_nagios_withdraw_alert },
{ "reloadNagiosConfig", ntop_nagios_reload_config },
{ "checkProfileSyntax", ntop_check_profile_syntax },
{ "reloadProfiles", ntop_reload_traffic_profiles },
#endif
/* Pro */
{ "isPro", ntop_is_pro },
{ "isEnterprise", ntop_is_enterprise },
/* Historical database */
{ "insertMinuteSampling", ntop_stats_insert_minute_sampling },
{ "insertHourSampling", ntop_stats_insert_hour_sampling },
{ "insertDaySampling", ntop_stats_insert_day_sampling },
{ "getMinuteSampling", ntop_stats_get_minute_sampling },
{ "deleteMinuteStatsOlderThan", ntop_stats_delete_minute_older_than },
{ "deleteHourStatsOlderThan", ntop_stats_delete_hour_older_than },
{ "deleteDayStatsOlderThan", ntop_stats_delete_day_older_than },
{ "getMinuteSamplingsFromEpoch", ntop_stats_get_samplings_of_minutes_from_epoch },
{ "getHourSamplingsFromEpoch", ntop_stats_get_samplings_of_hours_from_epoch },
{ "getDaySamplingsFromEpoch", ntop_stats_get_samplings_of_days_from_epoch },
{ "getMinuteSamplingsInterval", ntop_stats_get_minute_samplings_interval },
{ "deleteDumpFiles", ntop_delete_dump_files },
/* Time */
{ "gettimemsec", ntop_gettimemsec },
/* Trace */
{ "verboseTrace", ntop_verbose_trace },
/* UDP */
{ "send_udp_data", ntop_send_udp_data },
/* IP */
{ "inet_ntoa", ntop_inet_ntoa },
/* RRD */
{ "rrd_create", ntop_rrd_create },
{ "rrd_update", ntop_rrd_update },
{ "rrd_fetch", ntop_rrd_fetch },
{ "rrd_fetch_columns", ntop_rrd_fetch_columns },
{ "rrd_lastupdate", ntop_rrd_lastupdate },
/* Prefs */
{ "getPrefs", ntop_get_prefs },
/* HTTP */
{ "httpRedirect", ntop_http_redirect },
{ "httpGet", ntop_http_get },
{ "getHttpPrefix", ntop_http_get_prefix },
/* Admin */
{ "getNologinUser", ntop_get_nologin_username },
{ "getUsers", ntop_get_users },
{ "getUserGroup", ntop_get_user_group },
{ "getAllowedNetworks", ntop_get_allowed_networks },
{ "resetUserPassword", ntop_reset_user_password },
{ "changeUserRole", ntop_change_user_role },
{ "changeAllowedNets", ntop_change_allowed_nets },
{ "changeAllowedIfname",ntop_change_allowed_ifname },
{ "changeUserHostPool", ntop_change_user_host_pool },
{ "addUser", ntop_add_user },
{ "addUserLifetime", ntop_add_user_lifetime },
{ "clearUserLifetime", ntop_clear_user_lifetime },
{ "deleteUser", ntop_delete_user },
{ "isLoginDisabled", ntop_is_login_disabled },
{ "getNetworkNameById", ntop_network_name_by_id },
/* Security */
{ "getRandomCSRFValue", ntop_generate_csrf_value },
/* HTTP */
{ "postHTTPJsonData", ntop_post_http_json_data },
/* Address Resolution */
{ "resolveAddress", ntop_resolve_address },
{ "getResolvedAddress", ntop_get_resolved_address },
/* Logging */
{ "syslog", ntop_syslog },
{ "setLoggingLevel",ntop_set_logging_level },
/* SNMP */
{ "snmpget", ntop_snmpget },
{ "snmpgetnext", ntop_snmpgetnext },
/* SQLite */
{ "execQuery", ntop_sqlite_exec_query },
/* Runtime */
{ "hasVLANs", ntop_has_vlans },
{ "hasGeoIP", ntop_has_geoip },
{ "isWindows", ntop_is_windows },
/* Host Blacklist */
{ "allocHostBlacklist", ntop_allocHostBlacklist },
{ "swapHostBlacklist", ntop_swapHostBlacklist },
{ "addToHostBlacklist", ntop_addToHostBlacklist },
/* Misc */
{ "getservbyport", ntop_getservbyport },
{ "getMacManufacturer", ntop_get_mac_manufacturer },
{ "getSiteCategories", ntop_get_site_categories },
{ NULL, NULL}
};
/* ****************************************** */
void Lua::lua_register_classes(lua_State *L, bool http_mode) {
static const luaL_Reg _meta[] = { { NULL, NULL } };
int i;
ntop_class_reg ntop_lua_reg[] = {
{ "interface", ntop_interface_reg },
{ "ntop", ntop_reg },
{NULL, NULL}
};
if(!L) return;
luaopen_lsqlite3(L);
for(i=0; ntop_lua_reg[i].class_name != NULL; i++) {
int lib_id, meta_id;
/* newclass = {} */
lua_createtable(L, 0, 0);
lib_id = lua_gettop(L);
/* metatable = {} */
luaL_newmetatable(L, ntop_lua_reg[i].class_name);
meta_id = lua_gettop(L);
luaL_register(L, NULL, _meta);
/* metatable.__index = class_methods */
lua_newtable(L), luaL_register(L, NULL, ntop_lua_reg[i].class_methods);
lua_setfield(L, meta_id, "__index");
/* class.__metatable = metatable */
lua_setmetatable(L, lib_id);
/* _G["Foo"] = newclass */
lua_setglobal(L, ntop_lua_reg[i].class_name);
}
if(http_mode) {
/* Overload the standard Lua print() with ntop_lua_http_print that dumps data on HTTP server */
lua_register(L, "print", ntop_lua_http_print);
} else
lua_register(L, "print", ntop_lua_cli_print);
#ifdef NTOPNG_PRO
if(ntop->getPro()->has_valid_license()) {
lua_register(L, "ntopRequire", ntop_lua_require);
luaL_dostring(L, "table.insert(package.loaders, 1, ntopRequire)");
lua_register(L, "dofile", ntop_lua_dofile);
}
#endif
}
/* ****************************************** */
#if 0
/**
* Iterator over key-value pairs where the value
* maybe made available in increments and/or may
* not be zero-terminated. Used for processing
* POST data.
*
* @param cls user-specified closure
* @param kind type of the value
* @param key 0-terminated key for the value
* @param filename name of the uploaded file, NULL if not known
* @param content_type mime-type of the data, NULL if not known
* @param transfer_encoding encoding of the data, NULL if not known
* @param data pointer to size bytes of data at the
* specified offset
* @param off offset of data in the overall value
* @param size number of bytes in data available
* @return MHD_YES to continue iterating,
* MHD_NO to abort the iteration
*/
static int post_iterator(void *cls,
enum MHD_ValueKind kind,
const char *key,
const char *filename,
const char *content_type,
const char *transfer_encoding,
const char *data, uint64_t off, size_t size)
{
struct Request *request = cls;
char tmp[1024];
u_int len = min(size, sizeof(tmp)-1);
memcpy(tmp, &data[off], len);
tmp[len] = '\0';
fprintf(stdout, "[POST] [%s][%s]\n", key, tmp);
return MHD_YES;
}
#endif
/* ****************************************** */
/*
Run a Lua script from within ntopng (no HTTP GUI)
*/
int Lua::run_script(char *script_path) {
int rc = 0;
if(!L) return(-1);
try {
luaL_openlibs(L); /* Load base libraries */
lua_register_classes(L, false); /* Load custom classes */
#ifndef NTOPNG_PRO
rc = luaL_dofile(L, script_path);
#else
if(ntop->getPro()->has_valid_license())
rc = __ntop_lua_handlefile(L, script_path, true);
else
rc = luaL_dofile(L, script_path);
#endif
if(rc != 0) {
const char *err = lua_tostring(L, -1);
ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err);
rc = -1;
}
} catch(...) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s]", script_path);
rc = -2;
}
return(rc);
}
/* ****************************************** */
/* http://www.geekhideout.com/downloads/urlcode.c */
#if 0
/* Converts an integer value to its hex character*/
static char to_hex(char code) {
static char hex[] = "0123456789abcdef";
return hex[code & 15];
}
/* ****************************************** */
/* Returns a url-encoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
static char* http_encode(char *str) {
char *pstr = str, *buf = (char*)malloc(strlen(str) * 3 + 1), *pbuf = buf;
while (*pstr) {
if(isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
*pbuf++ = *pstr;
else if(*pstr == ' ')
*pbuf++ = '+';
else
*pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
pstr++;
}
*pbuf = '\0';
return buf;
}
#endif
/* ****************************************** */
void Lua::purifyHTTPParameter(char *param) {
char *ampercent;
if((ampercent = strchr(param, '%')) != NULL) {
/* We allow only a few chars, removing all the others */
if((ampercent[1] != 0) && (ampercent[2] != 0)) {
char c;
char b = ampercent[3];
ampercent[3] = '\0';
c = (char)strtol(&ercent[1], NULL, 16);
ampercent[3] = b;
switch(c) {
case '/':
case ':':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case '?':
case '!':
case '$':
case ',':
case '^':
case '*':
case '_':
case '&':
case ' ':
case '=':
case '<':
case '>':
case '@':
case '#':
break;
default:
if(!Utils::isPrintableChar(c)) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded char '0x%02x' in URI [%s]", c, param);
ampercent[0] = '\0';
return;
}
}
purifyHTTPParameter(&ercent[3]);
} else
ampercent[0] = '\0';
}
}
/* ****************************************** */
void Lua::setInterface(const char *user) {
char key[64], ifname[MAX_INTERFACE_NAME_LEN];
bool enforce_allowed_interface = false;
if(user[0] != '\0') {
// check if the user is restricted to browse only a given interface
if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user)
&& !ntop->getRedis()->get(key, ifname, sizeof(ifname))) {
// there is only one allowed interface for the user
enforce_allowed_interface = true;
goto set_preferred_interface;
} else if(snprintf(key, sizeof(key), "ntopng.prefs.%s.ifname", user)
&& ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) {
// no allowed interface and no default set interface
set_default_if_name_in_session:
snprintf(ifname, sizeof(ifname), "%s",
ntop->getInterfaceAtId(NULL /* allowed user interface check already enforced */,
0)->get_name());
lua_push_str_table_entry(L, "ifname", ifname);
ntop->getRedis()->set(key, ifname, 3600 /* 1h */);
} else {
goto set_preferred_interface;
}
} else {
// We need to check if ntopng is running with the option --disable-login
snprintf(key, sizeof(key), "ntopng.prefs.ifname");
if(ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) {
goto set_preferred_interface;
}
set_preferred_interface:
NetworkInterface *iface;
if((iface = ntop->getNetworkInterface(NULL /* allowed user interface check already enforced */,
ifname)) != NULL) {
/* The specified interface still exists */
lua_push_str_table_entry(L, "ifname", iface->get_name());
} else if(!enforce_allowed_interface) {
goto set_default_if_name_in_session;
} else {
// TODO: handle the case where the user has
// an allowed interface that is not presently available
// (e.g., not running?)
}
}
}
/* ****************************************** */
void Lua::setParamsTable(lua_State* vm, const char* table_name,
const char* query) const {
char outbuf[FILENAME_MAX];
char *where;
char *tok;
char *query_string = query ? strdup(query) : NULL;
lua_newtable(L);
if (query_string) {
// ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] %s", query_string);
tok = strtok_r(query_string, "&", &where);
while(tok != NULL) {
char *_equal;
if(strncmp(tok, "csrf", strlen("csrf")) /* Do not put csrf into the params table */
&& (_equal = strchr(tok, '='))) {
char *decoded_buf;
int len;
_equal[0] = '\0';
_equal = &_equal[1];
len = strlen(_equal);
purifyHTTPParameter(tok), purifyHTTPParameter(_equal);
// ntop->getTrace()->traceEvent(TRACE_WARNING, "%s = %s", tok, _equal);
if((decoded_buf = (char*)malloc(len+1)) != NULL) {
Utils::urlDecode(_equal, decoded_buf, len+1);
Utils::purifyHTTPparam(tok, true, false);
Utils::purifyHTTPparam(decoded_buf, false, false);
/* Now make sure that decoded_buf is not a file path */
FILE *fd;
if((decoded_buf[0] == '.')
&& ((fd = fopen(decoded_buf, "r"))
|| (fd = fopen(realpath(decoded_buf, outbuf), "r")))) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded '%s'='%s' as argument is a valid file path",
tok, decoded_buf);
decoded_buf[0] = '\0';
fclose(fd);
}
/* ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, decoded_buf); */
/* put tok and the decoded buffer in to the table */
lua_push_str_table_entry(vm, tok, decoded_buf);
free(decoded_buf);
} else
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
}
tok = strtok_r(NULL, "&", &where);
} /* while */
}
if(query_string) free(query_string);
if(table_name)
lua_setglobal(L, table_name);
else
lua_setglobal(L, (char*)"_GET"); /* Default */
}
/* ****************************************** */
int Lua::handle_script_request(struct mg_connection *conn,
const struct mg_request_info *request_info,
char *script_path) {
char buf[64], key[64], ifname[MAX_INTERFACE_NAME_LEN];
char *_cookies, user[64] = { '\0' };
AddressTree ptree;
int rc;
const char * content_type;
if(!L) return(-1);
luaL_openlibs(L); /* Load base libraries */
lua_register_classes(L, true); /* Load custom classes */
lua_pushlightuserdata(L, (char*)conn);
lua_setglobal(L, CONST_HTTP_CONN);
content_type = mg_get_header(conn, "Content-Type");
/* Check for POST requests */
if((strcmp(request_info->request_method, "POST") == 0) &&
((content_type != NULL) && (strstr(content_type, "application/x-www-form-urlencoded") == content_type))) {
char post_data[1024] = { '\0' };
char rsp[32];
char csrf[64] = { '\0' };
char user[64] = { '\0' };
int post_data_len = mg_read(conn, post_data, sizeof(post_data));
u_int8_t valid_csrf = 1;
post_data[sizeof(post_data)-1] = '\0';
/* CSRF is mandatory in POST request */
mg_get_var(post_data, post_data_len, "csrf", csrf, sizeof(csrf));
mg_get_cookie(conn, "user", user, sizeof(user));
if((ntop->getRedis()->get(csrf, rsp, sizeof(rsp)) == -1)
|| (strcmp(rsp, user) != 0)) {
#if 0
const char *msg = "The submitted form is expired. Please reload the page and try again. <p>[ <A HREF=/>Home</A> ]";
ntop->getTrace()->traceEvent(TRACE_WARNING,
"Invalid CSRF parameter specified [%s][%s][%s][%s]: page expired?",
csrf, rsp, user, "csrf");
return(send_error(conn, 500 /* Internal server error */,
msg, PAGE_ERROR, script_path, msg));
#else
valid_csrf = 0;
#endif
} else {
/* Invalidate csrf */
ntop->getRedis()->del(csrf);
}
if(valid_csrf)
setParamsTable(L, "_POST", post_data); /* CSRF is valid here, now fill the _POST table with POST parameters */
else
setParamsTable(L, "_POST", NULL /* Empty */);
} else
setParamsTable(L, "_POST", NULL /* Empty */);
/* Put the GET params into the environment */
if(request_info->query_string)
setParamsTable(L, "_GET", request_info->query_string);
else
setParamsTable(L, "_GET", NULL /* Empty */);
/* _SERVER */
lua_newtable(L);
lua_push_str_table_entry(L, "REQUEST_METHOD", (char*)request_info->request_method);
lua_push_str_table_entry(L, "URI", (char*)request_info->uri ? (char*)request_info->uri : (char*)"");
lua_push_str_table_entry(L, "REFERER", (char*)mg_get_header(conn, "Referer") ? (char*)mg_get_header(conn, "Referer") : (char*)"");
if(request_info->remote_user) lua_push_str_table_entry(L, "REMOTE_USER", (char*)request_info->remote_user);
if(request_info->query_string) lua_push_str_table_entry(L, "QUERY_STRING", (char*)request_info->query_string);
for(int i=0; ((request_info->http_headers[i].name != NULL)
&& request_info->http_headers[i].name[0] != '\0'); i++)
lua_push_str_table_entry(L,
request_info->http_headers[i].name,
(char*)request_info->http_headers[i].value);
lua_setglobal(L, (char*)"_SERVER");
/* Cookies */
lua_newtable(L);
if((_cookies = (char*)mg_get_header(conn, "Cookie")) != NULL) {
char *cookies = strdup(_cookies);
char *tok, *where;
// ntop->getTrace()->traceEvent(TRACE_WARNING, "=> '%s'", cookies);
tok = strtok_r(cookies, "=", &where);
while(tok != NULL) {
char *val;
while(tok[0] == ' ') tok++;
if((val = strtok_r(NULL, ";", &where)) != NULL) {
lua_push_str_table_entry(L, tok, val);
// ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, val);
} else
break;
tok = strtok_r(NULL, "=", &where);
}
free(cookies);
}
lua_setglobal(L, "_COOKIE"); /* Like in php */
/* Put the _SESSION params into the environment */
lua_newtable(L);
mg_get_cookie(conn, "user", user, sizeof(user));
lua_push_str_table_entry(L, "user", user);
mg_get_cookie(conn, "session", buf, sizeof(buf));
lua_push_str_table_entry(L, "session", buf);
// now it's time to set the interface.
setInterface(user);
lua_setglobal(L, "_SESSION"); /* Like in php */
if(user[0] != '\0') {
char val[255];
lua_pushlightuserdata(L, user);
lua_setglobal(L, "user");
snprintf(key, sizeof(key), "ntopng.user.%s.allowed_nets", user);
if((ntop->getRedis()->get(key, val, sizeof(val)) != -1)
&& (val[0] != '\0')) {
ptree.addAddresses(val);
lua_pushlightuserdata(L, &ptree);
lua_setglobal(L, CONST_ALLOWED_NETS);
// ntop->getTrace()->traceEvent(TRACE_WARNING, "SET %p", ptree);
}
snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user);
if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user)
&& !ntop->getRedis()->get(key, ifname, sizeof(ifname))) {
lua_pushlightuserdata(L, ifname);
lua_setglobal(L, CONST_ALLOWED_IFNAME);
}
}
#ifndef NTOPNG_PRO
rc = luaL_dofile(L, script_path);
#else
if(ntop->getPro()->has_valid_license())
rc = __ntop_lua_handlefile(L, script_path, true);
else
rc = luaL_dofile(L, script_path);
#endif
if(rc != 0) {
const char *err = lua_tostring(L, -1);
ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err);
return(send_error(conn, 500 /* Internal server error */,
"Internal server error", PAGE_ERROR, script_path, err));
}
return(CONST_LUA_OK);
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_3266_0 |
crossvul-cpp_data_good_656_2 | /* GRAPHITE2 LICENSING
Copyright 2010, SIL International
All rights reserved.
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 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
Lesser General Public License for more details.
You should also have received a copy of the GNU Lesser General Public
License along with this library in the file named "LICENSE".
If not, write to the Free Software Foundation, 51 Franklin Street,
Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
internet at http://www.fsf.org/licenses/lgpl.html.
Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or 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 "graphite2/Font.h"
#include "inc/Face.h"
#include "inc/FileFace.h"
#include "inc/GlyphCache.h"
#include "inc/CachedFace.h"
#include "inc/CmapCache.h"
#include "inc/Silf.h"
#include "inc/json.h"
using namespace graphite2;
#if !defined GRAPHITE2_NTRACING
extern json *global_log;
#endif
namespace
{
bool load_face(Face & face, unsigned int options)
{
#ifdef GRAPHITE2_TELEMETRY
telemetry::category _misc_cat(face.tele.misc);
#endif
Face::Table silf(face, Tag::Silf, 0x00050000);
if (!silf)
return false;
if (!face.readGlyphs(options))
return false;
if (silf)
{
if (!face.readFeatures() || !face.readGraphite(silf))
{
#if !defined GRAPHITE2_NTRACING
if (global_log)
{
*global_log << json::object
<< "type" << "fontload"
<< "failure" << face.error()
<< "context" << face.error_context()
<< json::close;
}
#endif
return false;
}
else
return true;
}
else
return false;
}
}
extern "C" {
gr_face* gr_make_face_with_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *ops, unsigned int faceOptions)
//the appFaceHandle must stay alive all the time when the gr_face is alive. When finished with the gr_face, call destroy_face
{
if (ops == 0) return 0;
Face *res = new Face(appFaceHandle, *ops);
if (res && load_face(*res, faceOptions))
return static_cast<gr_face *>(res);
delete res;
return 0;
}
gr_face* gr_make_face(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn tablefn, unsigned int faceOptions)
{
const gr_face_ops ops = {sizeof(gr_face_ops), tablefn, NULL};
return gr_make_face_with_ops(appFaceHandle, &ops, faceOptions);
}
#ifndef GRAPHITE2_NSEGCACHE
gr_face* gr_make_face_with_seg_cache_and_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *ops, unsigned int cacheSize, unsigned int faceOptions)
//the appFaceHandle must stay alive all the time when the GrFace is alive. When finished with the GrFace, call destroy_face
{
if (ops == 0) return 0;
CachedFace *res = new CachedFace(appFaceHandle, *ops);
if (res && load_face(*res, faceOptions)
&& res->setupCache(cacheSize))
return static_cast<gr_face *>(static_cast<Face *>(res));
delete res;
return 0;
}
gr_face* gr_make_face_with_seg_cache(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable, unsigned int cacheSize, unsigned int faceOptions)
{
const gr_face_ops ops = {sizeof(gr_face_ops), getTable, NULL};
return gr_make_face_with_seg_cache_and_ops(appFaceHandle, &ops, cacheSize, faceOptions);
}
#endif
gr_uint32 gr_str_to_tag(const char *str)
{
uint32 res = 0;
int i = strlen(str);
if (i > 4) i = 4;
while (--i >= 0)
res = (res >> 8) + (str[i] << 24);
return res;
}
void gr_tag_to_str(gr_uint32 tag, char *str)
{
int i = 4;
while (--i >= 0)
{
str[i] = tag & 0xFF;
tag >>= 8;
}
}
inline
uint32 zeropad(const uint32 x)
{
if (x == 0x20202020) return 0;
if ((x & 0x00FFFFFF) == 0x00202020) return x & 0xFF000000;
if ((x & 0x0000FFFF) == 0x00002020) return x & 0xFFFF0000;
if ((x & 0x000000FF) == 0x00000020) return x & 0xFFFFFF00;
return x;
}
gr_feature_val* gr_face_featureval_for_lang(const gr_face* pFace, gr_uint32 langname/*0 means clone default*/) //clones the features. if none for language, clones the default
{
assert(pFace);
langname = zeropad(langname);
return static_cast<gr_feature_val *>(pFace->theSill().cloneFeatures(langname));
}
const gr_feature_ref* gr_face_find_fref(const gr_face* pFace, gr_uint32 featId) //When finished with the FeatureRef, call destroy_FeatureRef
{
assert(pFace);
featId = zeropad(featId);
const FeatureRef* pRef = pFace->featureById(featId);
return static_cast<const gr_feature_ref*>(pRef);
}
unsigned short gr_face_n_fref(const gr_face* pFace)
{
assert(pFace);
return pFace->numFeatures();
}
const gr_feature_ref* gr_face_fref(const gr_face* pFace, gr_uint16 i) //When finished with the FeatureRef, call destroy_FeatureRef
{
assert(pFace);
const FeatureRef* pRef = pFace->feature(i);
return static_cast<const gr_feature_ref*>(pRef);
}
unsigned short gr_face_n_languages(const gr_face* pFace)
{
assert(pFace);
return pFace->theSill().numLanguages();
}
gr_uint32 gr_face_lang_by_index(const gr_face* pFace, gr_uint16 i)
{
assert(pFace);
return pFace->theSill().getLangName(i);
}
void gr_face_destroy(gr_face *face)
{
delete static_cast<Face*>(face);
}
gr_uint16 gr_face_name_lang_for_locale(gr_face *face, const char * locale)
{
if (face)
{
return face->languageForLocale(locale);
}
return 0;
}
unsigned short gr_face_n_glyphs(const gr_face* pFace)
{
return pFace->glyphs().numGlyphs();
}
const gr_faceinfo *gr_face_info(const gr_face *pFace, gr_uint32 script)
{
if (!pFace) return 0;
const Silf *silf = pFace->chooseSilf(script);
if (silf) return silf->silfInfo();
return 0;
}
int gr_face_is_char_supported(const gr_face* pFace, gr_uint32 usv, gr_uint32 script)
{
const Cmap & cmap = pFace->cmap();
gr_uint16 gid = cmap[usv];
if (!gid)
{
const Silf * silf = pFace->chooseSilf(script);
gid = silf->findPseudo(usv);
}
return (gid != 0);
}
#ifndef GRAPHITE2_NFILEFACE
gr_face* gr_make_file_face(const char *filename, unsigned int faceOptions)
{
FileFace* pFileFace = new FileFace(filename);
if (*pFileFace)
{
gr_face* pRes = gr_make_face_with_ops(pFileFace, &FileFace::ops, faceOptions);
if (pRes)
{
pRes->takeFileFace(pFileFace); //takes ownership
return pRes;
}
}
//error when loading
delete pFileFace;
return NULL;
}
#ifndef GRAPHITE2_NSEGCACHE
gr_face* gr_make_file_face_with_seg_cache(const char* filename, unsigned int segCacheMaxSize, unsigned int faceOptions) //returns NULL on failure. //TBD better error handling
//when finished with, call destroy_face
{
FileFace* pFileFace = new FileFace(filename);
if (*pFileFace)
{
gr_face * pRes = gr_make_face_with_seg_cache_and_ops(pFileFace, &FileFace::ops, segCacheMaxSize, faceOptions);
if (pRes)
{
pRes->takeFileFace(pFileFace); //takes ownership
return pRes;
}
}
//error when loading
delete pFileFace;
return NULL;
}
#endif
#endif //!GRAPHITE2_NFILEFACE
} // extern "C"
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_656_2 |
crossvul-cpp_data_bad_393_0 | #include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <utility>
#include <vector>
#include "Emscripten/Emscripten.h"
#include "IR/Module.h"
#include "IR/Operators.h"
#include "IR/Types.h"
#include "IR/Validate.h"
#include "IR/Value.h"
#include "Inline/BasicTypes.h"
#include "Inline/CLI.h"
#include "Inline/Errors.h"
#include "Inline/Hash.h"
#include "Inline/HashMap.h"
#include "Inline/Serialization.h"
#include "Inline/Timing.h"
#include "Logging/Logging.h"
#include "Runtime/Linker.h"
#include "Runtime/Runtime.h"
#include "ThreadTest/ThreadTest.h"
#include "WASTParse/WASTParse.h"
using namespace IR;
using namespace Runtime;
struct RootResolver : Resolver
{
Compartment* compartment;
HashMap<std::string, ModuleInstance*> moduleNameToInstanceMap;
RootResolver(Compartment* inCompartment) : compartment(inCompartment) {}
bool resolve(const std::string& moduleName,
const std::string& exportName,
ObjectType type,
Object*& outObject) override
{
auto namedInstance = moduleNameToInstanceMap.get(moduleName);
if(namedInstance)
{
outObject = getInstanceExport(*namedInstance, exportName);
if(outObject)
{
if(isA(outObject, type)) { return true; }
else
{
Log::printf(Log::error,
"Resolved import %s.%s to a %s, but was expecting %s\n",
moduleName.c_str(),
exportName.c_str(),
asString(getObjectType(outObject)).c_str(),
asString(type).c_str());
return false;
}
}
}
Log::printf(Log::error,
"Generated stub for missing import %s.%s : %s\n",
moduleName.c_str(),
exportName.c_str(),
asString(type).c_str());
outObject = getStubObject(exportName, type);
return true;
}
Object* getStubObject(const std::string& exportName, ObjectType type) const
{
// If the import couldn't be resolved, stub it in.
switch(type.kind)
{
case IR::ObjectKind::function:
{
// Generate a function body that just uses the unreachable op to fault if called.
Serialization::ArrayOutputStream codeStream;
OperatorEncoderStream encoder(codeStream);
encoder.unreachable();
encoder.end();
// Generate a module for the stub function.
IR::Module stubModule;
DisassemblyNames stubModuleNames;
stubModule.types.push_back(asFunctionType(type));
stubModule.functions.defs.push_back({{0}, {}, std::move(codeStream.getBytes()), {}});
stubModule.exports.push_back({"importStub", IR::ObjectKind::function, 0});
stubModuleNames.functions.push_back({"importStub: " + exportName, {}, {}});
IR::setDisassemblyNames(stubModule, stubModuleNames);
IR::validateDefinitions(stubModule);
// Instantiate the module and return the stub function instance.
auto stubModuleInstance
= instantiateModule(compartment, compileModule(stubModule), {}, "importStub");
return getInstanceExport(stubModuleInstance, "importStub");
}
case IR::ObjectKind::memory:
{
return asObject(Runtime::createMemory(compartment, asMemoryType(type)));
}
case IR::ObjectKind::table:
{
return asObject(Runtime::createTable(compartment, asTableType(type)));
}
case IR::ObjectKind::global:
{
return asObject(Runtime::createGlobal(
compartment,
asGlobalType(type),
IR::Value(asGlobalType(type).valueType, IR::UntaggedValue())));
}
case IR::ObjectKind::exceptionType:
{
return asObject(
Runtime::createExceptionTypeInstance(asExceptionType(type), "importStub"));
}
default: Errors::unreachable();
};
}
};
struct CommandLineOptions
{
const char* filename = nullptr;
const char* functionName = nullptr;
char** args = nullptr;
bool onlyCheck = false;
bool enableEmscripten = true;
bool enableThreadTest = false;
bool precompiled = false;
};
static int run(const CommandLineOptions& options)
{
IR::Module irModule;
// Load the module.
if(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; }
if(options.onlyCheck) { return EXIT_SUCCESS; }
// Compile the module.
Runtime::Module* module = nullptr;
if(!options.precompiled) { module = Runtime::compileModule(irModule); }
else
{
const UserSection* precompiledObjectSection = nullptr;
for(const UserSection& userSection : irModule.userSections)
{
if(userSection.name == "wavm.precompiled_object")
{
precompiledObjectSection = &userSection;
break;
}
}
if(!precompiledObjectSection)
{
Log::printf(Log::error, "Input file did not contain 'wavm.precompiled_object' section");
return EXIT_FAILURE;
}
else
{
module = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data);
}
}
// Link the module with the intrinsic modules.
Compartment* compartment = Runtime::createCompartment();
Context* context = Runtime::createContext(compartment);
RootResolver rootResolver(compartment);
Emscripten::Instance* emscriptenInstance = nullptr;
if(options.enableEmscripten)
{
emscriptenInstance = Emscripten::instantiate(compartment, irModule);
if(emscriptenInstance)
{
rootResolver.moduleNameToInstanceMap.set("env", emscriptenInstance->env);
rootResolver.moduleNameToInstanceMap.set("asm2wasm", emscriptenInstance->asm2wasm);
rootResolver.moduleNameToInstanceMap.set("global", emscriptenInstance->global);
}
}
if(options.enableThreadTest)
{
ModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment);
rootResolver.moduleNameToInstanceMap.set("threadTest", threadTestInstance);
}
LinkResult linkResult = linkModule(irModule, rootResolver);
if(!linkResult.success)
{
Log::printf(Log::error, "Failed to link module:\n");
for(auto& missingImport : linkResult.missingImports)
{
Log::printf(Log::error,
"Missing import: module=\"%s\" export=\"%s\" type=\"%s\"\n",
missingImport.moduleName.c_str(),
missingImport.exportName.c_str(),
asString(missingImport.type).c_str());
}
return EXIT_FAILURE;
}
// Instantiate the module.
ModuleInstance* moduleInstance = instantiateModule(
compartment, module, std::move(linkResult.resolvedImports), options.filename);
if(!moduleInstance) { return EXIT_FAILURE; }
// Call the module start function, if it has one.
FunctionInstance* startFunction = getStartFunction(moduleInstance);
if(startFunction) { invokeFunctionChecked(context, startFunction, {}); }
if(options.enableEmscripten)
{
// Call the Emscripten global initalizers.
Emscripten::initializeGlobals(context, irModule, moduleInstance);
}
// Look up the function export to call.
FunctionInstance* functionInstance;
if(!options.functionName)
{
functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "main"));
if(!functionInstance)
{ functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "_main")); }
if(!functionInstance)
{
Log::printf(Log::error, "Module does not export main function\n");
return EXIT_FAILURE;
}
}
else
{
functionInstance
= asFunctionNullable(getInstanceExport(moduleInstance, options.functionName));
if(!functionInstance)
{
Log::printf(Log::error, "Module does not export '%s'\n", options.functionName);
return EXIT_FAILURE;
}
}
FunctionType functionType = getFunctionType(functionInstance);
// Set up the arguments for the invoke.
std::vector<Value> invokeArgs;
if(!options.functionName)
{
if(functionType.params().size() == 2)
{
MemoryInstance* defaultMemory = Runtime::getDefaultMemory(moduleInstance);
if(!defaultMemory)
{
Log::printf(
Log::error,
"Module does not declare a default memory object to put arguments in.\n");
return EXIT_FAILURE;
}
std::vector<const char*> argStrings;
argStrings.push_back(options.filename);
char** args = options.args;
while(*args) { argStrings.push_back(*args++); };
Emscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);
}
else if(functionType.params().size() > 0)
{
Log::printf(Log::error,
"WebAssembly function requires %" PRIu64
" argument(s), but only 0 or 2 can be passed!",
functionType.params().size());
return EXIT_FAILURE;
}
}
else
{
for(U32 i = 0; options.args[i]; ++i)
{
Value value;
switch(functionType.params()[i])
{
case ValueType::i32: value = (U32)atoi(options.args[i]); break;
case ValueType::i64: value = (U64)atol(options.args[i]); break;
case ValueType::f32: value = (F32)atof(options.args[i]); break;
case ValueType::f64: value = atof(options.args[i]); break;
case ValueType::v128:
case ValueType::anyref:
case ValueType::anyfunc:
Errors::fatalf("Cannot parse command-line argument for %s function parameter",
asString(functionType.params()[i]));
default: Errors::unreachable();
}
invokeArgs.push_back(value);
}
}
// Invoke the function.
Timing::Timer executionTimer;
IR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs);
Timing::logTimer("Invoked function", executionTimer);
if(options.functionName)
{
Log::printf(Log::debug,
"%s returned: %s\n",
options.functionName,
asString(functionResults).c_str());
return EXIT_SUCCESS;
}
else if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32)
{
return functionResults[0].i32;
}
else
{
return EXIT_SUCCESS;
}
}
static void showHelp()
{
Log::printf(Log::error,
"Usage: wavm [switches] [programfile] [--] [arguments]\n"
" in.wast|in.wasm Specify program file (.wast/.wasm)\n"
" -c|--check Exit after checking that the program is valid\n"
" -d|--debug Write additional debug information to stdout\n"
" -f|--function name Specify function name to run in module rather than main\n"
" -h|--help Display this message\n"
" --disable-emscripten Disable Emscripten intrinsics\n"
" --enable-thread-test Enable ThreadTest intrinsics\n"
" --precompiled Use precompiled object code in programfile\n"
" -- Stop parsing arguments\n");
}
int main(int argc, char** argv)
{
CommandLineOptions options;
options.args = argv;
while(*++options.args)
{
if(!strcmp(*options.args, "--function") || !strcmp(*options.args, "-f"))
{
if(!*++options.args)
{
showHelp();
return EXIT_FAILURE;
}
options.functionName = *options.args;
}
else if(!strcmp(*options.args, "--check") || !strcmp(*options.args, "-c"))
{
options.onlyCheck = true;
}
else if(!strcmp(*options.args, "--debug") || !strcmp(*options.args, "-d"))
{
Log::setCategoryEnabled(Log::debug, true);
}
else if(!strcmp(*options.args, "--disable-emscripten"))
{
options.enableEmscripten = false;
}
else if(!strcmp(*options.args, "--enable-thread-test"))
{
options.enableThreadTest = true;
}
else if(!strcmp(*options.args, "--precompiled"))
{
options.precompiled = true;
}
else if(!strcmp(*options.args, "--"))
{
++options.args;
break;
}
else if(!strcmp(*options.args, "--help") || !strcmp(*options.args, "-h"))
{
showHelp();
return EXIT_SUCCESS;
}
else if(!options.filename)
{
options.filename = *options.args;
}
else
{
break;
}
}
if(!options.filename)
{
showHelp();
return EXIT_FAILURE;
}
// Treat any unhandled exception (e.g. in a thread) as a fatal error.
Runtime::setUnhandledExceptionHandler([](Runtime::Exception&& exception) {
Errors::fatalf("Runtime exception: %s\n", describeException(exception).c_str());
});
return run(options);
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_393_0 |
crossvul-cpp_data_good_4037_1 | /*
* Copyright (C) 2004-2020 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gmock/gmock.h>
#include "znctest.h"
using testing::HasSubstr;
namespace znc_inttest {
namespace {
TEST(Config, AlreadyExists) {
QTemporaryDir dir;
WriteConfig(dir.path());
Process p(ZNC_BIN_DIR "/znc", QStringList() << "--debug"
<< "--datadir" << dir.path()
<< "--makeconf");
p.ReadUntil("already exists");
p.CanDie();
}
TEST_F(ZNCTest, Connect) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.ReadUntil("CAP LS");
auto client = ConnectClient();
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
client.ReadUntil("Welcome");
client.Close();
client = ConnectClient();
client.Write("PASS :user:hunter2");
client.Write("NICK nick");
client.Write("USER u x x x");
client.ReadUntil("Welcome");
client.Close();
client = ConnectClient();
client.Write("NICK nick");
client.Write("USER user x x x");
client.ReadUntil("Configure your client to send a server password");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("WHO");
}
TEST_F(ZNCTest, Channel) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.ReadUntil("Welcome");
client.Write("JOIN #znc");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc");
ircd.Write(":nick JOIN :#znc");
ircd.Write(":server 353 nick #znc :nick");
ircd.Write(":server 366 nick #znc :End of /NAMES list");
ircd.Write(":server PING :1");
ircd.ReadUntil("PONG 1");
client = LoginClient();
client.ReadUntil(":nick JOIN :#znc");
}
TEST_F(ZNCTest, HTTP) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto reply = HttpGet(QNetworkRequest(QUrl("http://127.0.0.1:12345/")));
EXPECT_THAT(reply->rawHeader("Server").toStdString(), HasSubstr("ZNC"));
}
TEST_F(ZNCTest, FixCVE20149403) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.Write(":server 005 nick CHANTYPES=# :supports");
ircd.Write(":server PING :1");
ircd.ReadUntil("PONG 1");
QNetworkRequest request;
request.setRawHeader("Authorization",
"Basic " + QByteArray("user:hunter2").toBase64());
request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
HttpPost(request, {
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "znc"},
{"enabled", "1"},
});
EXPECT_THAT(HttpPost(request,
{
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "znc"},
{"enabled", "1"},
})
->readAll()
.toStdString(),
HasSubstr("Channel [#znc] already exists"));
}
TEST_F(ZNCTest, FixFixOfCVE20149403) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.Write(":nick JOIN @#znc");
ircd.ReadUntil("MODE @#znc");
ircd.Write(":server 005 nick STATUSMSG=@ :supports");
ircd.Write(":server PING :12345");
ircd.ReadUntil("PONG 12345");
QNetworkRequest request;
request.setRawHeader("Authorization",
"Basic " + QByteArray("user:hunter2").toBase64());
request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
auto reply = HttpPost(request, {
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "@#znc"},
{"enabled", "1"},
});
EXPECT_THAT(reply->readAll().toStdString(),
HasSubstr("Could not add channel [@#znc]"));
}
TEST_F(ZNCTest, InvalidConfigInChan) {
QFile conf(m_dir.path() + "/configs/znc.conf");
ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
QTextStream out(&conf);
out << R"(
<User foo>
<Network bar>
<Chan #baz>
Invalid = Line
</Chan>
</Network>
</User>
)";
out.flush();
auto znc = Run();
znc->ShouldFinishItself(1);
}
TEST_F(ZNCTest, Encoding) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
ircd.Write(":server 001 nick :hello");
// legacy
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xE6world");
client.Write("PRIVMSG *controlpanel :SetNetwork Encoding $me $net UTF-8");
client.ReadUntil("Encoding = UTF-8");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xEF\xBF\xBDworld");
client.Write(
"PRIVMSG *controlpanel :SetNetwork Encoding $me $net ^CP-1251");
client.ReadUntil("Encoding = ^CP-1251");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xD0\xB6world");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xD0\xB6world");
client.ReadUntil("Hello\xD0\xB6world");
}
TEST_F(ZNCTest, BuildMod) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
QTemporaryDir srcd;
QDir srcdir(srcd.path());
QFile file(srcdir.filePath("testmod.cpp"));
ASSERT_TRUE(file.open(QIODevice::WriteOnly | QIODevice::Text));
QTextStream out(&file);
out << R"(
#include <znc/Modules.h>
class TestModule : public CModule {
public:
MODCONSTRUCTOR(TestModule) {}
void OnModCommand(const CString& sLine) override {
PutModule("Lorem ipsum");
}
};
MODULEDEFS(TestModule, "Test")
)";
file.close();
QDir dir(m_dir.path());
EXPECT_TRUE(dir.mkdir("modules"));
EXPECT_TRUE(dir.cd("modules"));
{
Process p(ZNC_BIN_DIR "/znc-buildmod",
QStringList() << srcdir.filePath("file-not-found.cpp"),
[&](QProcess* proc) {
proc->setWorkingDirectory(dir.absolutePath());
proc->setProcessChannelMode(QProcess::ForwardedChannels);
});
p.ShouldFinishItself(1);
p.ShouldFinishInSec(300);
}
{
Process p(ZNC_BIN_DIR "/znc-buildmod",
QStringList() << srcdir.filePath("testmod.cpp"),
[&](QProcess* proc) {
proc->setWorkingDirectory(dir.absolutePath());
proc->setProcessChannelMode(QProcess::ForwardedChannels);
});
p.ShouldFinishItself();
p.ShouldFinishInSec(300);
}
client.Write("znc loadmod testmod");
client.Write("PRIVMSG *testmod :hi");
client.ReadUntil("Lorem ipsum");
}
TEST_F(ZNCTest, AwayNotify) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = ConnectClient();
client.Write("CAP LS");
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
QByteArray cap_ls;
client.ReadUntilAndGet(" LS :", cap_ls);
ASSERT_THAT(cap_ls.toStdString(),
AllOf(HasSubstr("cap-notify"), Not(HasSubstr("away-notify"))));
client.Write("CAP REQ :cap-notify");
client.ReadUntil("ACK :cap-notify");
client.Write("CAP END");
client.ReadUntil(" 001 ");
ircd.ReadUntil("USER");
ircd.Write("CAP user LS :away-notify");
ircd.ReadUntil("CAP REQ :away-notify");
ircd.Write("CAP user ACK :away-notify");
ircd.ReadUntil("CAP END");
ircd.Write(":server 001 user :welcome");
client.ReadUntil("CAP user NEW :away-notify");
client.Write("CAP REQ :away-notify");
client.ReadUntil("ACK :away-notify");
ircd.Write(":x!y@z AWAY :reason");
client.ReadUntil(":x!y@z AWAY :reason");
ircd.Close();
client.ReadUntil("DEL :away-notify");
// This test often fails on macos due to ZNC process not finishing.
// No idea why. Let's try to shutdown it more explicitly...
client.Write("znc shutdown");
}
TEST_F(ZNCTest, JoinKey) {
QFile conf(m_dir.path() + "/configs/znc.conf");
ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
QTextStream(&conf) << "ServerThrottle = 1\n";
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
ircd.Write(":server 001 nick :Hello");
client.Write("JOIN #znc secret");
ircd.ReadUntil("JOIN #znc secret");
ircd.Write(":nick JOIN :#znc");
client.ReadUntil("JOIN :#znc");
ircd.Close();
ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc secret");
}
TEST_F(ZNCTest, StatusEchoMessage) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("CAP REQ :echo-message");
client.Write("PRIVMSG *status :blah");
client.ReadUntil(":nick!user@irc.znc.in PRIVMSG *status :blah");
client.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command");
client.Write("znc delnetwork test");
client.ReadUntil("Network deleted");
auto client2 = LoginClient();
client2.Write("PRIVMSG *status :blah2");
client2.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command");
auto client3 = LoginClient();
client3.Write("PRIVMSG *status :blah3");
client3.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command");
}
} // namespace
} // namespace znc_inttest
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_4037_1 |
crossvul-cpp_data_bad_2609_2 | /*****************************************************************
|
| AP4 - File Processor
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4Processor.h"
#include "Ap4AtomSampleTable.h"
#include "Ap4MovieFragment.h"
#include "Ap4FragmentSampleTable.h"
#include "Ap4TfhdAtom.h"
#include "Ap4AtomFactory.h"
#include "Ap4Movie.h"
#include "Ap4Array.h"
#include "Ap4Sample.h"
#include "Ap4TrakAtom.h"
#include "Ap4TfraAtom.h"
#include "Ap4TrunAtom.h"
#include "Ap4TrexAtom.h"
#include "Ap4TkhdAtom.h"
#include "Ap4SidxAtom.h"
#include "Ap4DataBuffer.h"
#include "Ap4Debug.h"
/*----------------------------------------------------------------------
| types
+---------------------------------------------------------------------*/
struct AP4_SampleLocator {
AP4_SampleLocator() :
m_TrakIndex(0),
m_SampleTable(NULL),
m_SampleIndex(0),
m_ChunkIndex(0) {}
AP4_Ordinal m_TrakIndex;
AP4_AtomSampleTable* m_SampleTable;
AP4_Ordinal m_SampleIndex;
AP4_Ordinal m_ChunkIndex;
AP4_Sample m_Sample;
};
struct AP4_SampleCursor {
AP4_SampleCursor() : m_EndReached(false) {}
AP4_SampleLocator m_Locator;
bool m_EndReached;
};
struct AP4_AtomLocator {
AP4_AtomLocator(AP4_Atom* atom, AP4_UI64 offset) :
m_Atom(atom),
m_Offset(offset) {}
AP4_Atom* m_Atom;
AP4_UI64 m_Offset;
};
/*----------------------------------------------------------------------
| AP4_DefaultFragmentHandler
+---------------------------------------------------------------------*/
class AP4_DefaultFragmentHandler: public AP4_Processor::FragmentHandler {
public:
AP4_DefaultFragmentHandler(AP4_Processor::TrackHandler* track_handler) :
m_TrackHandler(track_handler) {}
AP4_Result ProcessSample(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out);
private:
AP4_Processor::TrackHandler* m_TrackHandler;
};
/*----------------------------------------------------------------------
| AP4_DefaultFragmentHandler::ProcessSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_DefaultFragmentHandler::ProcessSample(AP4_DataBuffer& data_in, AP4_DataBuffer& data_out)
{
if (m_TrackHandler == NULL) {
data_out.SetData(data_in.GetData(), data_in.GetDataSize());
return AP4_SUCCESS;
}
return m_TrackHandler->ProcessSample(data_in, data_out);
}
/*----------------------------------------------------------------------
| FragmentMapEntry
+---------------------------------------------------------------------*/
typedef struct {
AP4_UI64 before;
AP4_UI64 after;
} FragmentMapEntry;
/*----------------------------------------------------------------------
| FindFragmentMapEntry
+---------------------------------------------------------------------*/
static const FragmentMapEntry*
FindFragmentMapEntry(AP4_Array<FragmentMapEntry>& fragment_map, AP4_UI64 fragment_offset) {
int first = 0;
int last = fragment_map.ItemCount();
while (first < last) {
int middle = (last+first)/2;
AP4_UI64 middle_value = fragment_map[middle].before;
if (fragment_offset < middle_value) {
last = middle;
} else if (fragment_offset > middle_value) {
first = middle+1;
} else {
return &fragment_map[middle];
}
}
return NULL;
}
/*----------------------------------------------------------------------
| AP4_Processor::ProcessFragments
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::ProcessFragments(AP4_MoovAtom* moov,
AP4_List<AP4_AtomLocator>& atoms,
AP4_ContainerAtom* mfra,
AP4_SidxAtom* sidx,
AP4_Position sidx_position,
AP4_ByteStream& input,
AP4_ByteStream& output)
{
unsigned int fragment_index = 0;
AP4_Array<FragmentMapEntry> fragment_map;
for (AP4_List<AP4_AtomLocator>::Item* item = atoms.FirstItem();
item;
item = item->GetNext(), ++fragment_index) {
AP4_AtomLocator* locator = item->GetData();
AP4_Atom* atom = locator->m_Atom;
AP4_UI64 atom_offset = locator->m_Offset;
AP4_UI64 mdat_payload_offset = atom_offset+atom->GetSize()+AP4_ATOM_HEADER_SIZE;
AP4_Sample sample;
AP4_DataBuffer sample_data_in;
AP4_DataBuffer sample_data_out;
AP4_Result result;
// if this is not a moof atom, just write it back and continue
if (atom->GetType() != AP4_ATOM_TYPE_MOOF) {
result = atom->Write(output);
if (AP4_FAILED(result)) return result;
continue;
}
// parse the moof
AP4_ContainerAtom* moof = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
AP4_MovieFragment* fragment = new AP4_MovieFragment(moof);
// process all the traf atoms
AP4_Array<AP4_Processor::FragmentHandler*> handlers;
AP4_Array<AP4_FragmentSampleTable*> sample_tables;
for (;AP4_Atom* child = moof->GetChild(AP4_ATOM_TYPE_TRAF, handlers.ItemCount());) {
AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, child);
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
// find the 'trak' for this track
AP4_TrakAtom* trak = NULL;
for (AP4_List<AP4_Atom>::Item* child_item = moov->GetChildren().FirstItem();
child_item;
child_item = child_item->GetNext()) {
AP4_Atom* child_atom = child_item->GetData();
if (child_atom->GetType() == AP4_ATOM_TYPE_TRAK) {
trak = AP4_DYNAMIC_CAST(AP4_TrakAtom, child_atom);
if (trak) {
AP4_TkhdAtom* tkhd = AP4_DYNAMIC_CAST(AP4_TkhdAtom, trak->GetChild(AP4_ATOM_TYPE_TKHD));
if (tkhd && tkhd->GetTrackId() == tfhd->GetTrackId()) {
break;
}
}
trak = NULL;
}
}
// find the 'trex' for this track
AP4_ContainerAtom* mvex = NULL;
AP4_TrexAtom* trex = NULL;
mvex = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->GetChild(AP4_ATOM_TYPE_MVEX));
if (mvex) {
for (AP4_List<AP4_Atom>::Item* child_item = mvex->GetChildren().FirstItem();
child_item;
child_item = child_item->GetNext()) {
AP4_Atom* child_atom = child_item->GetData();
if (child_atom->GetType() == AP4_ATOM_TYPE_TREX) {
trex = AP4_DYNAMIC_CAST(AP4_TrexAtom, child_atom);
if (trex && trex->GetTrackId() == tfhd->GetTrackId()) {
break;
}
trex = NULL;
}
}
}
// create the handler for this traf
AP4_Processor::FragmentHandler* handler = CreateFragmentHandler(trak, trex, traf, input, atom_offset);
if (handler) {
result = handler->ProcessFragment();
if (AP4_FAILED(result)) return result;
}
handlers.Append(handler);
// create a sample table object so we can read the sample data
AP4_FragmentSampleTable* sample_table = NULL;
result = fragment->CreateSampleTable(moov, tfhd->GetTrackId(), &input, atom_offset, mdat_payload_offset, 0, sample_table);
if (AP4_FAILED(result)) return result;
sample_tables.Append(sample_table);
// let the handler look at the samples before we process them
if (handler) result = handler->PrepareForSamples(sample_table);
if (AP4_FAILED(result)) return result;
}
// write the moof
AP4_UI64 moof_out_start = 0;
output.Tell(moof_out_start);
moof->Write(output);
// remember the location of this fragment
FragmentMapEntry map_entry = {atom_offset, moof_out_start};
fragment_map.Append(map_entry);
// write an mdat header
AP4_Position mdat_out_start;
AP4_UI64 mdat_size = AP4_ATOM_HEADER_SIZE;
output.Tell(mdat_out_start);
output.WriteUI32(0);
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
// process all track runs
for (unsigned int i=0; i<handlers.ItemCount(); i++) {
AP4_Processor::FragmentHandler* handler = handlers[i];
// get the track ID
AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moof->GetChild(AP4_ATOM_TYPE_TRAF, i));
if (traf == NULL) continue;
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
// compute the base data offset
AP4_UI64 base_data_offset;
if (tfhd->GetFlags() & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {
base_data_offset = mdat_out_start+AP4_ATOM_HEADER_SIZE;
} else {
base_data_offset = moof_out_start;
}
// build a list of all trun atoms
AP4_Array<AP4_TrunAtom*> truns;
for (AP4_List<AP4_Atom>::Item* child_item = traf->GetChildren().FirstItem();
child_item;
child_item = child_item->GetNext()) {
AP4_Atom* child_atom = child_item->GetData();
if (child_atom->GetType() == AP4_ATOM_TYPE_TRUN) {
AP4_TrunAtom* trun = AP4_DYNAMIC_CAST(AP4_TrunAtom, child_atom);
truns.Append(trun);
}
}
AP4_Ordinal trun_index = 0;
AP4_Ordinal trun_sample_index = 0;
AP4_TrunAtom* trun = truns[0];
trun->SetDataOffset((AP4_SI32)((mdat_out_start+mdat_size)-base_data_offset));
// write the mdat
for (unsigned int j=0; j<sample_tables[i]->GetSampleCount(); j++, trun_sample_index++) {
// advance the trun index if necessary
if (trun_sample_index >= trun->GetEntries().ItemCount()) {
trun = truns[++trun_index];
trun->SetDataOffset((AP4_SI32)((mdat_out_start+mdat_size)-base_data_offset));
trun_sample_index = 0;
}
// get the next sample
result = sample_tables[i]->GetSample(j, sample);
if (AP4_FAILED(result)) return result;
sample.ReadData(sample_data_in);
// process the sample data
if (handler) {
result = handler->ProcessSample(sample_data_in, sample_data_out);
if (AP4_FAILED(result)) return result;
// write the sample data
result = output.Write(sample_data_out.GetData(), sample_data_out.GetDataSize());
if (AP4_FAILED(result)) return result;
// update the mdat size
mdat_size += sample_data_out.GetDataSize();
// update the trun entry
trun->UseEntries()[trun_sample_index].sample_size = sample_data_out.GetDataSize();
} else {
// write the sample data (unmodified)
result = output.Write(sample_data_in.GetData(), sample_data_in.GetDataSize());
if (AP4_FAILED(result)) return result;
// update the mdat size
mdat_size += sample_data_in.GetDataSize();
}
}
if (handler) {
// update the tfhd header
if (tfhd->GetFlags() & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {
tfhd->SetBaseDataOffset(mdat_out_start+AP4_ATOM_HEADER_SIZE);
}
if (tfhd->GetFlags() & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) {
tfhd->SetDefaultSampleSize(trun->GetEntries()[0].sample_size);
}
// give the handler a chance to update the atoms
handler->FinishFragment();
}
}
// update the mdat header
AP4_Position mdat_out_end;
output.Tell(mdat_out_end);
#if defined(AP4_DEBUG)
AP4_ASSERT(mdat_out_end-mdat_out_start == mdat_size);
#endif
output.Seek(mdat_out_start);
output.WriteUI32((AP4_UI32)mdat_size);
output.Seek(mdat_out_end);
// update the moof if needed
output.Seek(moof_out_start);
moof->Write(output);
output.Seek(mdat_out_end);
// update the sidx if we have one
if (sidx && fragment_index < sidx->GetReferences().ItemCount()) {
if (fragment_index == 0) {
sidx->SetFirstOffset(moof_out_start-(sidx_position+sidx->GetSize()));
}
AP4_LargeSize fragment_size = mdat_out_end-moof_out_start;
AP4_SidxAtom::Reference& sidx_ref = sidx->UseReferences()[fragment_index];
sidx_ref.m_ReferencedSize = (AP4_UI32)fragment_size;
}
// cleanup
delete fragment;
for (unsigned int i=0; i<handlers.ItemCount(); i++) {
delete handlers[i];
}
for (unsigned int i=0; i<sample_tables.ItemCount(); i++) {
delete sample_tables[i];
}
}
// update the mfra if we have one
if (mfra) {
for (AP4_List<AP4_Atom>::Item* mfra_item = mfra->GetChildren().FirstItem();
mfra_item;
mfra_item = mfra_item->GetNext()) {
if (mfra_item->GetData()->GetType() != AP4_ATOM_TYPE_TFRA) continue;
AP4_TfraAtom* tfra = AP4_DYNAMIC_CAST(AP4_TfraAtom, mfra_item->GetData());
if (tfra == NULL) continue;
AP4_Array<AP4_TfraAtom::Entry>& entries = tfra->GetEntries();
AP4_Cardinal entry_count = entries.ItemCount();
for (unsigned int i=0; i<entry_count; i++) {
const FragmentMapEntry* found = FindFragmentMapEntry(fragment_map, entries[i].m_MoofOffset);
if (found) {
entries[i].m_MoofOffset = found->after;
}
}
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Processor::CreateFragmentHandler
+---------------------------------------------------------------------*/
AP4_Processor::FragmentHandler*
AP4_Processor::CreateFragmentHandler(AP4_TrakAtom* /* trak */,
AP4_TrexAtom* /* trex */,
AP4_ContainerAtom* traf,
AP4_ByteStream& /* moof_data */,
AP4_Position /* moof_offset */)
{
// find the matching track handler
for (unsigned int i=0; i<m_TrackIds.ItemCount(); i++) {
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
if (tfhd && m_TrackIds[i] == tfhd->GetTrackId()) {
return new AP4_DefaultFragmentHandler(m_TrackHandlers[i]);
}
}
return NULL;
}
/*----------------------------------------------------------------------
| AP4_Processor::Process
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Process(AP4_ByteStream& input,
AP4_ByteStream& output,
AP4_ByteStream* fragments,
ProgressListener* listener,
AP4_AtomFactory& atom_factory)
{
// read all atoms.
// keep all atoms except [mdat]
// keep a ref to [moov]
// put [moof] atoms in a separate list
AP4_AtomParent top_level;
AP4_MoovAtom* moov = NULL;
AP4_ContainerAtom* mfra = NULL;
AP4_SidxAtom* sidx = NULL;
AP4_List<AP4_AtomLocator> frags;
AP4_UI64 stream_offset = 0;
bool in_fragments = false;
unsigned int sidx_count = 0;
for (AP4_Atom* atom = NULL;
AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(input, atom));
input.Tell(stream_offset)) {
if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {
delete atom;
continue;
} else if (atom->GetType() == AP4_ATOM_TYPE_MOOV) {
moov = AP4_DYNAMIC_CAST(AP4_MoovAtom, atom);
if (fragments) break;
} else if (atom->GetType() == AP4_ATOM_TYPE_MFRA) {
mfra = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
continue;
} else if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {
// don't keep the index, it is likely to be invalidated, we will recompute it later
++sidx_count;
if (sidx == NULL) {
sidx = AP4_DYNAMIC_CAST(AP4_SidxAtom, atom);
} else {
delete atom;
continue;
}
} else if (atom->GetType() == AP4_ATOM_TYPE_SSIX) {
// don't keep the index, it is likely to be invalidated
delete atom;
continue;
} else if (!fragments && (in_fragments || atom->GetType() == AP4_ATOM_TYPE_MOOF)) {
in_fragments = true;
frags.Add(new AP4_AtomLocator(atom, stream_offset));
continue;
}
top_level.AddChild(atom);
}
// check that we have at most one sidx (we can't deal with multi-sidx streams here
if (sidx_count > 1) {
top_level.RemoveChild(sidx);
delete sidx;
sidx = NULL;
}
// if we have a fragments stream, get the fragment locators from there
if (fragments) {
stream_offset = 0;
for (AP4_Atom* atom = NULL;
AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(*fragments, atom));
fragments->Tell(stream_offset)) {
if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {
delete atom;
continue;
}
frags.Add(new AP4_AtomLocator(atom, stream_offset));
}
}
// initialize the processor
AP4_Result result = Initialize(top_level, input);
if (AP4_FAILED(result)) return result;
// process the tracks if we have a moov atom
AP4_Array<AP4_SampleLocator> locators;
AP4_Cardinal track_count = 0;
AP4_List<AP4_TrakAtom>* trak_atoms = NULL;
AP4_LargeSize mdat_payload_size = 0;
AP4_SampleCursor* cursors = NULL;
if (moov) {
// build an array of track sample locators
trak_atoms = &moov->GetTrakAtoms();
track_count = trak_atoms->ItemCount();
cursors = new AP4_SampleCursor[track_count];
m_TrackHandlers.SetItemCount(track_count);
m_TrackIds.SetItemCount(track_count);
for (AP4_Ordinal i=0; i<track_count; i++) {
m_TrackHandlers[i] = NULL;
m_TrackIds[i] = 0;
}
unsigned int index = 0;
for (AP4_List<AP4_TrakAtom>::Item* item = trak_atoms->FirstItem(); item; item=item->GetNext()) {
AP4_TrakAtom* trak = item->GetData();
// find the stsd atom
AP4_ContainerAtom* stbl = AP4_DYNAMIC_CAST(AP4_ContainerAtom, trak->FindChild("mdia/minf/stbl"));
if (stbl == NULL) continue;
// see if there's an external data source for this track
AP4_ByteStream* trak_data_stream = &input;
for (AP4_List<ExternalTrackData>::Item* ditem = m_ExternalTrackData.FirstItem(); ditem; ditem=ditem->GetNext()) {
ExternalTrackData* tdata = ditem->GetData();
if (tdata->m_TrackId == trak->GetId()) {
trak_data_stream = tdata->m_MediaData;
break;
}
}
// create the track handler
m_TrackHandlers[index] = CreateTrackHandler(trak);
m_TrackIds[index] = trak->GetId();
cursors[index].m_Locator.m_TrakIndex = index;
cursors[index].m_Locator.m_SampleTable = new AP4_AtomSampleTable(stbl, *trak_data_stream);
cursors[index].m_Locator.m_SampleIndex = 0;
cursors[index].m_Locator.m_ChunkIndex = 0;
if (cursors[index].m_Locator.m_SampleTable->GetSampleCount()) {
cursors[index].m_Locator.m_SampleTable->GetSample(0, cursors[index].m_Locator.m_Sample);
} else {
cursors[index].m_EndReached = true;
}
index++;
}
// figure out the layout of the chunks
for (;;) {
// see which is the next sample to write
AP4_UI64 min_offset = (AP4_UI64)(-1);
int cursor = -1;
for (unsigned int i=0; i<track_count; i++) {
if (!cursors[i].m_EndReached &&
cursors[i].m_Locator.m_Sample.GetOffset() <= min_offset) {
min_offset = cursors[i].m_Locator.m_Sample.GetOffset();
cursor = i;
}
}
// stop if all cursors are exhausted
if (cursor == -1) break;
// append this locator to the layout list
AP4_SampleLocator& locator = cursors[cursor].m_Locator;
locators.Append(locator);
// move the cursor to the next sample
locator.m_SampleIndex++;
if (locator.m_SampleIndex == locator.m_SampleTable->GetSampleCount()) {
// mark this track as completed
cursors[cursor].m_EndReached = true;
} else {
// get the next sample info
locator.m_SampleTable->GetSample(locator.m_SampleIndex, locator.m_Sample);
AP4_Ordinal skip, sdesc;
locator.m_SampleTable->GetChunkForSample(locator.m_SampleIndex,
locator.m_ChunkIndex,
skip, sdesc);
}
}
// update the stbl atoms and compute the mdat size
int current_track = -1;
int current_chunk = -1;
AP4_Position current_chunk_offset = 0;
AP4_Size current_chunk_size = 0;
for (AP4_Ordinal i=0; i<locators.ItemCount(); i++) {
AP4_SampleLocator& locator = locators[i];
if ((int)locator.m_TrakIndex != current_track ||
(int)locator.m_ChunkIndex != current_chunk) {
// start a new chunk for this track
current_chunk_offset += current_chunk_size;
current_chunk_size = 0;
current_track = locator.m_TrakIndex;
current_chunk = locator.m_ChunkIndex;
locator.m_SampleTable->SetChunkOffset(locator.m_ChunkIndex, current_chunk_offset);
}
AP4_Size sample_size;
TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];
if (handler) {
sample_size = handler->GetProcessedSampleSize(locator.m_Sample);
locator.m_SampleTable->SetSampleSize(locator.m_SampleIndex, sample_size);
} else {
sample_size = locator.m_Sample.GetSize();
}
current_chunk_size += sample_size;
mdat_payload_size += sample_size;
}
// process the tracks (ex: sample descriptions processing)
for (AP4_Ordinal i=0; i<track_count; i++) {
TrackHandler* handler = m_TrackHandlers[i];
if (handler) handler->ProcessTrack();
}
}
// finalize the processor
Finalize(top_level);
if (!fragments) {
// calculate the size of all atoms combined
AP4_UI64 atoms_size = 0;
top_level.GetChildren().Apply(AP4_AtomSizeAdder(atoms_size));
// see if we need a 64-bit or 32-bit mdat
AP4_Size mdat_header_size = AP4_ATOM_HEADER_SIZE;
if (mdat_payload_size+mdat_header_size > 0xFFFFFFFF) {
// we need a 64-bit size
mdat_header_size += 8;
}
// adjust the chunk offsets
for (AP4_Ordinal i=0; i<track_count; i++) {
AP4_TrakAtom* trak;
trak_atoms->Get(i, trak);
trak->AdjustChunkOffsets(atoms_size+mdat_header_size);
}
// write all atoms
top_level.GetChildren().Apply(AP4_AtomListWriter(output));
// write mdat header
if (mdat_payload_size) {
if (mdat_header_size == AP4_ATOM_HEADER_SIZE) {
// 32-bit size
output.WriteUI32((AP4_UI32)(mdat_header_size+mdat_payload_size));
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
} else {
// 64-bit size
output.WriteUI32(1);
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
output.WriteUI64(mdat_header_size+mdat_payload_size);
}
}
}
// write the samples
if (moov) {
if (!fragments) {
#if defined(AP4_DEBUG)
AP4_Position before;
output.Tell(before);
#endif
AP4_Sample sample;
AP4_DataBuffer data_in;
AP4_DataBuffer data_out;
for (unsigned int i=0; i<locators.ItemCount(); i++) {
AP4_SampleLocator& locator = locators[i];
locator.m_Sample.ReadData(data_in);
TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];
if (handler) {
result = handler->ProcessSample(data_in, data_out);
if (AP4_FAILED(result)) return result;
output.Write(data_out.GetData(), data_out.GetDataSize());
} else {
output.Write(data_in.GetData(), data_in.GetDataSize());
}
// notify the progress listener
if (listener) {
listener->OnProgress(i+1, locators.ItemCount());
}
}
#if defined(AP4_DEBUG)
AP4_Position after;
output.Tell(after);
AP4_ASSERT(after-before == mdat_payload_size);
#endif
}
// find the position of the sidx atom
AP4_Position sidx_position = 0;
if (sidx) {
for (AP4_List<AP4_Atom>::Item* item = top_level.GetChildren().FirstItem();
item;
item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {
break;
}
sidx_position += atom->GetSize();
}
}
// process the fragments, if any
result = ProcessFragments(moov, frags, mfra, sidx, sidx_position, fragments?*fragments:input, output);
if (AP4_FAILED(result)) return result;
// update and re-write the sidx if we have one
if (sidx && sidx_position) {
AP4_Position where = 0;
output.Tell(where);
output.Seek(sidx_position);
result = sidx->Write(output);
if (AP4_FAILED(result)) return result;
output.Seek(where);
}
if (!fragments) {
// write the mfra atom at the end if we have one
if (mfra) {
mfra->Write(output);
}
}
// cleanup
for (AP4_Ordinal i=0; i<track_count; i++) {
delete cursors[i].m_Locator.m_SampleTable;
delete m_TrackHandlers[i];
}
m_TrackHandlers.Clear();
delete[] cursors;
}
// cleanup
frags.DeleteReferences();
delete mfra;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Processor::Process
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Process(AP4_ByteStream& input,
AP4_ByteStream& output,
ProgressListener* listener,
AP4_AtomFactory& atom_factory)
{
return Process(input, output, NULL, listener, atom_factory);
}
/*----------------------------------------------------------------------
| AP4_Processor::Process
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Process(AP4_ByteStream& fragments,
AP4_ByteStream& output,
AP4_ByteStream& init,
ProgressListener* listener,
AP4_AtomFactory& atom_factory)
{
return Process(init, output, &fragments, listener, atom_factory);
}
/*----------------------------------------------------------------------
| AP4_Processor:Initialize
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Initialize(AP4_AtomParent& /* top_level */,
AP4_ByteStream& /* stream */,
ProgressListener* /* listener */)
{
// default implementation: do nothing
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Processor:Finalize
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Finalize(AP4_AtomParent& /* top_level */,
ProgressListener* /* listener */ )
{
// default implementation: do nothing
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Processor::TrackHandler Dynamic Cast Anchor
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR_S(AP4_Processor::TrackHandler, TrackHandler)
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_2609_2 |
crossvul-cpp_data_good_3266_0 | /*
*
* (C) 2013-17 - ntop.org
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include "ntop_includes.h"
#ifndef _GETOPT_H
#define _GETOPT_H
#endif
#ifndef LIB_VERSION
#define LIB_VERSION "1.4.7"
#endif
extern "C" {
#include "rrd.h"
#ifdef HAVE_GEOIP
extern const char * GeoIP_lib_version(void);
#endif
#include "../third-party/snmp/snmp.c"
#include "../third-party/snmp/asn1.c"
#include "../third-party/snmp/net.c"
};
#include "../third-party/lsqlite3/lsqlite3.c"
struct keyval string_to_replace[MAX_NUM_HTTP_REPLACEMENTS] = { { NULL, NULL } };
/* ******************************* */
Lua::Lua() {
L = luaL_newstate();
if(L == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "Unable to create Lua interpreter");
return;
}
}
/* ******************************* */
Lua::~Lua() {
if(L) lua_close(L);
}
/* ******************************* */
/**
* @brief Check the expected type of lua function.
* @details Find in the lua stack the function and check the function parameters types.
*
* @param vm The lua state.
* @param func The function name.
* @param pos Index of lua stack.
* @param expected_type Index of expected type.
* @return @ref CONST_LUA_ERROR if the expected type is equal to function type, @ref CONST_LUA_PARAM_ERROR otherwise.
*/
int ntop_lua_check(lua_State* vm, const char* func, int pos, int expected_type) {
if(lua_type(vm, pos) != expected_type) {
ntop->getTrace()->traceEvent(TRACE_ERROR,
"%s : expected %s, got %s", func,
lua_typename(vm, expected_type),
lua_typename(vm, lua_type(vm,pos)));
return(CONST_LUA_PARAM_ERROR);
}
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static void get_host_vlan_info(char* lua_ip, char** host_ip,
u_int16_t* vlan_id,
char *buf, u_int buf_len) {
char *where, *vlan = NULL;
snprintf(buf, buf_len, "%s", lua_ip);
if(((*host_ip) = strtok_r(buf, "@", &where)) != NULL)
vlan = strtok_r(NULL, "@", &where);
if(vlan)
(*vlan_id) = (u_int16_t)atoi(vlan);
}
/* ****************************************** */
static NetworkInterface* handle_null_interface(lua_State* vm) {
char allowed_ifname[MAX_INTERFACE_NAME_LEN];
ntop->getTrace()->traceEvent(TRACE_INFO, "NULL interface: did you restart ntopng in the meantime?");
if(ntop->getInterfaceAllowed(vm, allowed_ifname)) {
return ntop->getNetworkInterface(allowed_ifname);
}
return(ntop->getInterfaceAtId(0));
}
/* ****************************************** */
static int ntop_dump_file(lua_State* vm) {
char *fname;
FILE *fd;
struct mg_connection *conn;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, CONST_HTTP_CONN);
if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection");
return(CONST_LUA_ERROR);
}
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((fname = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->fixPath(fname);
if((fd = fopen(fname, "r")) != NULL) {
char tmp[1024];
ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] Serving file %s", fname);
while((fgets(tmp, sizeof(tmp)-256 /* To make sure we have room for replacements */, fd)) != NULL) {
for(int i=0; string_to_replace[i].key != NULL; i++)
Utils::replacestr(tmp, string_to_replace[i].key, string_to_replace[i].val);
mg_printf(conn, "%s", tmp);
}
fclose(fd);
return(CONST_LUA_OK);
} else {
ntop->getTrace()->traceEvent(TRACE_INFO, "Unable to read file %s", fname);
return(CONST_LUA_ERROR);
}
}
/* ****************************************** */
/**
* @brief Get default interface name.
* @details Push the default interface name of ntop into the lua stack.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK.
*/
static int ntop_get_default_interface_name(lua_State* vm) {
char ifname[MAX_INTERFACE_NAME_LEN];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop->getInterfaceAllowed(vm, ifname)) {
// if there is an allowed interface for the user
// we return that interface
lua_pushstring(vm,
ntop->getNetworkInterface(ifname)->get_name());
} else {
lua_pushstring(vm, ntop->getInterfaceAtId(NULL, /* no need to check as there is no constaint */
0)->get_name());
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Set the name of active interface id into lua stack.
*
* @param vm The lua stack.
* @return @ref CONST_LUA_OK.
*/
static int ntop_set_active_interface_id(lua_State* vm) {
NetworkInterface *iface;
int id;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
id = (u_int32_t)lua_tonumber(vm, 1);
iface = ntop->getNetworkInterface(vm, id);
ntop->getTrace()->traceEvent(TRACE_INFO, "Index: %d, Name: %s", id, iface ? iface->get_name() : "<unknown>");
if(iface != NULL)
lua_pushstring(vm, iface->get_name());
else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the ntopng interface names.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK.
*/
static int ntop_get_interface_names(lua_State* vm) {
lua_newtable(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
for(int i=0; i<ntop->get_num_interfaces(); i++) {
NetworkInterface *iface;
if((iface = ntop->getInterfaceAtId(vm, i)) != NULL) {
char num[8];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "Returning name %s", iface->get_name());
snprintf(num, sizeof(num), "%d", i);
lua_push_str_table_entry(vm, num, iface->get_name());
}
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static AddressTree* get_allowed_nets(lua_State* vm) {
AddressTree *ptree;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, CONST_ALLOWED_NETS);
ptree = (AddressTree*)lua_touserdata(vm, lua_gettop(vm));
//ntop->getTrace()->traceEvent(TRACE_WARNING, "GET %p", ptree);
return(ptree);
}
/* ****************************************** */
static NetworkInterface* getCurrentInterface(lua_State* vm) {
NetworkInterface *ntop_interface;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, "ntop_interface");
if((ntop_interface = (NetworkInterface*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop_interface = handle_null_interface(vm);
}
return(ntop_interface);
}
/* ****************************************** */
/**
* @brief Find the network interface and set it as global variable to lua.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_select_interface(lua_State* vm) {
char *ifname;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TNIL)
ifname = (char*)"any";
else {
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
ifname = (char*)lua_tostring(vm, 1);
}
lua_pushlightuserdata(vm, (char*)ntop->getNetworkInterface(vm, ifname));
lua_setglobal(vm, "ntop_interface");
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the nDPI statistics of interface.
* @details Get the ntop interface global variable of lua, get nDpistats of interface and push it into lua stack.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_ndpi_interface_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
char *host_ip = NULL;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
/* Optional host */
if(lua_type(vm, 1) == LUA_TSTRING) get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if(ntop_interface) {
ntop_interface->getnDPIStats(&stats, get_allowed_nets(vm), host_ip, vlan_id);
lua_newtable(vm);
stats.lua(ntop_interface, vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
#ifdef NTOPNG_PRO
/**
* @brief Get the Host Pool statistics of interface.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_host_pool_interface_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface && ntop_interface->getHostPools()) {
ntop_interface->luaHostPoolsStats(vm);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/**
* @brief Get the Host Pool volatile members
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_host_pool_volatile_members(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface && ntop_interface->getHostPools()) {
ntop_interface->luaHostPoolsVolatileMembers(vm);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
#endif
/* ****************************************** */
/**
* @brief Get the ndpi flows count of interface.
* @details Get the ntop interface global variable of lua, get nDpi flow count of interface and push it into lua stack.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_ndpi_interface_flows_count(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) {
lua_newtable(vm);
ntop_interface->getnDPIFlowsCount(vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the flow status for flows in cache
* @details Get the ntop interface global variable of lua, get flow stats of interface and push it into lua stack.
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK
*/
static int ntop_get_ndpi_interface_flows_status(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) {
lua_newtable(vm);
ntop_interface->getFlowsStatus(vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the ndpi protocol name of protocol id of network interface.
* @details Get the ntop interface global variable of lua. Once do that, get the protocol id of lua stack and return into lua stack "Host-to-Host Contact" if protocol id is equal to host family id; the protocol name or null otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_ndpi_protocol_name(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
int proto;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
proto = (u_int32_t)lua_tonumber(vm, 1);
if(proto == HOST_FAMILY_ID)
lua_pushstring(vm, "Host-to-Host Contact");
else {
if(ntop_interface)
lua_pushstring(vm, ntop_interface->get_ndpi_proto_name(proto));
else
lua_pushnil(vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_ndpi_protocol_id(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
char *proto;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
proto = (char*)lua_tostring(vm, 1);
if(ntop_interface && proto)
lua_pushnumber(vm, ntop_interface->get_ndpi_proto_id(proto));
else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_ndpi_protocol_category(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int proto;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
proto = (u_int)lua_tonumber(vm, 1);
if(ntop_interface) {
ndpi_protocol_category_t category = ntop_interface->get_ndpi_proto_category(proto);
lua_newtable(vm);
lua_push_int32_table_entry(vm, "id", category);
lua_push_str_table_entry(vm, "name", (char*)ndpi_category_str(category));
} else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Same as ntop_get_ndpi_protocol_name() with the exception that the protocol breed is returned
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_ndpi_protocol_breed(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
nDPIStats stats;
int proto;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
proto = (u_int32_t)lua_tonumber(vm, 1);
if(proto == HOST_FAMILY_ID)
lua_pushstring(vm, "Unrated-to-Host Contact");
else {
if(ntop_interface)
lua_pushstring(vm, ntop_interface->get_ndpi_proto_breed_name(proto));
else
lua_pushnil(vm);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_hosts(lua_State* vm, LocationPolicy location) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool show_details = true;
char *sortColumn = (char*)"column_ip", *country = NULL, *os_filter = NULL, *mac_filter = NULL;
bool a2zSortOrder = true;
u_int16_t vlan_filter, *vlan_filter_ptr = NULL;
u_int32_t asn_filter, *asn_filter_ptr = NULL;
int16_t network_filter, *network_filter_ptr = NULL;
u_int16_t pool_filter, *pool_filter_ptr = NULL;
u_int32_t toSkip = 0, maxHits = CONST_MAX_NUM_HITS;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TBOOLEAN) show_details = lua_toboolean(vm, 1) ? true : false;
if(lua_type(vm, 2) == LUA_TSTRING) sortColumn = (char*)lua_tostring(vm, 2);
if(lua_type(vm, 3) == LUA_TNUMBER) maxHits = (u_int16_t)lua_tonumber(vm, 3);
if(lua_type(vm, 4) == LUA_TNUMBER) toSkip = (u_int16_t)lua_tonumber(vm, 4);
if(lua_type(vm, 5) == LUA_TBOOLEAN) a2zSortOrder = lua_toboolean(vm, 5) ? true : false;
if(lua_type(vm, 6) == LUA_TSTRING) country = (char*)lua_tostring(vm, 6);
if(lua_type(vm, 7) == LUA_TSTRING) os_filter = (char*)lua_tostring(vm, 7);
if(lua_type(vm, 8) == LUA_TNUMBER) vlan_filter = (u_int16_t)lua_tonumber(vm, 8), vlan_filter_ptr = &vlan_filter;
if(lua_type(vm, 9) == LUA_TNUMBER) asn_filter = (u_int32_t)lua_tonumber(vm, 9), asn_filter_ptr = &asn_filter;
if(lua_type(vm,10) == LUA_TNUMBER) network_filter = (int16_t)lua_tonumber(vm, 10), network_filter_ptr = &network_filter;
if(lua_type(vm,11) == LUA_TSTRING) mac_filter = (char*)lua_tostring(vm, 11);
if(lua_type(vm,12) == LUA_TNUMBER) pool_filter = (u_int16_t)lua_tonumber(vm, 12), pool_filter_ptr = &pool_filter;
if(!ntop_interface ||
ntop_interface->getActiveHostsList(vm, get_allowed_nets(vm),
show_details, location,
country, mac_filter,
vlan_filter_ptr, os_filter, asn_filter_ptr,
network_filter_ptr, pool_filter_ptr,
sortColumn, maxHits,
toSkip, a2zSortOrder) < 0)
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_latest_activity_hosts_info(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->getLatestActivityHostsList(vm, get_allowed_nets(vm));
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the host information of network interface grouped according to the criteria.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null or the host is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_grouped_interface_hosts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool show_details = true, hostsOnly = true;
char *country = NULL, *os_filter = NULL;
char *groupBy = (char*)"column_ip";
u_int16_t vlan_filter, *vlan_filter_ptr = NULL;
u_int32_t asn_filter, *asn_filter_ptr = NULL;
u_int16_t pool_filter, *pool_filter_ptr = NULL;
int16_t network_filter, *network_filter_ptr = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TBOOLEAN) show_details = lua_toboolean(vm, 1) ? true : false;
if(lua_type(vm, 2) == LUA_TSTRING) groupBy = (char*)lua_tostring(vm, 2);
if(lua_type(vm, 3) == LUA_TSTRING) country = (char*)lua_tostring(vm, 3);
if(lua_type(vm, 4) == LUA_TSTRING) os_filter = (char*)lua_tostring(vm, 4);
if(lua_type(vm, 5) == LUA_TNUMBER) vlan_filter = (u_int16_t)lua_tonumber(vm, 5), vlan_filter_ptr = &vlan_filter;
if(lua_type(vm, 6) == LUA_TNUMBER) asn_filter = (u_int32_t)lua_tonumber(vm, 6), asn_filter_ptr = &asn_filter;
if(lua_type(vm, 7) == LUA_TNUMBER) network_filter = (int16_t)lua_tonumber(vm, 7), network_filter_ptr = &network_filter;
if(lua_type(vm, 8) == LUA_TBOOLEAN) hostsOnly = lua_toboolean(vm, 8) ? true : false;
if(lua_type(vm, 9) == LUA_TNUMBER) pool_filter = (u_int16_t)lua_tonumber(vm, 9), pool_filter_ptr = &pool_filter;
if((!ntop_interface)
|| ntop_interface->getActiveHostsGroup(vm, get_allowed_nets(vm),
show_details, location_all,
country,
vlan_filter_ptr, os_filter,
asn_filter_ptr, network_filter_ptr,
pool_filter_ptr,
hostsOnly, groupBy) < 0)
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the hosts information of network interface.
* @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the host information.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_hosts_info(lua_State* vm) {
return(ntop_get_interface_hosts(vm, location_all));
}
/* ****************************************** */
static int ntop_get_interface_macs_info(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *sortColumn = (char*)"column_mac";
u_int32_t toSkip = 0, maxHits = CONST_MAX_NUM_HITS;
u_int16_t vlan_id = 0;
bool a2zSortOrder = true,
skipSpecialMacs = false, hostMacsOnly = false;
if(lua_type(vm, 1) == LUA_TSTRING) {
sortColumn = (char*)lua_tostring(vm, 1);
if(lua_type(vm, 2) == LUA_TNUMBER) {
maxHits = (u_int16_t)lua_tonumber(vm, 2);
if(lua_type(vm, 3) == LUA_TNUMBER) {
toSkip = (u_int16_t)lua_tonumber(vm, 3);
if(lua_type(vm, 4) == LUA_TBOOLEAN) {
a2zSortOrder = lua_toboolean(vm, 4) ? true : false;
if(lua_type(vm, 5) == LUA_TNUMBER) {
vlan_id = (u_int16_t)lua_tonumber(vm, 5);
if(lua_type(vm, 6) == LUA_TBOOLEAN) {
skipSpecialMacs = lua_toboolean(vm, 6) ? true : false;
}
if(lua_type(vm, 7) == LUA_TBOOLEAN) {
hostMacsOnly = lua_toboolean(vm, 7) ? true : false;
}
}
}
}
}
}
if(!ntop_interface ||
ntop_interface->getActiveMacList(vm, vlan_id, skipSpecialMacs,
hostMacsOnly,
sortColumn, maxHits,
toSkip, a2zSortOrder) < 0)
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_mac_info(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *mac = NULL;
u_int16_t vlan_id = 0;
if(lua_type(vm, 1) == LUA_TSTRING) {
mac = (char*)lua_tostring(vm, 1);
if(lua_type(vm, 2) == LUA_TNUMBER) {
vlan_id = (u_int16_t)lua_tonumber(vm, 2);
}
}
if((!ntop_interface)
|| (!mac)
|| (!ntop_interface->getMacInfo(vm, mac, vlan_id)))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_mac_manufacturer(lua_State* vm) {
const char *mac = NULL;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
mac = (char*)lua_tostring(vm, 1);
ntop->getMacManufacturer(mac, vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_site_categories(lua_State* vm) {
Flashstart *flash = ntop->get_flashstart();
if (!flash)
lua_pushnil(vm);
else
flash->lua(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get local hosts information of network interface.
* @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the local host information.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_local_hosts_info(lua_State* vm) {
return(ntop_get_interface_hosts(vm, location_local_only));
}
/* ****************************************** */
/**
* @brief Get remote hosts information of network interface.
* @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the remote host information.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_remote_hosts_info(lua_State* vm) {
return(ntop_get_interface_hosts(vm, location_remote_only));
}
/* ****************************************** */
/**
* @brief Get local hosts activity information.
* @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the local host activities.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null or host is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_host_activity(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
const char * host = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if (lua_type(vm, 1) == LUA_TSTRING)
host = lua_tostring(vm, 1);
if (ntop_interface == NULL || host == NULL)
return CONST_LUA_ERROR;
ntop_interface->getLocalHostActivity(vm, host);
return CONST_LUA_OK;
}
/* ****************************************** */
/**
* @brief Check if the specified path is a directory and it exists.
* @details True if if the specified path is a directory and it exists, false otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_OK
*/
static int ntop_is_dir(lua_State* vm) {
char *path;
struct stat buf;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
rc = ((stat(path, &buf) != 0) || (!S_ISDIR(buf.st_mode))) ? 0 : 1;
lua_pushboolean(vm, rc);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if the file is exists and is not empty
* @details Simple check for existance + non empty file
*
* @param vm The lua state.
* @return CONST_LUA_OK
*/
static int ntop_is_not_empty_file(lua_State* vm) {
char *path;
struct stat buf;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
rc = (stat(path, &buf) != 0) ? 0 : 1;
if(rc && (buf.st_size == 0)) rc = 0;
lua_pushboolean(vm, rc);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if the file or directory exists.
* @details Get the path of file/directory from to lua stack and push true into lua stack if it exists, false otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_OK
*/
static int ntop_get_file_dir_exists(lua_State* vm) {
char *path;
struct stat buf;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
rc = (stat(path, &buf) != 0) ? 0 : 1;
// ntop->getTrace()->traceEvent(TRACE_ERROR, "%s: %d", path, rc);
lua_pushboolean(vm, rc);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Return the epoch of the file last change
* @details This function return that time (epoch) of the last chnge on a file, or -1 if the file does not exist.
*
* @param vm The lua state.
* @return CONST_LUA_OK
*/
static int ntop_get_file_last_change(lua_State* vm) {
char *path;
struct stat buf;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
if(stat(path, &buf) == 0)
lua_pushnumber(vm, (lua_Number)buf.st_mtime);
else
lua_pushnumber(vm, -1); /* not found */
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if ntop has seen VLAN tagged packets on this interface.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_has_vlans(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface)
lua_pushboolean(vm, ntop_interface->hasSeenVlanTaggedPackets());
else
lua_pushboolean(vm, 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if ntop has loaded ASN information (via GeoIP)
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_has_geoip(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm, ntop->getGeolocation() ? 1 : 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if ntop is running on windows.
* @details Push into lua stack 1 if ntop is running on windows, 0 otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_is_windows(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm,
#ifdef WIN32
1
#else
0
#endif
);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_allocHostBlacklist(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->allocHostBlacklist();
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_swapHostBlacklist(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->swapHostBlacklist();
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_addToHostBlacklist(lua_State* vm) {
char *net;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
net = (char*)lua_tostring(vm, 1);
ntop->addToHostBlacklist(net);
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Wrapper for the libc call getservbyport()
* @details Wrapper for the libc call getservbyport()
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_getservbyport(lua_State* vm) {
int port;
char *proto;
struct servent *s = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
port = (int)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
proto = (char*)lua_tostring(vm, 2);
if((port > 0) && (proto != NULL))
s = getservbyport(htons(port), proto);
if(s && s->s_name)
lua_pushstring(vm, s->s_name);
else {
char buf[32];
snprintf(buf, sizeof(buf), "%d", port);
lua_pushstring(vm, buf);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Scan the input directory and return the list of files.
* @details Get the path from the lua stack and push into a new hashtable the files name existing in the directory.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_list_dir_files(lua_State* vm) {
char *path;
DIR *dirp;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
ntop->fixPath(path);
lua_newtable(vm);
if((dirp = opendir(path)) != NULL) {
struct dirent *dp;
while ((dp = readdir(dirp)) != NULL)
if((dp->d_name[0] != '\0')
&& (dp->d_name[0] != '.')) {
lua_push_str_table_entry(vm, dp->d_name, dp->d_name);
}
(void)closedir(dirp);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
/* Adapted from http://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c */
static int remove_recursively(const char * path) {
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;
size_t len;
char *buf;
if (d) {
struct dirent *p;
r = 0;
while ((r==0) && (p=readdir(d))) {
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
continue;
len = path_len + strlen(p->d_name) + 2;
buf = (char *) malloc(len);
if (buf) {
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (stat(buf, &statbuf) == 0) {
if (S_ISDIR(statbuf.st_mode))
r = remove_recursively(buf);
else
r = unlink(buf);
}
free(buf);
}
}
closedir(d);
}
if (r == 0)
r = rmdir(path);
return r;
}
/**
* @brief Scan the input directory, removes it and its contets.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_remove_dir_recursively(lua_State* vm) {
char *path;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
path = (char*)lua_tostring(vm, 1);
ntop->fixPath(path);
remove_recursively(path);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the system time and push it into the lua stack.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_gettimemsec(lua_State* vm) {
struct timeval tp;
double ret;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
gettimeofday(&tp, NULL);
ret = (((double)tp.tv_usec) / (double)1000) + tp.tv_sec;
lua_pushnumber(vm, ret);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Lua-equivaled ot C inet_ntoa
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_inet_ntoa(lua_State* vm) {
u_int32_t ip;
struct in_addr in;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TSTRING)
ip = atol((char*)lua_tostring(vm, 1));
else if(lua_type(vm, 1) == LUA_TNUMBER)
ip = (u_int32_t)lua_tonumber(vm, 1);
else
return(CONST_LUA_ERROR);
in.s_addr = htonl(ip);
lua_pushstring(vm, inet_ntoa(in));
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_zmq_connect(lua_State* vm) {
char *endpoint, *topic;
void *context, *subscriber;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((endpoint = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((topic = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
context = zmq_ctx_new(), subscriber = zmq_socket(context, ZMQ_SUB);
if(zmq_connect(subscriber, endpoint) != 0) {
zmq_close(subscriber);
zmq_ctx_destroy(context);
return(CONST_LUA_PARAM_ERROR);
}
if(zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, topic, strlen(topic)) != 0) {
zmq_close(subscriber);
zmq_ctx_destroy(context);
return -1;
}
lua_pushlightuserdata(vm, context);
lua_setglobal(vm, "zmq_context");
lua_pushlightuserdata(vm, subscriber);
lua_setglobal(vm, "zmq_subscriber");
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Delete the specified member(field) from the redis hash stored at key.
* @details Get the key parameter from the lua stack and delete it from redis.
*
* @param vm The lua stack.
* @return CONST_LUA_OK.
*/
static int ntop_delete_redis_key(lua_State* vm) {
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->getRedis()->del(key);
return(CONST_LUA_OK);
}
/* ****************************************** */
/* ****************************************** */
/**
* @brief Add a member to the a redis set.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_add_set_member_redis(lua_State* vm) {
char *key, *value;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if (ntop->getRedis()->sadd(key, value) == 0)
return(CONST_LUA_OK);
else
return(CONST_LUA_ERROR);
}
/**
* @brief Removes a member from a redis set.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_del_set_member_redis(lua_State* vm) {
char *key, *value;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if (ntop->getRedis()->srem(key, value) == 0)
return(CONST_LUA_OK);
else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
/**
* @brief Get the members of a redis set.
* @details Get the set key form the lua stack and push the mambers name into lua stack.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_get_set_members_redis(lua_State* vm) {
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->getRedis()->smembers(vm, key);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Delete the specified member(field) from the redis hash stored at key.
* @details Get the member name and the hash key form the lua stack and remove the specified member.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_delete_hash_redis_key(lua_State* vm) {
char *key, *member;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->getRedis()->hashDel(key, member);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_zmq_disconnect(lua_State* vm) {
void *context, *subscriber;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, "zmq_context");
if((context = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL context");
return(CONST_LUA_ERROR);
}
lua_getglobal(vm, "zmq_subscriber");
if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber");
return(CONST_LUA_ERROR);
}
zmq_close(subscriber);
zmq_ctx_destroy(context);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_zmq_receive(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
void *subscriber;
int size;
struct zmq_msg_hdr h;
char *payload;
int payload_len;
zmq_pollitem_t item;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, "zmq_subscriber");
if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber");
return(CONST_LUA_ERROR);
}
item.socket = subscriber;
item.events = ZMQ_POLLIN;
do {
rc = zmq_poll(&item, 1, 1000);
if(rc < 0 || !ntop_interface->isRunning()) /* CHECK */
return(CONST_LUA_PARAM_ERROR);
} while (rc == 0);
size = zmq_recv(subscriber, &h, sizeof(h), 0);
if(size != sizeof(h) || h.version != ZMQ_MSG_VERSION) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unsupported publisher version [%d]", h.version);
return -1;
}
payload_len = h.size + 1;
if((payload = (char*)malloc(payload_len)) != NULL) {
size = zmq_recv(subscriber, payload, payload_len, 0);
payload[h.size] = '\0';
if(size > 0) {
enum json_tokener_error jerr = json_tokener_success;
json_object *o = json_tokener_parse_verbose(payload, &jerr);
if(o != NULL) {
struct json_object_iterator it = json_object_iter_begin(o);
struct json_object_iterator itEnd = json_object_iter_end(o);
while (!json_object_iter_equal(&it, &itEnd)) {
char *key = (char*)json_object_iter_peek_name(&it);
const char *value = json_object_get_string(json_object_iter_peek_value(&it));
ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%s]=[%s]", key, value);
json_object_iter_next(&it);
}
json_object_put(o);
} else
ntop->getTrace()->traceEvent(TRACE_WARNING, "JSON Parse error [%s]: %s",
json_tokener_error_desc(jerr),
payload);
lua_pushfstring(vm, "%s", payload);
ntop->getTrace()->traceEvent(TRACE_INFO, "[%u] %s", h.size, payload);
free(payload);
return(CONST_LUA_OK);
} else {
free(payload);
return(CONST_LUA_PARAM_ERROR);
}
} else
return(CONST_LUA_PARAM_ERROR);
}
/* ****************************************** */
static int ntop_get_local_networks(lua_State* vm) {
lua_newtable(vm);
ntop->getLocalNetworks(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_reload_preferences(lua_State* vm) {
lua_newtable(vm);
ntop->getPrefs()->reloadPrefsFromRedis();
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Check if the trace level of ntop is verbose.
* @details Push true into the lua stack if the trace level of ntop is set to MAX_TRACE_LEVEL, false otherwise.
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_verbose_trace(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm, (ntop->getTrace()->get_trace_level() == MAX_TRACE_LEVEL) ? true : false);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_send_udp_data(lua_State* vm) {
int rc, port, sockfd = ntop->getUdpSock();
char *host, *data;
if(sockfd == -1)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
host = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
port = (u_int16_t)lua_tonumber(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
data = (char*)lua_tostring(vm, 3);
if(strchr(host, ':') != NULL) {
struct sockaddr_in6 server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin6_family = AF_INET6;
inet_pton(AF_INET6, host, &server_addr.sin6_addr);
server_addr.sin6_port = htons(port);
rc = sendto(sockfd, data, strlen(data),0,
(struct sockaddr *)&server_addr,
sizeof(server_addr));
} else {
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(host); /* FIX: add IPv6 support */
server_addr.sin_port = htons(port);
rc = sendto(sockfd, data, strlen(data),0,
(struct sockaddr *)&server_addr,
sizeof(server_addr));
}
if(rc == -1)
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_flows(lua_State* vm, LocationPolicy location) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char buf[64];
char *host_ip = NULL;
u_int16_t vlan_id = 0;
Host *host = NULL;
Paginator *p = NULL;
int numFlows = -1;
if(!ntop_interface)
return(CONST_LUA_ERROR);
if((p = new(std::nothrow) Paginator()) == NULL)
return(CONST_LUA_ERROR);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TSTRING) {
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
host = ntop_interface->getHost(host_ip, vlan_id);
}
if(lua_type(vm, 2) == LUA_TTABLE)
p->readOptions(vm, 2);
if(ntop_interface)
numFlows = ntop_interface->getFlows(vm, get_allowed_nets(vm), location, host, p);
if(p) delete p;
return numFlows < 0 ? CONST_LUA_ERROR : CONST_LUA_OK;
}
static int ntop_get_interface_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_all)); }
static int ntop_get_interface_local_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_local_only)); }
static int ntop_get_interface_remote_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_remote_only)); }
/* ****************************************** */
/**
* @brief Get nDPI stats for flows
* @details Compute nDPI flow statistics
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_get_interface_flows_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) ntop_interface->getFlowsStats(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get interface stats for local networks
* @details Returns traffic statistics per local network
*
* @param vm The lua state.
* @return CONST_LUA_OK.
*/
static int ntop_get_interface_networks_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) ntop_interface->getNetworksStats(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Get the host information of network interface.
* @details Get the ntop interface global variable of lua, the host ip and optional the VLAN id form the lua stack and push a new hash table of hash tables containing the host information into lua stack.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null or the host is null, CONST_LUA_OK otherwise.
*/
static int ntop_get_interface_host_info(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface) || !ntop_interface->getHostInfo(vm, get_allowed_nets(vm), host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
#ifdef NOTUSED
static int ntop_get_grouped_interface_host(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *country_s = NULL, *os_s = NULL;
u_int16_t vlan_n, *vlan_ptr = NULL;
u_int32_t as_n, *as_ptr = NULL;
int16_t network_n, *network_ptr = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TNUMBER) vlan_n = (u_int16_t)lua_tonumber(vm, 1), vlan_ptr = &vlan_n;
if(lua_type(vm, 2) == LUA_TNUMBER) as_n = (u_int32_t)lua_tonumber(vm, 2), as_ptr = &as_n;
if(lua_type(vm, 3) == LUA_TNUMBER) network_n = (int16_t)lua_tonumber(vm, 3), network_ptr = &network_n;
if(lua_type(vm, 4) == LUA_TSTRING) country_s = (char*)lua_tostring(vm, 4);
if(lua_type(vm, 5) == LUA_TSTRING) os_s = (char*)lua_tostring(vm, 5);
if(!ntop_interface || ntop_interface->getActiveHostsGroup(vm, get_allowed_nets(vm), false, false, country_s, vlan_ptr, os_s, as_ptr,
network_ptr, (char*)"column_ip", (char*)"country", CONST_MAX_NUM_HITS, 0 /* toSkip */, true /* a2zSortOrder */) < 0)
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
#endif
/* ****************************************** */
static int ntop_getflowdevices(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
else {
ntop_interface->getFlowDevices(vm);
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_getflowdeviceinfo(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *device_ip;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
device_ip = (char*)lua_tostring(vm, 1);
if(!ntop_interface)
return(CONST_LUA_ERROR);
else {
in_addr_t addr = inet_addr(device_ip);
ntop_interface->getFlowDeviceInfo(vm, ntohl(addr));
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_interface_load_host_alert_prefs(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface) || !ntop_interface->loadHostAlertPrefs(vm, get_allowed_nets(vm), host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_host_reset_periodic_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->resetPeriodicStats();
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_host_trigger_alerts(lua_State* vm, bool trigger) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER)
vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
if(trigger)
h->enableAlerts();
else
h->disableAlerts();
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_host_enable_alerts(lua_State* vm) {
return ntop_interface_host_trigger_alerts(vm, true);
}
/* ****************************************** */
static int ntop_interface_host_disable_alerts(lua_State* vm) {
return ntop_interface_host_trigger_alerts(vm, false);
}
/* ****************************************** */
static int ntop_interface_refresh_num_alerts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
AlertsManager *am;
Host *h;
char *host_ip;
u_int16_t vlan_id = 0;
u_int32_t num_alerts;
char buf[128];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if((!ntop_interface))
return(CONST_LUA_ERROR);
if(lua_type(vm, 1) == LUA_TSTRING) {
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((h = ntop_interface->getHost(host_ip, vlan_id))) {
if(lua_type(vm, 3) == LUA_TNUMBER) {
num_alerts = (u_int32_t)lua_tonumber(vm, 3);
h->setNumAlerts(num_alerts);
} else {
h->getNumAlerts(true /* From AlertsManager re-reads the values */);
}
}
} else {
if((am = ntop_interface->getAlertsManager()) == NULL)
return(CONST_LUA_ERROR);
am->refreshCachedNumAlerts();
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_correalate_host_activity(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface) || !ntop_interface->correlateHostActivity(vm, get_allowed_nets(vm), host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_similar_host_activity(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface) || !ntop_interface->similarHostActivity(vm, get_allowed_nets(vm), host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_host_activitymap(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
GenericHost *h;
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
h = ntop_interface->getHost(host_ip, vlan_id);
if(h == NULL)
return(CONST_LUA_ERROR);
else {
if(h->match(get_allowed_nets(vm))) {
char *json = h->getJsonActivityMap();
lua_pushfstring(vm, "%s", json);
free(json);
}
return(CONST_LUA_OK);
}
}
/* ****************************************** */
/**
* @brief Restore the host of network interface.
* @details Get the ntop interface global variable of lua and the IP address of host form the lua stack and restore the host into hash host of network interface.
*
* @param vm The lua state.
* @return CONST_LUA_ERROR if ntop_interface is null or if is impossible to restore the host, CONST_LUA_OK otherwise.
*/
static int ntop_restore_interface_host(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
bool skip_privileges_check = false;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* make sure skip privileges check cannot be set from the web interface */
if(lua_type(vm, 2) == LUA_TBOOLEAN) skip_privileges_check = lua_toboolean(vm, 2);
if(!skip_privileges_check && !Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if((!ntop_interface) || !ntop_interface->restoreHost(host_ip, vlan_id))
return(CONST_LUA_ERROR);
else
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_flow_key(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
Host *cli, *srv;
char *cli_name = NULL; u_int16_t cli_vlan = 0; u_int16_t cli_port = 0;
char *srv_name = NULL; u_int16_t srv_vlan = 0; u_int16_t srv_port = 0;
u_int16_t protocol;
char cli_buf[256], srv_buf[256];
if(!ntop_interface)
return(CONST_LUA_ERROR);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING) /* cli_host@cli_vlan */
|| ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER) /* cli port */
|| ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING) /* srv_host@srv_vlan */
|| ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER) /* srv port */
|| ntop_lua_check(vm, __FUNCTION__, 5, LUA_TNUMBER) /* protocol */
) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &cli_name, &cli_vlan, cli_buf, sizeof(cli_buf));
cli_port = htons((u_int16_t)lua_tonumber(vm, 2));
get_host_vlan_info((char*)lua_tostring(vm, 3), &srv_name, &srv_vlan, srv_buf, sizeof(srv_buf));
srv_port = htons((u_int16_t)lua_tonumber(vm, 4));
protocol = (u_int16_t)lua_tonumber(vm, 5);
if(cli_vlan != srv_vlan) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "Client and Server vlans don't match.");
return(CONST_LUA_ERROR);
}
if(cli_name == NULL || srv_name == NULL
||(cli = ntop_interface->getHost(cli_name, cli_vlan)) == NULL
||(srv = ntop_interface->getHost(srv_name, srv_vlan)) == NULL) {
lua_pushnil(vm);
} else {
lua_pushnumber(vm, Flow::key(cli, cli_port, srv, srv_port, cli_vlan, protocol));
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_flow_by_key(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t key;
Flow *f;
AddressTree *ptree = get_allowed_nets(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
key = (u_int32_t)lua_tonumber(vm, 1);
if(!ntop_interface) return(false);
f = ntop_interface->findFlowByKey(key, ptree);
if(f == NULL)
return(CONST_LUA_ERROR);
else {
f->lua(vm, ptree, details_high, false);
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_drop_flow_traffic(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t key;
Flow *f;
AddressTree *ptree = get_allowed_nets(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
key = (u_int32_t)lua_tonumber(vm, 1);
if(!ntop_interface) return(false);
f = ntop_interface->findFlowByKey(key, ptree);
if(f == NULL)
return(CONST_LUA_ERROR);
else {
f->setDropVerdict();
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_dump_flow_traffic(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t key, what;
Flow *f;
AddressTree *ptree = get_allowed_nets(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
key = (u_int32_t)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
what = (u_int32_t)lua_tonumber(vm, 2);
if(!ntop_interface) return(false);
f = ntop_interface->findFlowByKey(key, ptree);
if(f == NULL)
return(CONST_LUA_ERROR);
else {
f->setDumpFlowTraffic(what ? true : false);
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_dump_local_hosts_2_redis(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
ntop_interface->dumpLocalHosts2redis(true /* must disable purge as we are called from lua */);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_user_flows(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
key = (char*)lua_tostring(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findUserFlows(vm, key);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_pid_flows(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t pid;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
pid = (u_int32_t)lua_tonumber(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findPidFlows(vm, pid);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_father_pid_flows(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int32_t father_pid;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
father_pid = (u_int32_t)lua_tonumber(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findFatherPidFlows(vm, father_pid);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_proc_name_flows(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *proc_name;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
proc_name = (char*)lua_tostring(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findProcNameFlows(vm, proc_name);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_list_http_hosts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
if(lua_type(vm, 1) != LUA_TSTRING) /* Optional */
key = NULL;
else
key = (char*)lua_tostring(vm, 1);
ntop_interface->listHTTPHosts(vm, key);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_find_host(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
key = (char*)lua_tostring(vm, 1);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->findHostsByName(vm, get_allowed_nets(vm), key);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_update_host_traffic_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->updateHostTrafficPolicy(host_ip);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_update_host_alert_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->readAlertPrefs();
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_set_second_traffic(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
ntop_interface->updateSecondTraffic(time(NULL));
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_set_host_dump_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
bool dump_traffic_to_disk;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR);
dump_traffic_to_disk = lua_toboolean(vm, 1) ? true : false;
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->setDumpTrafficPolicy(dump_traffic_to_disk);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_host_hit_rate(lua_State* vm) {
#ifdef NOTUSED
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
u_int32_t peer_key;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
peer_key = (u_int32_t)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->getPeerBytes(vm, peer_key);
return(CONST_LUA_OK);
#else
return(CONST_LUA_ERROR); // not supported
#endif
}
/* ****************************************** */
static int ntop_set_host_quota(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
u_int32_t quota;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
quota = (u_int32_t)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf));
/* Optional VLAN id */
if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL))
return(CONST_LUA_ERROR);
h->setQuota(quota);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_tap_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool dump_traffic_to_tap;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
dump_traffic_to_tap = ntop_interface->getDumpTrafficTapPolicy();
lua_pushboolean(vm, dump_traffic_to_tap ? 1 : 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_tap_name(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
lua_pushstring(vm, ntop_interface->getDumpTrafficTapName());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_disk_policy(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool dump_traffic_to_disk;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
dump_traffic_to_disk = ntop_interface->getDumpTrafficDiskPolicy();
lua_pushboolean(vm, dump_traffic_to_disk ? 1 : 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_max_pkts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int max_pkts;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
max_pkts = ntop_interface->getDumpTrafficMaxPktsPerFile();
lua_pushnumber(vm, max_pkts);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_max_sec(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int max_sec;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
max_sec = ntop_interface->getDumpTrafficMaxSecPerFile();
lua_pushnumber(vm, max_sec);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_dump_max_files(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int max_files;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
max_files = ntop_interface->getDumpTrafficMaxFiles();
lua_pushnumber(vm, max_files);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_pkts_dumped_file(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int num_pkts;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
PacketDumper *dumper = ntop_interface->getPacketDumper();
if(!dumper)
return(CONST_LUA_ERROR);
num_pkts = dumper->get_num_dumped_packets();
lua_pushnumber(vm, num_pkts);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_pkts_dumped_tap(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int num_pkts;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
PacketDumperTuntap *dumper = ntop_interface->getPacketDumperTap();
if(!dumper)
return(CONST_LUA_ERROR);
num_pkts = dumper->get_num_dumped_packets();
lua_pushnumber(vm, num_pkts);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_interface_endpoint(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
u_int8_t id;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) != LUA_TNUMBER) /* Optional */
id = 0;
else
id = (u_int8_t)lua_tonumber(vm, 1);
if(ntop_interface) {
char *endpoint = ntop_interface->getEndpoint(id); /* CHECK */
lua_pushfstring(vm, "%s", endpoint ? endpoint : "");
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_is_packet_interface(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
lua_pushboolean(vm, ntop_interface->isPacketInterface());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_is_bridge_interface(lua_State* vm) {
int ifid;
NetworkInterface *iface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if((lua_type(vm, 1) == LUA_TNUMBER)) {
ifid = lua_tointeger(vm, 1);
if(ifid < 0 || !(iface = ntop->getNetworkInterface(ifid)))
return (CONST_LUA_ERROR);
}
lua_pushboolean(vm, iface->is_bridge_interface());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_is_pcap_dump_interface(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
const char *interface_type;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface
|| ((interface_type = ntop_interface->get_type()) == NULL))
return(CONST_LUA_ERROR);
lua_pushboolean(vm, strcmp(interface_type, CONST_INTERFACE_TYPE_PCAP_DUMP) == 0);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_is_running(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
return(ntop_interface->isRunning());
}
/* ****************************************** */
static int ntop_interface_is_idle(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
return(ntop_interface->idle());
}
/* ****************************************** */
static int ntop_interface_set_idle(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool state;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR);
state = lua_toboolean(vm, 1) ? true : false;
ntop_interface->setIdleState(state);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_name2id(lua_State* vm) {
char *if_name;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TNIL)
if_name = NULL;
else {
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if_name = (char*)lua_tostring(vm, 1);
}
lua_pushinteger(vm, ntop->getInterfaceIdByName(if_name));
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_ndpi_protocols(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ndpi_protocol_category_t category_filter;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if((lua_type(vm, 1) == LUA_TNUMBER)) {
category_filter = (ndpi_protocol_category_t)lua_tointeger(vm, 1);
if(category_filter >= NDPI_PROTOCOL_NUM_CATEGORIES)
return (CONST_LUA_ERROR);
ntop_interface->getnDPIProtocols(vm, category_filter);
} else
ntop_interface->getnDPIProtocols(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_ndpi_categories(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_newtable(vm);
for (int i=0; i < NDPI_PROTOCOL_NUM_CATEGORIES; i++) {
char buf[8];
snprintf(buf, sizeof(buf), "%d", i);
lua_push_str_table_entry(vm, ndpi_category_str((ndpi_protocol_category_t)i), buf);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_load_dump_prefs(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop_interface->loadDumpPrefs();
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_load_scaling_factor_prefs(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop_interface->loadScalingFactorPrefs();
return(CONST_LUA_OK);
}
/* ****************************************** */
/*
Code partially taken from third-party/rrdtool-1.4.7/bindings/lua/rrdlua.c
and made reentrant
*/
static void reset_rrd_state(void) {
optind = 0;
opterr = 0;
rrd_clear_error();
}
/* ****************************************** */
static const char **make_argv(lua_State * vm, u_int offset) {
const char **argv;
int i;
int argc = lua_gettop(vm) - offset;
if(!(argv = (const char**)calloc(argc, sizeof (char *))))
/* raise an error and never return */
luaL_error(vm, "Can't allocate memory for arguments array");
/* fprintf(stderr, "%s\n", argv[0]); */
for(i=0; i<argc; i++) {
u_int idx = i + offset;
/* accepts string or number */
if(lua_isstring(vm, idx) || lua_isnumber(vm, idx)) {
if(!(argv[i] = (char*)lua_tostring (vm, idx))) {
/* raise an error and never return */
luaL_error(vm, "Error duplicating string area for arg #%d", i);
}
} else {
/* raise an error and never return */
luaL_error(vm, "Invalid arg #%d: args must be strings or numbers", i);
}
// ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%d] %s", i, argv[i]);
}
return(argv);
}
/* ****************************************** */
static int ntop_rrd_create(lua_State* vm) {
const char *filename;
unsigned long pdp_step;
const char **argv;
int argc, status, offset = 3;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
pdp_step = (unsigned long)lua_tonumber(vm, 2);
ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename);
argc = lua_gettop(vm) - offset;
argv = make_argv(vm, offset);
reset_rrd_state();
status = rrd_create_r(filename, pdp_step, time(NULL)-86400 /* 1 day */, argc, argv);
free(argv);
if(status != 0) {
char *err = rrd_get_error();
if(err != NULL) {
luaL_error(vm, err);
return(CONST_LUA_ERROR);
}
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_rrd_update(lua_State* vm) {
const char *filename, *update_arg;
int status;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((update_arg = (const char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s(%s) %s", __FUNCTION__, filename, update_arg);
reset_rrd_state();
status = rrd_update_r(filename, NULL, 1, &update_arg);
if(status != 0) {
char *err = rrd_get_error();
if(err != NULL) {
luaL_error(vm, err);
return(CONST_LUA_ERROR);
}
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_rrd_lastupdate(lua_State* vm) {
const char *filename;
time_t last_update;
char **ds_names;
char **last_ds;
unsigned long ds_count, i;
int status;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
status = rrd_lastupdate_r(filename, &last_update, &ds_count, &ds_names, &last_ds);
if(status != 0) {
return(CONST_LUA_ERROR);
} else {
for(i = 0; i < ds_count; i++)
free(last_ds[i]), free(ds_names[i]);
free(last_ds), free(ds_names);
lua_pushnumber(vm, last_update);
lua_pushnumber(vm, ds_count);
return(2 /* 2 values returned */);
}
}
/* ****************************************** */
/* positional 1:4 parameters for ntop_rrd_fetch */
static int __ntop_rrd_args (lua_State* vm, char **filename, char **cf, time_t *start, time_t *end) {
char *start_s, *end_s, *err;
rrd_time_value_t start_tv, end_tv;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((*filename = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((*cf = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((lua_type(vm, 3) == LUA_TNUMBER) && (lua_type(vm, 4) == LUA_TNUMBER))
*start = (time_t)lua_tonumber(vm, 3), *end = (time_t)lua_tonumber(vm, 4);
else {
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((start_s = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((err = rrd_parsetime(start_s, &start_tv)) != NULL) {
luaL_error(vm, err);
return(CONST_LUA_PARAM_ERROR);
}
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((end_s = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((err = rrd_parsetime(end_s, &end_tv)) != NULL) {
luaL_error(vm, err);
return(CONST_LUA_PARAM_ERROR);
}
if(rrd_proc_start_end(&start_tv, &end_tv, start, end) == -1)
return(CONST_LUA_PARAM_ERROR);
}
return(CONST_LUA_OK);
}
static int __ntop_rrd_status(lua_State* vm, int status, char *filename, char *cf) {
char * err;
if(status != 0) {
err = rrd_get_error();
if(err != NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR,
"Error '%s' while calling rrd_fetch_r(%s, %s): is the RRD corrupted perhaps?",
err, filename, cf);
lua_pushnil(vm);
lua_pushnil(vm);
lua_pushnil(vm);
lua_pushnil(vm);
return(CONST_LUA_ERROR);
}
}
return(CONST_LUA_OK);
}
/* Fetches data from RRD by rows */
static int ntop_rrd_fetch(lua_State* vm) {
unsigned long i, j, step = 0, ds_cnt = 0;
rrd_value_t *data, *p;
char **names;
char *filename, *cf;
time_t t, start, end;
int status;
if ((status = __ntop_rrd_args(vm, &filename, &cf, &start, &end)) != CONST_LUA_OK) return status;
ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename);
reset_rrd_state();
if ((status = __ntop_rrd_status(vm, rrd_fetch_r(filename, cf, &start, &end, &step, &ds_cnt, &names, &data), filename, cf)) != CONST_LUA_OK) return status;
lua_pushnumber(vm, (lua_Number) start);
lua_pushnumber(vm, (lua_Number) step);
/* fprintf(stderr, "%lu, %lu, %lu, %lu\n", start, end, step, num_points); */
/* create the ds names array */
lua_newtable(vm);
for(i=0; i<ds_cnt; i++) {
lua_pushstring(vm, names[i]);
lua_rawseti(vm, -2, i+1);
rrd_freemem(names[i]);
}
rrd_freemem(names);
/* create the data points array */
lua_newtable(vm);
p = data;
for(t=start+1, i=0; t<end; t+=step, i++) {
lua_newtable(vm);
for(j=0; j<ds_cnt; j++) {
rrd_value_t value = *p++;
if(value != DNAN /* Skip NaN */) {
lua_pushnumber(vm, (lua_Number)value);
lua_rawseti(vm, -2, j+1);
// ntop->getTrace()->traceEvent(TRACE_NORMAL, "%u / %.f", t, value);
}
}
lua_rawseti(vm, -2, i+1);
}
rrd_freemem(data);
/* return the end as the last value */
lua_pushnumber(vm, (lua_Number) end);
/* number of return values: start, step, names, data, end */
return(5);
}
/* ****************************************** */
/*
* Similar to ntop_rrd_fetch, but data series oriented (reads RRD by columns)
*
* Positional parameters:
* filename: RRD file path
* cf: RRD cf
* start: the start time you wish to query
* end: the end time you wish to query
*
* Positional return values:
* start: the time of the first data in the series
* step: the fetched data step
* data: a table, where each key is an RRD name, and the value is its series data
* end: the time of the last data in each series
* npoints: the number of points in each series
*/
static int ntop_rrd_fetch_columns(lua_State* vm) {
char *filename, *cf;
time_t start, end;
int status;
unsigned int npoints = 0, i, j;
char **names;
unsigned long step = 0, ds_cnt = 0;
rrd_value_t *data, *p;
if ((status = __ntop_rrd_args(vm, &filename, &cf, &start, &end)) != CONST_LUA_OK) return status;
ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename);
reset_rrd_state();
if ((status = __ntop_rrd_status(vm, rrd_fetch_r(filename, cf, &start, &end, &step, &ds_cnt, &names, &data), filename, cf)) != CONST_LUA_OK) return status;
npoints = (end - start) / step;
lua_pushnumber(vm, (lua_Number) start);
lua_pushnumber(vm, (lua_Number) step);
/* create the data series table */
lua_createtable(vm, 0, ds_cnt);
for(i=0; i<ds_cnt; i++) {
/* a single serie table, preallocated */
lua_createtable(vm, npoints, 0);
p = data + i;
for(j=0; j<npoints; j++) {
rrd_value_t value = *p;
/* we are accessing data table by columns */
p = p + ds_cnt;
lua_pushnumber(vm, (lua_Number)value);
lua_rawseti(vm, -2, j+1);
}
/* add the single serie to the series table */
lua_setfield(vm, -2, names[i]);
rrd_freemem(names[i]);
}
rrd_freemem(names);
rrd_freemem(data);
/* end and npoints as last values */
lua_pushnumber(vm, (lua_Number) end);
lua_pushnumber(vm, (lua_Number) npoints);
/* number of return values */
return(5);
}
/* ****************************************** */
static int ntop_http_redirect(lua_State* vm) {
char *url, str[512];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((url = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
snprintf(str, sizeof(str), "HTTP/1.1 302 Found\r\n"
"Location: %s\r\n\r\n"
"<html>\n"
"<head>\n"
"<title>Moved</title>\n"
"</head>\n"
"<body>\n"
"<h1>Moved</h1>\n"
"<p>This page has moved to <a href=\"%s\">%s</a>.</p>\n"
"</body>\n"
"</html>\n", url, url, url);
lua_pushstring(vm, str);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_http_get(lua_State* vm) {
char *url, *username = NULL, *pwd = NULL;
int timeout = 30;
bool return_content = true;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((url = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 2) == LUA_TSTRING) {
username = (char*)lua_tostring(vm, 2);
if(lua_type(vm, 3) == LUA_TSTRING) {
pwd = (char*)lua_tostring(vm, 3);
if(lua_type(vm, 4) == LUA_TNUMBER) {
timeout = lua_tointeger(vm, 4);
if(timeout < 1) timeout = 1;
/*
This optional parameter specifies if the result of HTTP GET has to be returned
to LUA or not. Usually the content has to be returned, but in some causes
it just matters to time (for instance when use for testing HTTP services)
*/
if(lua_type(vm, 4) == LUA_TBOOLEAN) {
return_content = lua_toboolean(vm, 5) ? true : false;
}
}
}
}
if(Utils::httpGet(vm, url, username, pwd, timeout, return_content))
return(CONST_LUA_OK);
else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_http_get_prefix(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushstring(vm, ntop->getPrefs()->get_http_prefix());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_prefs(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->getPrefs()->lua(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_nologin_username(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushstring(vm, NTOP_NOLOGIN_USER);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_users(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->getUsers(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_user_group(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->getUserGroup(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_allowed_networks(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
ntop->getAllowedNetworks(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_reset_user_password(lua_State* vm) {
char *who, *username, *old_password, *new_password;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
/* Username who requested the password change */
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((who = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((old_password = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((new_password = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((!Utils::isUserAdministrator(vm)) && (strcmp(who, username)))
return(CONST_LUA_ERROR);
return(ntop->resetUserPassword(username, old_password, new_password));
}
/* ****************************************** */
static int ntop_change_user_role(lua_State* vm) {
char *username, *user_role;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((user_role = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->changeUserRole(username, user_role);
}
/* ****************************************** */
static int ntop_change_allowed_nets(lua_State* vm) {
char *username, *allowed_nets;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((allowed_nets = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->changeAllowedNets(username, allowed_nets);
}
/* ****************************************** */
static int ntop_change_allowed_ifname(lua_State* vm) {
char *username, *allowed_ifname;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((allowed_ifname = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->changeAllowedIfname(username, allowed_ifname);
}
/* ****************************************** */
static int ntop_change_user_host_pool(lua_State* vm) {
char *username, *host_pool_id;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((host_pool_id = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->changeUserHostPool(username, host_pool_id);
}
/* ****************************************** */
static int ntop_post_http_json_data(lua_State* vm) {
char *username, *password, *url, *json;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((password = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((url = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((json = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(Utils::postHTTPJsonData(username, password, url, json))
return(CONST_LUA_OK);
else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_add_user(lua_State* vm) {
char *username, *full_name, *password, *host_role, *allowed_networks, *allowed_interface, *host_pool_id = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((full_name = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((password = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((host_role = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((allowed_networks = (char*)lua_tostring(vm, 5)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 6, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((allowed_interface = (char*)lua_tostring(vm, 6)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 7) == LUA_TSTRING)
if((host_pool_id = (char*)lua_tostring(vm, 7)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->addUser(username, full_name, password, host_role,
allowed_networks, allowed_interface, host_pool_id);
}
/* ****************************************** */
static int ntop_add_user_lifetime(lua_State* vm) {
char *username;
int32_t num_secs;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_PARAM_ERROR);
num_secs = (int32_t)lua_tonumber(vm, 2);
if(num_secs > 0)
return ntop->addUserLifetime(username, num_secs) ? CONST_LUA_OK : CONST_LUA_ERROR;
return CONST_LUA_OK; /* Negative or zero lifetimes means unlimited */
}
/* ****************************************** */
static int ntop_clear_user_lifetime(lua_State* vm) {
char *username;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->clearUserLifetime(username) ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_delete_user(lua_State* vm) {
char *username;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
return ntop->deleteUser(username);
}
/* ****************************************** */
static int ntop_resolve_address(lua_State* vm) {
char *numIP, symIP[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((numIP = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
ntop->resolveHostName(numIP, symIP, sizeof(symIP));
lua_pushstring(vm, symIP);
return(CONST_LUA_OK);
}
/* ****************************************** */
void lua_push_str_table_entry(lua_State *L, const char *key, char *value) {
if(L) {
lua_pushstring(L, key);
lua_pushstring(L, value);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_nil_table_entry(lua_State *L, const char *key) {
if(L) {
lua_pushstring(L, key);
lua_pushnil(L);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_bool_table_entry(lua_State *L, const char *key, bool value) {
if(L) {
lua_pushstring(L, key);
lua_pushboolean(L, value ? 1 : 0);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_int_table_entry(lua_State *L, const char *key, u_int64_t value) {
if(L) {
lua_pushstring(L, key);
/* using LUA_NUMBER (double: 64 bit) in place of LUA_INTEGER (ptrdiff_t: 32 or 64 bit
* according to the platform, as defined in luaconf.h) to handle big counters */
lua_pushnumber(L, (lua_Number)value);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_int32_table_entry(lua_State *L, const char *key, int32_t value) {
if(L) {
lua_pushstring(L, key);
lua_pushnumber(L, (lua_Number)value);
lua_settable(L, -3);
}
}
/* ****************************************** */
void lua_push_float_table_entry(lua_State *L, const char *key, float value) {
if(L) {
lua_pushstring(L, key);
lua_pushnumber(L, value);
lua_settable(L, -3);
}
}
/* ****************************************** */
static int ntop_get_interface_stats(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
/*
ntop_interface->getAlertsManager()->engageAlert(alert_entity_host, "127.0.0.1",
"min_bytes",
alert_threshold_exceeded,
alert_level_warning,
"miao");
ntop_interface->getAlertsManager()->releaseAlert(alert_entity_host, "127.0.0.1",
"min_bytes",
alert_threshold_exceeded,
alert_level_warning,
"miao");
*/
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) ntop_interface->lua(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_reset_counters(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool only_drops = true;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TBOOLEAN)
only_drops = lua_toboolean(vm, 1) ? true : false;
if(!ntop_interface)
return(CONST_LUA_ERROR);
ntop_interface->checkPointCounters(only_drops);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_is_pro(lua_State *vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm, ntop->getPrefs()->is_pro_edition());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_is_enterprise(lua_State *vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushboolean(vm, ntop->getPrefs()->is_enterprise_edition());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_reload_host_pools(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) {
ntop_interface->getHostPools()->reloadPools();
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
#ifdef NTOPNG_PRO
static int ntop_purge_expired_host_pools_members(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface && ntop_interface->getHostPools()) {
ntop_interface->getHostPools()->purgeExpiredVolatileMembers();
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
static int ntop_remove_volatile_member_from_pool(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_or_mac;
u_int16_t pool_id;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((host_or_mac = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_PARAM_ERROR);
pool_id = (u_int16_t)lua_tonumber(vm, 2);
if(ntop_interface && ntop_interface->getHostPools()) {
ntop_interface->getHostPools()->removeVolatileMemberFromPool(host_or_mac, pool_id);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
#endif
/* ****************************************** */
static int ntop_reload_l7_rules(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_PARAM_ERROR);
if(ntop_interface) {
#ifdef NTOPNG_PRO
u_int16_t host_pool_id = (u_int16_t)lua_tonumber(vm, 1);
#ifdef SHAPER_DEBUG
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s(%i)", __FUNCTION__, host_pool_id);
#endif
ntop_interface->refreshL7Rules();
ntop_interface->updateHostsL7Policy(host_pool_id);
ntop_interface->updateFlowsL7Policy();
#endif
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_reload_shapers(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface) {
#ifdef NTOPNG_PRO
ntop_interface->refreshShapers();
#endif
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_interface_exec_sql_query(lua_State *vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
bool limit_rows = true; // honour the limit by default
bool wait_for_db_created = true;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!ntop_interface)
return(CONST_LUA_ERROR);
else {
char *sql;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((sql = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 2) == LUA_TBOOLEAN) {
limit_rows = lua_toboolean(vm, 2) ? true : false;
}
if(lua_type(vm, 3) == LUA_TBOOLEAN) {
wait_for_db_created = lua_toboolean(vm, 3) ? true : false;
}
if(ntop_interface->exec_sql_query(vm, sql, limit_rows, wait_for_db_created) < 0)
lua_pushnil(vm);
return(CONST_LUA_OK);
}
}
/* ****************************************** */
static int ntop_get_dirs(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_newtable(vm);
lua_push_str_table_entry(vm, "installdir", ntop->get_install_dir());
lua_push_str_table_entry(vm, "workingdir", ntop->get_working_dir());
lua_push_str_table_entry(vm, "scriptdir", ntop->getPrefs()->get_scripts_dir());
lua_push_str_table_entry(vm, "httpdocsdir", ntop->getPrefs()->get_docs_dir());
lua_push_str_table_entry(vm, "callbacksdir", ntop->getPrefs()->get_callbacks_dir());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_uptime(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_pushinteger(vm, ntop->getGlobals()->getUptime());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_check_license(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
#ifdef NTOPNG_PRO
ntop->getPro()->check_license();
#endif
lua_pushinteger(vm,1);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_info(lua_State* vm) {
char rsp[256];
int major, minor, patch;
bool verbose = true;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(lua_type(vm, 1) == LUA_TBOOLEAN)
verbose = lua_toboolean(vm, 1) ? true : false;
lua_newtable(vm);
lua_push_str_table_entry(vm, "product", (char*)"ntopng");
lua_push_str_table_entry(vm, "copyright", (char*)"© 1998-17 - ntop.org");
lua_push_str_table_entry(vm, "authors", (char*)"The ntop.org team");
lua_push_str_table_entry(vm, "license", (char*)"GNU GPLv3");
lua_push_str_table_entry(vm, "version", (char*)PACKAGE_VERSION);
lua_push_str_table_entry(vm, "git", (char*)NTOPNG_GIT_RELEASE);
snprintf(rsp, sizeof(rsp), "%s [%s][%s]",
PACKAGE_OSNAME, PACKAGE_MACHINE, PACKAGE_OS);
lua_push_str_table_entry(vm, "platform", rsp);
lua_push_str_table_entry(vm, "OS",
#ifdef WIN32
(char*)"Windows"
#else
(char*)PACKAGE_OS
#endif
);
lua_push_int_table_entry(vm, "bits", (sizeof(void*) == 4) ? 32 : 64);
lua_push_int_table_entry(vm, "uptime", ntop->getGlobals()->getUptime());
lua_push_str_table_entry(vm, "command_line", ntop->getPrefs()->get_command_line());
if(verbose) {
lua_push_str_table_entry(vm, "version.rrd", rrd_strversion());
lua_push_str_table_entry(vm, "version.redis", ntop->getRedis()->getVersion(rsp, sizeof(rsp)));
lua_push_str_table_entry(vm, "version.httpd", (char*)mg_version());
lua_push_str_table_entry(vm, "version.git", (char*)NTOPNG_GIT_RELEASE);
lua_push_str_table_entry(vm, "version.luajit", (char*)LUAJIT_VERSION);
#ifdef HAVE_GEOIP
lua_push_str_table_entry(vm, "version.geoip", (char*)GeoIP_lib_version());
#endif
lua_push_str_table_entry(vm, "version.ndpi", ndpi_revision());
lua_push_bool_table_entry(vm, "version.enterprise_edition", ntop->getPrefs()->is_enterprise_edition());
lua_push_bool_table_entry(vm, "version.embedded_edition", ntop->getPrefs()->is_embedded_edition());
lua_push_bool_table_entry(vm, "pro.release", ntop->getPrefs()->is_pro_edition());
lua_push_int_table_entry(vm, "pro.demo_ends_at", ntop->getPrefs()->pro_edition_demo_ends_at());
#ifdef NTOPNG_PRO
lua_push_str_table_entry(vm, "pro.license", ntop->getPro()->get_license());
lua_push_bool_table_entry(vm, "pro.use_redis_license", ntop->getPro()->use_redis_license());
lua_push_str_table_entry(vm, "pro.systemid", ntop->getPro()->get_system_id());
#endif
#if 0
ntop->getRedis()->get((char*)CONST_STR_NTOPNG_LICENSE, rsp, sizeof(rsp));
lua_push_str_table_entry(vm, "ntopng.license", rsp);
#endif
zmq_version(&major, &minor, &patch);
snprintf(rsp, sizeof(rsp), "%d.%d.%d", major, minor, patch);
lua_push_str_table_entry(vm, "version.zmq", rsp);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_resolved_address(lua_State* vm) {
char *key, *tmp,rsp[256],value[64];
Redis *redis = ntop->getRedis();
u_int16_t vlan_id = 0;
char buf[64];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &key, &vlan_id, buf, sizeof(buf));
if(key == NULL)
return(CONST_LUA_ERROR);
if(redis->getAddress(key, rsp, sizeof(rsp), true) == 0)
tmp = rsp;
else
tmp = key;
if(vlan_id != 0)
snprintf(value, sizeof(value), "%s@%u", tmp, vlan_id);
else
snprintf(value, sizeof(value), "%s", tmp);
#if 0
if(!strcmp(value, key)) {
char rsp[64];
if((ntop->getRedis()->hashGet((char*)HOST_LABEL_NAMES, key, rsp, sizeof(rsp)) == 0)
&& (rsp[0] !='\0'))
lua_pushfstring(vm, "%s", rsp);
else
lua_pushfstring(vm, "%s", value);
} else
lua_pushfstring(vm, "%s", value);
#else
lua_pushfstring(vm, "%s", value);
#endif
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_snmp_get_fctn(lua_State* vm, int operation) {
char *agent_host, *oid, *community;
u_int agent_port = 161, timeout = 5, request_id = (u_int)time(NULL);
int sock, i = 0, rc = CONST_LUA_OK;
SNMPMessage *message;
int len;
unsigned char *buf;
bool debug = false;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
agent_host = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
community = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
oid = (char*)lua_tostring(vm, 3);
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sock < 0) return(CONST_LUA_ERROR);
message = snmp_create_message();
snmp_set_version(message, 0);
snmp_set_community(message, community);
snmp_set_pdu_type(message, operation);
snmp_set_request_id(message, request_id);
snmp_set_error(message, 0);
snmp_set_error_index(message, 0);
snmp_add_varbind_null(message, oid);
/* Add additional OIDs */
i = 4;
while(lua_type(vm, i) == LUA_TSTRING) {
snmp_add_varbind_null(message, (char*)lua_tostring(vm, i));
i++;
}
len = snmp_message_length(message);
buf = (unsigned char*)malloc(len);
snmp_render_message(message, buf);
snmp_destroy_message(message);
send_udp_datagram(buf, len, sock, agent_host, agent_port);
free(buf);
if(debug)
ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP %s %s@%s %s",
(operation == SNMP_GET_REQUEST_TYPE) ? "Get" : "GetNext",
agent_host, community, oid);
if(input_timeout(sock, timeout) == 0) {
/* Timeout */
if(debug)
ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP Timeout %s@%s %s", agent_host, community, oid);
rc = CONST_LUA_ERROR;
lua_pushnil(vm);
} else {
char buf[BUFLEN];
SNMPMessage *message;
char *sender_host, *oid_str, *value_str;
int sender_port, added = 0, len;
len = receive_udp_datagram(buf, BUFLEN, sock, &sender_host, &sender_port);
message = snmp_parse_message(buf, len);
i = 0;
while(snmp_get_varbind_as_string(message, i, &oid_str, NULL, &value_str)) {
if(!added) lua_newtable(vm), added = 1;
lua_push_str_table_entry(vm, oid_str, value_str);
if(debug)
ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP OK %s@%s %s=%s", agent_host, community, oid_str, value_str);
i++;
}
snmp_destroy_message(message);
if(!added) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "SNMP Error %s@%s", agent_host, community);
lua_pushnil(vm), rc = CONST_LUA_ERROR;
}
}
closesocket(sock);
return(rc);
}
/* ****************************************** */
static int ntop_snmpget(lua_State* vm) { return(ntop_snmp_get_fctn(vm, SNMP_GET_REQUEST_TYPE)); }
static int ntop_snmpgetnext(lua_State* vm) { return(ntop_snmp_get_fctn(vm, SNMP_GETNEXT_REQUEST_TYPE)); }
/* ****************************************** */
/**
* @brief Send a message to the system syslog
* @details Send a message to the syslog syslog: callers can specify if it is an error or informational message
*
* @param vm The lua state.
* @return @ref CONST_LUA_ERROR if the expected type is equal to function type, @ref CONST_LUA_PARAM_ERROR otherwise.
*/
static int ntop_syslog(lua_State* vm) {
#ifndef WIN32
char *msg;
bool is_error;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
is_error = lua_toboolean(vm, 1) ? true : false;
msg = (char*)lua_tostring(vm, 2);
syslog(is_error ? LOG_ERR : LOG_INFO, "%s", msg);
#endif
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Generate a random value to prevent CSRF and XSRF attacks
* @details See http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
*
* @param vm The lua state.
* @return The random value just generated
*/
static int ntop_generate_csrf_value(lua_State* vm) {
char random_a[32], random_b[32], csrf[33], user[64] = { '\0' };
Redis *redis = ntop->getRedis();
struct mg_connection *conn;
lua_getglobal(vm, CONST_HTTP_CONN);
if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection");
return(CONST_LUA_OK);
}
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
#ifdef __OpenBSD__
snprintf(random_a, sizeof(random_a), "%d", arc4random());
snprintf(random_b, sizeof(random_b), "%lu", time(NULL)*arc4random());
#else
snprintf(random_a, sizeof(random_a), "%d", rand());
snprintf(random_b, sizeof(random_b), "%lu", time(NULL)*rand());
#endif
mg_get_cookie(conn, "user", user, sizeof(user));
mg_md5(csrf, random_a, random_b, NULL);
redis->set(csrf, (char*)user, MAX_CSRF_DURATION);
lua_pushfstring(vm, "%s", csrf);
return(CONST_LUA_OK);
}
/* ****************************************** */
struct ntopng_sqlite_state {
lua_State* vm;
u_int num_rows;
};
static int sqlite_callback(void *data, int argc,
char **argv, char **azColName) {
struct ntopng_sqlite_state *s = (struct ntopng_sqlite_state*)data;
lua_newtable(s->vm);
for(int i=0; i<argc; i++)
lua_push_str_table_entry(s->vm, (const char*)azColName[i],
(char*)(argv[i] ? argv[i] : "NULL"));
lua_pushinteger(s->vm, ++s->num_rows);
lua_insert(s->vm, -2);
lua_settable(s->vm, -3);
return(0);
}
/* ****************************************** */
/**
* @brief Exec SQL query
* @details Execute the specified query and return the results
*
* @param vm The lua state.
* @return @ref CONST_LUA_ERROR in case of error, CONST_LUA_OK otherwise.
*/
static int ntop_sqlite_exec_query(lua_State* vm) {
char *db_path, *db_query;
sqlite3 *db;
char *zErrMsg = 0;
struct ntopng_sqlite_state state;
struct stat buf;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
db_path = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
db_query = (char*)lua_tostring(vm, 2);
if(stat(db_path, &buf) != 0) {
ntop->getTrace()->traceEvent(TRACE_INFO, "Not found database %s",
db_path);
return(CONST_LUA_ERROR);
}
if(sqlite3_open(db_path, &db)) {
ntop->getTrace()->traceEvent(TRACE_INFO, "Unable to open %s: %s",
db_path, sqlite3_errmsg(db));
return(CONST_LUA_ERROR);
}
state.vm = vm, state.num_rows = 0;
lua_newtable(vm);
if(sqlite3_exec(db, db_query, sqlite_callback, (void*)&state, &zErrMsg)) {
ntop->getTrace()->traceEvent(TRACE_INFO, "SQL Error: %s", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return(CONST_LUA_OK);
}
/**
* @brief Insert a new minute sampling in the historical database
* @details Given a certain sampling point, store statistics for said
* sampling point.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_insert_minute_sampling(lua_State *vm) {
char *sampling;
time_t rawtime;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
time(&rawtime);
if(sm->insertMinuteSampling(rawtime, sampling))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Insert a new hour sampling in the historical database
* @details Given a certain sampling point, store statistics for said
* sampling point.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_insert_hour_sampling(lua_State *vm) {
char *sampling;
time_t rawtime;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
time(&rawtime);
rawtime -= (rawtime % 60);
if(sm->insertHourSampling(rawtime, sampling))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Insert a new day sampling in the historical database
* @details Given a certain sampling point, store statistics for said
* sampling point.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_insert_day_sampling(lua_State *vm) {
char *sampling;
time_t rawtime;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
time(&rawtime);
rawtime -= (rawtime % 60);
if(sm->insertDaySampling(rawtime, sampling))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Get a minute sampling from the historical database
* @details Given a certain sampling point, get statistics for said
* sampling point.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_minute_sampling(lua_State *vm) {
time_t epoch;
string sampling;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch = (time_t)lua_tointeger(vm, 2);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->getMinuteSampling(epoch, &sampling))
return(CONST_LUA_ERROR);
lua_pushstring(vm, sampling.c_str());
return(CONST_LUA_OK);
}
/**
* @brief Delete minute stats older than a certain number of days.
* @details Given a number of days, delete stats for the current interface that
* are older than a certain number of days.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_delete_minute_older_than(lua_State *vm) {
int num_days;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_days = lua_tointeger(vm, 2);
if(num_days < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->deleteMinuteStatsOlderThan(num_days))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Delete hour stats older than a certain number of days.
* @details Given a number of days, delete stats for the current interface that
* are older than a certain number of days.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_delete_hour_older_than(lua_State *vm) {
int num_days;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_days = lua_tointeger(vm, 2);
if(num_days < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->deleteHourStatsOlderThan(num_days))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Delete day stats older than a certain number of days.
* @details Given a number of days, delete stats for the current interface that
* are older than a certain number of days.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_delete_day_older_than(lua_State *vm) {
int num_days;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_days = lua_tointeger(vm, 2);
if(num_days < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->deleteDayStatsOlderThan(num_days))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/**
* @brief Get an interval of minute stats samplings from the historical database
* @details Given a certain interval of sampling points, get statistics for said
* sampling points.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_minute_samplings_interval(lua_State *vm) {
time_t epoch_start, epoch_end;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
struct statsManagerRetrieval retvals;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_start = lua_tointeger(vm, 2);
if(epoch_start < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 3);
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
if(sm->retrieveMinuteStatsInterval(epoch_start, epoch_end, &retvals))
return(CONST_LUA_ERROR);
lua_newtable(vm);
for (unsigned i = 0 ; i < retvals.rows.size() ; i++)
lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)"");
return(CONST_LUA_OK);
}
/**
* @brief Given an epoch, get minute stats for the latest n minutes
* @details Given a certain sampling point, get statistics for that point and
* for all timepoints spanning an interval of a given number of
* minutes.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_samplings_of_minutes_from_epoch(lua_State *vm) {
time_t epoch_start, epoch_end;
int num_minutes;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
struct statsManagerRetrieval retvals;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 2);
epoch_end -= (epoch_end % 60);
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_minutes = lua_tointeger(vm, 3);
if(num_minutes < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
epoch_start = epoch_end - (60 * num_minutes);
if(sm->retrieveMinuteStatsInterval(epoch_start, epoch_end, &retvals))
return(CONST_LUA_ERROR);
lua_newtable(vm);
for (unsigned i = 0 ; i < retvals.rows.size() ; i++)
lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)"");
return(CONST_LUA_OK);
}
/**
* @brief Given an epoch, get hour stats for the latest n hours
* @details Given a certain sampling point, get statistics for that point and
* for all timepoints spanning an interval of a given number of
* hours.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_samplings_of_hours_from_epoch(lua_State *vm) {
time_t epoch_start, epoch_end;
int num_hours;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
struct statsManagerRetrieval retvals;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 2);
epoch_end -= (epoch_end % 60);
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_hours = lua_tointeger(vm, 3);
if(num_hours < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
epoch_start = epoch_end - (num_hours * 60 * 60);
if(sm->retrieveHourStatsInterval(epoch_start, epoch_end, &retvals))
return(CONST_LUA_ERROR);
lua_newtable(vm);
for (unsigned i = 0 ; i < retvals.rows.size() ; i++)
lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)"");
return(CONST_LUA_OK);
}
/**
* @brief Given an epoch, get hour stats for the latest n days
* @details Given a certain sampling point, get statistics for that point and
* for all timepoints spanning an interval of a given number of
* days.
*
* @param vm The lua state.
* @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter,
* CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise.
*/
static int ntop_stats_get_samplings_of_days_from_epoch(lua_State *vm) {
time_t epoch_start, epoch_end;
int num_days;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
struct statsManagerRetrieval retvals;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 2);
epoch_end -= (epoch_end % 60);
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_days = lua_tointeger(vm, 3);
if(num_days < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid)) ||
!(sm = iface->getStatsManager()))
return (CONST_LUA_ERROR);
epoch_start = epoch_end - (num_days * 24 * 60 * 60);
if(sm->retrieveDayStatsInterval(epoch_start, epoch_end, &retvals))
return(CONST_LUA_ERROR);
lua_newtable(vm);
for (unsigned i = 0 ; i < retvals.rows.size() ; i++)
lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)"");
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_delete_dump_files(lua_State *vm) {
int ifid;
char pcap_path[MAX_PATH];
NetworkInterface *iface;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
if((ifid = lua_tointeger(vm, 1)) < 0) return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(ifid))) return(CONST_LUA_ERROR);
snprintf(pcap_path, sizeof(pcap_path), "%s/%d/pcap/",
ntop->get_working_dir(), ifid);
ntop->fixPath(pcap_path);
if(Utils::discardOldFilesExceeding(pcap_path, iface->getDumpTrafficMaxFiles()))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_mkdir_tree(lua_State* vm) {
char *dir;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((dir = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(dir[0] == '\0') return(CONST_LUA_OK); /* Nothing to do */
return(Utils::mkdir_tree(dir));
}
/* ****************************************** */
static int ntop_list_reports(lua_State* vm) {
DIR *dir;
char fullpath[MAX_PATH];
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_newtable(vm);
snprintf(fullpath, sizeof(fullpath), "%s/%s", ntop->get_working_dir(), "reports");
ntop->fixPath(fullpath);
if((dir = opendir(fullpath)) != NULL) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
char filepath[MAX_PATH];
snprintf(filepath, sizeof(filepath), "%s/%s", fullpath, ent->d_name);
ntop->fixPath(filepath);
struct stat buf;
if(!stat(filepath, &buf) && !S_ISDIR(buf.st_mode))
lua_push_str_table_entry(vm, ent->d_name, (char*)"");
}
closedir(dir);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_redis(lua_State* vm) {
char *key, *rsp;
u_int rsp_len = 32768;
Redis *redis = ntop->getRedis();
bool cache_it = false;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
/* Optional cache_it */
if(lua_type(vm, 2) == LUA_TBOOLEAN) cache_it = lua_toboolean(vm, 2);
if((rsp = (char*)malloc(rsp_len)) != NULL) {
lua_pushfstring(vm, "%s", (redis->get(key, rsp, rsp_len, cache_it) == 0) ? rsp : (char*)"");
free(rsp);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_get_hash_redis(lua_State* vm) {
char *key, *member, rsp[CONST_MAX_LEN_REDIS_VALUE];
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
lua_pushfstring(vm, "%s", (redis->hashGet(key, member, rsp, sizeof(rsp)) == 0) ? rsp : (char*)"");
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_set_hash_redis(lua_State* vm) {
char *key, *member, *value;
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((value = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
redis->hashSet(key, member, value);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_del_hash_redis(lua_State* vm) {
char *key, *member;
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
redis->hashDel(key, member);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_hash_keys_redis(lua_State* vm) {
char *key, **vals;
Redis *redis = ntop->getRedis();
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
rc = redis->hashKeys(key, &vals);
if(rc > 0) {
lua_newtable(vm);
for(int i = 0; i < rc; i++) {
lua_push_str_table_entry(vm, vals[i] ? vals[i] : "", (char*)"");
if(vals[i]) free(vals[i]);
}
free(vals);
} else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_keys_redis(lua_State* vm) {
char *pattern, **keys;
Redis *redis = ntop->getRedis();
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((pattern = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
rc = redis->keys(pattern, &keys);
if(rc > 0) {
lua_newtable(vm);
for(int i = 0; i < rc; i++) {
lua_push_str_table_entry(vm, keys[i] ? keys[i] : "", (char*)"");
if(keys[i]) free(keys[i]);
}
free(keys);
} else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_lrange_redis(lua_State* vm) {
char *l_name, **l_elements;
Redis *redis = ntop->getRedis();
int start_offset = 0, end_offset = -1;
int rc;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((l_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 2) == LUA_TNUMBER) {
start_offset = lua_tointeger(vm, 2);
}
if(lua_type(vm, 3) == LUA_TNUMBER) {
end_offset = lua_tointeger(vm, 3);
}
rc = redis->lrange(l_name, &l_elements, start_offset, end_offset);
if(rc > 0) {
lua_newtable(vm);
for(int i = 0; i < rc; i++) {
lua_push_str_table_entry(vm, l_elements[i] ? l_elements[i] : "", (char*)"");
if(l_elements[i]) free(l_elements[i]);
}
free(l_elements);
} else
lua_pushnil(vm);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_get_redis_set_pop(lua_State* vm) {
char *set_name, rsp[CONST_MAX_LEN_REDIS_VALUE];
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((set_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
lua_pushfstring(vm, "%s", redis->popSet(set_name, rsp, sizeof(rsp)));
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_list_index_redis(lua_State* vm) {
char *index_name, rsp[CONST_MAX_LEN_REDIS_VALUE];
Redis *redis = ntop->getRedis();
int idx;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((index_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
idx = lua_tointeger(vm, 2);
if(redis->lindex(index_name, idx, rsp, sizeof(rsp)) != 0)
return(CONST_LUA_ERROR);
lua_pushfstring(vm, "%s", rsp);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_lpop_redis(lua_State* vm) {
char msg[1024], *list_name;
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((list_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(redis->lpop(list_name, msg, sizeof(msg)) == 0) {
lua_pushfstring(vm, "%s", msg);
return(CONST_LUA_OK);
} else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_lpush_redis(lua_State* vm) {
char *list_name, *value;
u_int list_trim_size = 0; // default 0 = no trim
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((list_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
/* Optional trim list up to the specified number of elements */
if(lua_type(vm, 3) == LUA_TNUMBER)
list_trim_size = (u_int)lua_tonumber(vm, 3);
if(redis->lpush(list_name, value, list_trim_size) == 0) {
return(CONST_LUA_OK);
}else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_redis_get_host_id(lua_State* vm) {
char *host_name;
Redis *redis = ntop->getRedis();
char daybuf[32];
time_t when = time(NULL);
bool new_key;
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((host_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
strftime(daybuf, sizeof(daybuf), CONST_DB_DAY_FORMAT, localtime(&when));
lua_pushinteger(vm, redis->host_to_id(ntop_interface, daybuf, host_name, &new_key)); /* CHECK */
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_redis_get_id_to_host(lua_State* vm) {
char *host_idx, rsp[CONST_MAX_LEN_REDIS_VALUE];
Redis *redis = ntop->getRedis();
char daybuf[32];
time_t when = time(NULL);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((host_idx = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
strftime(daybuf, sizeof(daybuf), CONST_DB_DAY_FORMAT, localtime(&when));
lua_pushfstring(vm, "%d", redis->id_to_host(daybuf, host_idx, rsp, sizeof(rsp)));
return(CONST_LUA_OK);
}
/* ****************************************** */
#ifdef NOTUSED
static int ntop_interface_store_alert(lua_State* vm) {
int ifid;
NetworkInterface* iface;
AlertsManager *am;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TTABLE)) return(CONST_LUA_ERROR);
ifid = lua_tointeger(vm, 1);
if(ifid < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getNetworkInterface(vm, ifid)) ||
!(am = iface->getAlertsManager()))
return (CONST_LUA_ERROR);
return am->storeAlert(vm, 2) ? CONST_LUA_ERROR : CONST_LUA_OK;
}
#endif
/* ****************************************** */
static int ntop_interface_engage_release_host_alert(lua_State* vm, bool engage) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *host_ip;
u_int16_t vlan_id = 0;
char buf[64];
Host *h;
int alert_severity;
int alert_type;
char *alert_json, *engaged_alert_id;
AlertsManager *am;
int ret;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf));
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
engaged_alert_id = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_type = (int)lua_tonumber(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_severity = (int)lua_tonumber(vm, 4);
if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_json = (char*)lua_tostring(vm, 5);
if((!ntop_interface)
|| ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
if(engage)
ret = am->engageHostAlert(h, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
else
ret = am->releaseHostAlert(h, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_interface_engage_release_network_alert(lua_State* vm, bool engage) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
char *cidr;
int alert_severity;
int alert_type;
char *alert_json, *engaged_alert_id;
AlertsManager *am;
int ret;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
cidr = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
engaged_alert_id = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_type = (int)lua_tonumber(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_severity = (int)lua_tonumber(vm, 4);
if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_json = (char*)lua_tostring(vm, 5);
if((!ntop_interface)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
if(engage)
ret = am->engageNetworkAlert(cidr, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
else
ret = am->releaseNetworkAlert(cidr, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_interface_engage_release_interface_alert(lua_State* vm, bool engage) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int alert_severity;
int alert_type;
char *alert_json, *engaged_alert_id;
AlertsManager *am;
int ret;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
engaged_alert_id = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_type = (int)lua_tonumber(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_severity = (int)lua_tonumber(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_json = (char*)lua_tostring(vm, 4);
if((!ntop_interface)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
if(engage)
ret = am->engageInterfaceAlert(ntop_interface, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
else
ret = am->releaseInterfaceAlert(ntop_interface, engaged_alert_id,
(AlertType)alert_type, (AlertLevel)alert_severity, alert_json);
return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_interface_engage_host_alert(lua_State* vm) {
return ntop_interface_engage_release_host_alert(vm, true /* engage */);
}
/* ****************************************** */
static int ntop_interface_release_host_alert(lua_State* vm) {
return ntop_interface_engage_release_host_alert(vm, false /* release */);
}
/* ****************************************** */
static int ntop_interface_engage_network_alert(lua_State* vm) {
return ntop_interface_engage_release_network_alert(vm, true /* engage */);
}
/* ****************************************** */
static int ntop_interface_release_network_alert(lua_State* vm) {
return ntop_interface_engage_release_network_alert(vm, false /* release */);
}
/* ****************************************** */
static int ntop_interface_engage_interface_alert(lua_State* vm) {
return ntop_interface_engage_release_interface_alert(vm, true /* engage */);
}
/* ****************************************** */
static int ntop_interface_release_interface_alert(lua_State* vm) {
return ntop_interface_engage_release_interface_alert(vm, false /* release */);
}
/* ****************************************** */
static int ntop_interface_get_cached_num_alerts(lua_State* vm) {
NetworkInterface *iface = getCurrentInterface(vm);
AlertsManager *am;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!iface || !(am = iface->getAlertsManager()))
return (CONST_LUA_ERROR);
return (!am->getCachedNumAlerts(vm)) ? CONST_LUA_OK : CONST_LUA_ERROR;
}
/* ****************************************** */
static int ntop_interface_make_room_alerts(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
int alert_entity;
char *alert_entity_value, *table_name;
AlertsManager *am;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
alert_entity = (int)lua_tonumber(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_entity_value = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
table_name = (char*)lua_tostring(vm, 3);
if((!ntop_interface)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
am->makeRoom((AlertEntity)alert_entity, alert_entity_value, table_name);
return CONST_LUA_OK;
}
/* ****************************************** */
static int ntop_interface_make_room_requested(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
AlertsManager *am;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if((!ntop_interface)
|| ((am = ntop_interface->getAlertsManager()) == NULL))
return(CONST_LUA_ERROR);
lua_pushboolean(vm, am->makeRoomRequested());
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_query_alerts_raw(lua_State* vm) {
NetworkInterface *iface = getCurrentInterface(vm);
AlertsManager *am;
bool engaged = false;
char *selection = NULL, *clauses = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!iface || !(am = iface->getAlertsManager()))
return (CONST_LUA_ERROR);
if(lua_type(vm, 1) == LUA_TBOOLEAN)
engaged = lua_toboolean(vm, 1);
if(lua_type(vm, 2) == LUA_TSTRING)
if((selection = (char*)lua_tostring(vm, 2)) == NULL)
return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 3) == LUA_TSTRING)
if((clauses = (char*)lua_tostring(vm, 3)) == NULL)
return(CONST_LUA_PARAM_ERROR);
if(am->queryAlertsRaw(vm, engaged, selection, clauses))
return(CONST_LUA_ERROR);
return (CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_interface_query_flow_alerts_raw(lua_State* vm) {
NetworkInterface *iface = getCurrentInterface(vm);
AlertsManager *am;
char *selection = NULL, *clauses = NULL;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!iface || !(am = iface->getAlertsManager()))
return (CONST_LUA_ERROR);
if(lua_type(vm, 1) == LUA_TSTRING)
if((selection = (char*)lua_tostring(vm, 1)) == NULL)
return(CONST_LUA_PARAM_ERROR);
if(lua_type(vm, 2) == LUA_TSTRING)
if((clauses = (char*)lua_tostring(vm, 2)) == NULL)
return(CONST_LUA_PARAM_ERROR);
if(am->queryFlowAlertsRaw(vm, selection, clauses))
return(CONST_LUA_ERROR);
return (CONST_LUA_OK);
}
/* ****************************************** */
#if NTOPNG_PRO
static int ntop_nagios_reload_config(lua_State* vm) {
NagiosManager *nagios = ntop->getNagios();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(!nagios) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "%s(): unable to get the nagios manager",
__FUNCTION__);
return(CONST_LUA_ERROR);
}
nagios->loadConfig();
lua_pushnil(vm);
return(CONST_LUA_OK);
}
static int ntop_nagios_send_alert(lua_State* vm) {
NagiosManager *nagios = ntop->getNagios();
char *alert_source;
char *timespan;
char *alarmed_metric;
char *alert_msg;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_source = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
timespan = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
alarmed_metric = (char*)lua_tostring(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_msg = (char*)lua_tostring(vm, 4);
nagios->sendAlert(alert_source, timespan, alarmed_metric, alert_msg);
lua_pushnil(vm);
return(CONST_LUA_OK);
}
static int ntop_nagios_withdraw_alert(lua_State* vm) {
NagiosManager *nagios = ntop->getNagios();
char *alert_source;
char *timespan;
char *alarmed_metric;
char *alert_msg;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_source = (char*)lua_tostring(vm, 1);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
timespan = (char*)lua_tostring(vm, 2);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR);
alarmed_metric = (char*)lua_tostring(vm, 3);
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR);
alert_msg = (char*)lua_tostring(vm, 4);
nagios->withdrawAlert(alert_source, timespan, alarmed_metric, alert_msg);
lua_pushnil(vm);
return(CONST_LUA_OK);
}
#endif
/* ****************************************** */
#ifdef NTOPNG_PRO
static int ntop_check_profile_syntax(lua_State* vm) {
char *filter;
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
filter = (char*)lua_tostring(vm, 1);
lua_pushboolean(vm, ntop_interface ? ntop_interface->checkProfileSyntax(filter) : false);
return(CONST_LUA_OK);
}
#endif
/* ****************************************** */
#ifdef NTOPNG_PRO
static int ntop_reload_traffic_profiles(lua_State* vm) {
NetworkInterface *ntop_interface = getCurrentInterface(vm);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_interface)
ntop_interface->updateFlowProfiles(); /* Reload profiles in memory */
lua_pushnil(vm);
return(CONST_LUA_OK);
}
#endif
/* ****************************************** */
static int ntop_set_redis(lua_State* vm) {
char *key, *value;
u_int expire_secs = 0; // default 0 = no expiration
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
/* Optional key expiration in SECONDS */
if(lua_type(vm, 3) == LUA_TNUMBER)
expire_secs = (u_int)lua_tonumber(vm, 3);
if(redis->set(key, value, expire_secs) == 0) {
return(CONST_LUA_OK);
}else
return(CONST_LUA_ERROR);
}
/* ****************************************** */
static int ntop_set_redis_preference(lua_State* vm) {
char *key, *value;
Redis *redis = ntop->getRedis();
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR);
if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR);
if(redis->set(key, value) ||
ntop->getPrefs()->refresh(key, value))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_lua_http_print(lua_State* vm) {
struct mg_connection *conn;
char *printtype;
int t;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
lua_getglobal(vm, CONST_HTTP_CONN);
if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection");
return(CONST_LUA_OK);
}
/* Handle binary blob */
if(lua_type(vm, 2) == LUA_TSTRING &&
(printtype = (char*)lua_tostring(vm, 2)) != NULL)
if(!strncmp(printtype, "blob", 4)) {
char *str = NULL;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return (CONST_LUA_ERROR);
if((str = (char*)lua_tostring(vm, 1)) != NULL) {
int len = strlen(str);
if(len <= 1)
mg_printf(conn, "%c", str[0]);
else
return (CONST_LUA_PARAM_ERROR);
}
return (CONST_LUA_OK);
}
switch(t = lua_type(vm, 1)) {
case LUA_TNIL:
mg_printf(conn, "%s", "nil");
break;
case LUA_TBOOLEAN:
{
int v = lua_toboolean(vm, 1);
mg_printf(conn, "%s", v ? "true" : "false");
}
break;
case LUA_TSTRING:
{
char *str = (char*)lua_tostring(vm, 1);
if(str && (strlen(str) > 0))
mg_printf(conn, "%s", str);
}
break;
case LUA_TNUMBER:
{
char str[64];
snprintf(str, sizeof(str), "%f", (float)lua_tonumber(vm, 1));
mg_printf(conn, "%s", str);
}
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "%s(): Lua type %d is not handled",
__FUNCTION__, t);
return(CONST_LUA_ERROR);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
int ntop_lua_cli_print(lua_State* vm) {
int t;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
switch(t = lua_type(vm, 1)) {
case LUA_TSTRING:
{
char *str = (char*)lua_tostring(vm, 1);
if(str && (strlen(str) > 0))
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s", str);
}
break;
case LUA_TNUMBER:
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%f", (float)lua_tonumber(vm, 1));
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "%s(): Lua type %d is not handled",
__FUNCTION__, t);
return(CONST_LUA_ERROR);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
#ifdef NTOPNG_PRO
static int __ntop_lua_handlefile(lua_State* L, char *script_path, bool ex)
{
int rc;
LuaHandler *lh = new LuaHandler(L, script_path);
rc = lh->luaL_dofileM(ex);
delete lh;
return rc;
}
/* This function is called by Lua scripts when the call require(...) */
static int ntop_lua_require(lua_State* L)
{
char *script_name;
if(lua_type(L, 1) != LUA_TSTRING ||
(script_name = (char*)lua_tostring(L, 1)) == NULL)
return 0;
lua_getglobal( L, "package" );
lua_getfield( L, -1, "path" );
string cur_path = lua_tostring( L, -1 ), parsed, script_path = "";
stringstream input_stringstream(cur_path);
while(getline(input_stringstream, parsed, ';')) {
/* Example: package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path */
unsigned found = parsed.find_last_of("?");
if(found) {
string s = parsed.substr(0, found) + script_name + ".lua";
if(Utils::file_exists(s.c_str())) {
script_path = s;
break;
}
}
}
if(script_path == "" ||
__ntop_lua_handlefile(L, (char *)script_path.c_str(), false))
return 0;
return 1;
}
static int ntop_lua_dofile(lua_State* L)
{
char *script_path;
if(lua_type(L, 1) != LUA_TSTRING ||
(script_path = (char*)lua_tostring(L, 1)) == NULL ||
__ntop_lua_handlefile(L, script_path, true))
return 0;
return 1;
}
#endif
/* ****************************************** */
/**
* @brief Return true if login has been disabled
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK and push the return code into the Lua stack
*/
static int ntop_is_login_disabled(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
bool ret = ntop->getPrefs()->is_localhost_users_login_disabled()
|| !ntop->getPrefs()->is_users_login_enabled();
lua_pushboolean(vm, ret);
return(CONST_LUA_OK);
}
/* ****************************************** */
/**
* @brief Convert the network Id to a symbolic name (network/mask)
*
* @param vm The lua state.
* @return @ref CONST_LUA_OK and push the return code into the Lua stack
*/
static int ntop_network_name_by_id(lua_State* vm) {
int id;
char *name;
ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
id = (u_int32_t)lua_tonumber(vm, 1);
name = ntop->getLocalNetworkName(id);
lua_pushstring(vm, name ? name : "");
return(CONST_LUA_OK);
}
/* ****************************************** */
static int ntop_set_logging_level(lua_State* vm) {
char *lvlStr;
ntop->getTrace()->traceEvent(TRACE_INFO, "%s() called", __FUNCTION__);
if(ntop->getPrefs()->hasCmdlTraceLevel()) return(CONST_LUA_OK);
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR);
lvlStr = (char*)lua_tostring(vm, 1);
if(!strcmp(lvlStr, "trace")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_TRACE);
}
else if(!strcmp(lvlStr, "debug")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_DEBUG);
}
else if(!strcmp(lvlStr, "info")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_INFO);
}
else if(!strcmp(lvlStr, "normal")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_NORMAL);
}
else if(!strcmp(lvlStr, "warning")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_WARNING);
}
else if(!strcmp(lvlStr, "error")){
ntop->getTrace()->set_trace_level(TRACE_LEVEL_ERROR);
}
else{
return(CONST_LUA_ERROR);
}
return(CONST_LUA_OK);
}
/* ****************************************** */
static const luaL_Reg ntop_interface_reg[] = {
{ "getDefaultIfName", ntop_get_default_interface_name },
{ "setActiveInterfaceId", ntop_set_active_interface_id },
{ "getIfNames", ntop_get_interface_names },
{ "select", ntop_select_interface },
{ "getStats", ntop_get_interface_stats },
{ "resetCounters", ntop_interface_reset_counters },
{ "getnDPIStats", ntop_get_ndpi_interface_stats },
{ "getnDPIProtoName", ntop_get_ndpi_protocol_name },
{ "getnDPIProtoId", ntop_get_ndpi_protocol_id },
{ "getnDPIProtoCategory", ntop_get_ndpi_protocol_category },
{ "getnDPIFlowsCount", ntop_get_ndpi_interface_flows_count },
{ "getFlowsStatus", ntop_get_ndpi_interface_flows_status },
{ "getnDPIProtoBreed", ntop_get_ndpi_protocol_breed },
{ "getnDPIProtocols", ntop_get_ndpi_protocols },
{ "getnDPICategories", ntop_get_ndpi_categories },
{ "getHostsInfo", ntop_get_interface_hosts_info },
{ "getLocalHostsInfo", ntop_get_interface_local_hosts_info },
{ "getRemoteHostsInfo", ntop_get_interface_remote_hosts_info },
{ "getHostActivity", ntop_get_interface_host_activity },
{ "getHostInfo", ntop_get_interface_host_info },
{ "getGroupedHosts", ntop_get_grouped_interface_hosts },
{ "getNetworksStats", ntop_get_interface_networks_stats },
{ "resetPeriodicStats", ntop_host_reset_periodic_stats },
{ "correlateHostActivity", ntop_correalate_host_activity },
{ "similarHostActivity", ntop_similar_host_activity },
{ "getHostActivityMap", ntop_get_interface_host_activitymap },
{ "restoreHost", ntop_restore_interface_host },
{ "getFlowsInfo", ntop_get_interface_flows_info },
{ "getLocalFlowsInfo", ntop_get_interface_local_flows_info },
{ "getRemoteFlowsInfo", ntop_get_interface_remote_flows_info },
{ "getFlowsStats", ntop_get_interface_flows_stats },
{ "getFlowKey", ntop_get_interface_flow_key },
{ "findFlowByKey", ntop_get_interface_find_flow_by_key },
{ "dropFlowTraffic", ntop_drop_flow_traffic },
{ "dumpFlowTraffic", ntop_dump_flow_traffic },
{ "dumpLocalHosts2redis", ntop_dump_local_hosts_2_redis },
{ "findUserFlows", ntop_get_interface_find_user_flows },
{ "findPidFlows", ntop_get_interface_find_pid_flows },
{ "findFatherPidFlows", ntop_get_interface_find_father_pid_flows },
{ "findNameFlows", ntop_get_interface_find_proc_name_flows },
{ "listHTTPhosts", ntop_list_http_hosts },
{ "findHost", ntop_get_interface_find_host },
{ "updateHostTrafficPolicy", ntop_update_host_traffic_policy },
{ "updateHostAlertPolicy", ntop_update_host_alert_policy },
{ "setSecondTraffic", ntop_set_second_traffic },
{ "setHostDumpPolicy", ntop_set_host_dump_policy },
{ "setHostQuota", ntop_set_host_quota },
{ "getPeerHitRate", ntop_get_host_hit_rate },
{ "getLatestActivityHostsInfo", ntop_get_interface_latest_activity_hosts_info },
{ "getInterfaceDumpDiskPolicy", ntop_get_interface_dump_disk_policy },
{ "getInterfaceDumpTapPolicy", ntop_get_interface_dump_tap_policy },
{ "getInterfaceDumpTapName", ntop_get_interface_dump_tap_name },
{ "getInterfaceDumpMaxPkts", ntop_get_interface_dump_max_pkts },
{ "getInterfaceDumpMaxSec", ntop_get_interface_dump_max_sec },
{ "getInterfaceDumpMaxFiles", ntop_get_interface_dump_max_files },
{ "getInterfacePacketsDumpedFile", ntop_get_interface_pkts_dumped_file },
{ "getInterfacePacketsDumpedTap", ntop_get_interface_pkts_dumped_tap },
{ "getEndpoint", ntop_get_interface_endpoint },
{ "isPacketInterface", ntop_interface_is_packet_interface },
{ "isBridgeInterface", ntop_interface_is_bridge_interface },
{ "isPcapDumpInterface", ntop_interface_is_pcap_dump_interface },
{ "isRunning", ntop_interface_is_running },
{ "isIdle", ntop_interface_is_idle },
{ "setInterfaceIdleState", ntop_interface_set_idle },
{ "name2id", ntop_interface_name2id },
{ "loadDumpPrefs", ntop_load_dump_prefs },
{ "loadScalingFactorPrefs", ntop_load_scaling_factor_prefs },
{ "loadHostAlertPrefs", ntop_interface_load_host_alert_prefs },
/* Mac */
{ "getMacsInfo", ntop_get_interface_macs_info },
{ "getMacInfo", ntop_get_interface_mac_info },
/* L7 */
{ "reloadL7Rules", ntop_reload_l7_rules },
{ "reloadShapers", ntop_reload_shapers },
/* Host pools */
{ "reloadHostPools", ntop_reload_host_pools },
#ifdef NTOPNG_PRO
{ "getHostPoolsStats", ntop_get_host_pool_interface_stats },
{ "getHostPoolsVolatileMembers", ntop_get_host_pool_volatile_members },
{ "purgeExpiredPoolsMembers", ntop_purge_expired_host_pools_members },
{ "removeVolatileMemberFromPool", ntop_remove_volatile_member_from_pool },
#endif
/* DB */
{ "execSQLQuery", ntop_interface_exec_sql_query },
/* Flows */
{ "getFlowDevices", ntop_getflowdevices },
{ "getFlowDeviceInfo", ntop_getflowdeviceinfo },
/* New generation alerts */
{ "getCachedNumAlerts", ntop_interface_get_cached_num_alerts },
{ "queryAlertsRaw", ntop_interface_query_alerts_raw },
{ "queryFlowAlertsRaw", ntop_interface_query_flow_alerts_raw },
{ "engageHostAlert", ntop_interface_engage_host_alert },
{ "releaseHostAlert", ntop_interface_release_host_alert },
{ "engageNetworkAlert", ntop_interface_engage_network_alert },
{ "releaseNetworkAlert", ntop_interface_release_network_alert },
{ "engageInterfaceAlert", ntop_interface_engage_interface_alert },
{ "releaseInterfaceAlert",ntop_interface_release_interface_alert },
{ "enableHostAlerts", ntop_interface_host_enable_alerts },
{ "disableHostAlerts", ntop_interface_host_disable_alerts },
{ "refreshNumAlerts", ntop_interface_refresh_num_alerts },
{ "makeRoomAlerts", ntop_interface_make_room_alerts },
{ "makeRoomRequested", ntop_interface_make_room_requested },
{ NULL, NULL }
};
/* **************************************************************** */
static const luaL_Reg ntop_reg[] = {
{ "getDirs", ntop_get_dirs },
{ "getInfo", ntop_get_info },
{ "getUptime", ntop_get_uptime },
{ "dumpFile", ntop_dump_file },
{ "checkLicense", ntop_check_license },
/* Redis */
{ "getCache", ntop_get_redis },
{ "setCache", ntop_set_redis },
{ "delCache", ntop_delete_redis_key },
{ "listIndexCache", ntop_list_index_redis },
{ "lpushCache", ntop_lpush_redis },
{ "lpopCache", ntop_lpop_redis },
{ "lrangeCache", ntop_lrange_redis },
{ "setMembersCache", ntop_add_set_member_redis },
{ "delMembersCache", ntop_del_set_member_redis },
{ "getMembersCache", ntop_get_set_members_redis },
{ "getHashCache", ntop_get_hash_redis },
{ "setHashCache", ntop_set_hash_redis },
{ "delHashCache", ntop_del_hash_redis },
{ "getHashKeysCache",ntop_get_hash_keys_redis },
{ "getKeysCache", ntop_get_keys_redis },
{ "delHashCache", ntop_delete_hash_redis_key },
{ "setPopCache", ntop_get_redis_set_pop },
{ "getHostId", ntop_redis_get_host_id },
{ "getIdToHost", ntop_redis_get_id_to_host },
/* Redis Preferences */
{ "setPref", ntop_set_redis_preference },
{ "getPref", ntop_get_redis },
{ "isdir", ntop_is_dir },
{ "mkdir", ntop_mkdir_tree },
{ "notEmptyFile", ntop_is_not_empty_file },
{ "exists", ntop_get_file_dir_exists },
{ "listReports", ntop_list_reports },
{ "fileLastChange", ntop_get_file_last_change },
{ "readdir", ntop_list_dir_files },
{ "rmdir", ntop_remove_dir_recursively },
{ "zmq_connect", ntop_zmq_connect },
{ "zmq_disconnect", ntop_zmq_disconnect },
{ "zmq_receive", ntop_zmq_receive },
{ "getLocalNetworks", ntop_get_local_networks },
{ "reloadPreferences", ntop_reload_preferences },
#ifdef NTOPNG_PRO
{ "sendNagiosAlert", ntop_nagios_send_alert },
{ "withdrawNagiosAlert", ntop_nagios_withdraw_alert },
{ "reloadNagiosConfig", ntop_nagios_reload_config },
{ "checkProfileSyntax", ntop_check_profile_syntax },
{ "reloadProfiles", ntop_reload_traffic_profiles },
#endif
/* Pro */
{ "isPro", ntop_is_pro },
{ "isEnterprise", ntop_is_enterprise },
/* Historical database */
{ "insertMinuteSampling", ntop_stats_insert_minute_sampling },
{ "insertHourSampling", ntop_stats_insert_hour_sampling },
{ "insertDaySampling", ntop_stats_insert_day_sampling },
{ "getMinuteSampling", ntop_stats_get_minute_sampling },
{ "deleteMinuteStatsOlderThan", ntop_stats_delete_minute_older_than },
{ "deleteHourStatsOlderThan", ntop_stats_delete_hour_older_than },
{ "deleteDayStatsOlderThan", ntop_stats_delete_day_older_than },
{ "getMinuteSamplingsFromEpoch", ntop_stats_get_samplings_of_minutes_from_epoch },
{ "getHourSamplingsFromEpoch", ntop_stats_get_samplings_of_hours_from_epoch },
{ "getDaySamplingsFromEpoch", ntop_stats_get_samplings_of_days_from_epoch },
{ "getMinuteSamplingsInterval", ntop_stats_get_minute_samplings_interval },
{ "deleteDumpFiles", ntop_delete_dump_files },
/* Time */
{ "gettimemsec", ntop_gettimemsec },
/* Trace */
{ "verboseTrace", ntop_verbose_trace },
/* UDP */
{ "send_udp_data", ntop_send_udp_data },
/* IP */
{ "inet_ntoa", ntop_inet_ntoa },
/* RRD */
{ "rrd_create", ntop_rrd_create },
{ "rrd_update", ntop_rrd_update },
{ "rrd_fetch", ntop_rrd_fetch },
{ "rrd_fetch_columns", ntop_rrd_fetch_columns },
{ "rrd_lastupdate", ntop_rrd_lastupdate },
/* Prefs */
{ "getPrefs", ntop_get_prefs },
/* HTTP */
{ "httpRedirect", ntop_http_redirect },
{ "httpGet", ntop_http_get },
{ "getHttpPrefix", ntop_http_get_prefix },
/* Admin */
{ "getNologinUser", ntop_get_nologin_username },
{ "getUsers", ntop_get_users },
{ "getUserGroup", ntop_get_user_group },
{ "getAllowedNetworks", ntop_get_allowed_networks },
{ "resetUserPassword", ntop_reset_user_password },
{ "changeUserRole", ntop_change_user_role },
{ "changeAllowedNets", ntop_change_allowed_nets },
{ "changeAllowedIfname",ntop_change_allowed_ifname },
{ "changeUserHostPool", ntop_change_user_host_pool },
{ "addUser", ntop_add_user },
{ "addUserLifetime", ntop_add_user_lifetime },
{ "clearUserLifetime", ntop_clear_user_lifetime },
{ "deleteUser", ntop_delete_user },
{ "isLoginDisabled", ntop_is_login_disabled },
{ "getNetworkNameById", ntop_network_name_by_id },
/* Security */
{ "getRandomCSRFValue", ntop_generate_csrf_value },
/* HTTP */
{ "postHTTPJsonData", ntop_post_http_json_data },
/* Address Resolution */
{ "resolveAddress", ntop_resolve_address },
{ "getResolvedAddress", ntop_get_resolved_address },
/* Logging */
{ "syslog", ntop_syslog },
{ "setLoggingLevel",ntop_set_logging_level },
/* SNMP */
{ "snmpget", ntop_snmpget },
{ "snmpgetnext", ntop_snmpgetnext },
/* SQLite */
{ "execQuery", ntop_sqlite_exec_query },
/* Runtime */
{ "hasVLANs", ntop_has_vlans },
{ "hasGeoIP", ntop_has_geoip },
{ "isWindows", ntop_is_windows },
/* Host Blacklist */
{ "allocHostBlacklist", ntop_allocHostBlacklist },
{ "swapHostBlacklist", ntop_swapHostBlacklist },
{ "addToHostBlacklist", ntop_addToHostBlacklist },
/* Misc */
{ "getservbyport", ntop_getservbyport },
{ "getMacManufacturer", ntop_get_mac_manufacturer },
{ "getSiteCategories", ntop_get_site_categories },
{ NULL, NULL}
};
/* ****************************************** */
void Lua::lua_register_classes(lua_State *L, bool http_mode) {
static const luaL_Reg _meta[] = { { NULL, NULL } };
int i;
ntop_class_reg ntop_lua_reg[] = {
{ "interface", ntop_interface_reg },
{ "ntop", ntop_reg },
{NULL, NULL}
};
if(!L) return;
luaopen_lsqlite3(L);
for(i=0; ntop_lua_reg[i].class_name != NULL; i++) {
int lib_id, meta_id;
/* newclass = {} */
lua_createtable(L, 0, 0);
lib_id = lua_gettop(L);
/* metatable = {} */
luaL_newmetatable(L, ntop_lua_reg[i].class_name);
meta_id = lua_gettop(L);
luaL_register(L, NULL, _meta);
/* metatable.__index = class_methods */
lua_newtable(L), luaL_register(L, NULL, ntop_lua_reg[i].class_methods);
lua_setfield(L, meta_id, "__index");
/* class.__metatable = metatable */
lua_setmetatable(L, lib_id);
/* _G["Foo"] = newclass */
lua_setglobal(L, ntop_lua_reg[i].class_name);
}
if(http_mode) {
/* Overload the standard Lua print() with ntop_lua_http_print that dumps data on HTTP server */
lua_register(L, "print", ntop_lua_http_print);
} else
lua_register(L, "print", ntop_lua_cli_print);
#ifdef NTOPNG_PRO
if(ntop->getPro()->has_valid_license()) {
lua_register(L, "ntopRequire", ntop_lua_require);
luaL_dostring(L, "table.insert(package.loaders, 1, ntopRequire)");
lua_register(L, "dofile", ntop_lua_dofile);
}
#endif
}
/* ****************************************** */
#if 0
/**
* Iterator over key-value pairs where the value
* maybe made available in increments and/or may
* not be zero-terminated. Used for processing
* POST data.
*
* @param cls user-specified closure
* @param kind type of the value
* @param key 0-terminated key for the value
* @param filename name of the uploaded file, NULL if not known
* @param content_type mime-type of the data, NULL if not known
* @param transfer_encoding encoding of the data, NULL if not known
* @param data pointer to size bytes of data at the
* specified offset
* @param off offset of data in the overall value
* @param size number of bytes in data available
* @return MHD_YES to continue iterating,
* MHD_NO to abort the iteration
*/
static int post_iterator(void *cls,
enum MHD_ValueKind kind,
const char *key,
const char *filename,
const char *content_type,
const char *transfer_encoding,
const char *data, uint64_t off, size_t size)
{
struct Request *request = cls;
char tmp[1024];
u_int len = min(size, sizeof(tmp)-1);
memcpy(tmp, &data[off], len);
tmp[len] = '\0';
fprintf(stdout, "[POST] [%s][%s]\n", key, tmp);
return MHD_YES;
}
#endif
/* ****************************************** */
/*
Run a Lua script from within ntopng (no HTTP GUI)
*/
int Lua::run_script(char *script_path) {
int rc = 0;
if(!L) return(-1);
try {
luaL_openlibs(L); /* Load base libraries */
lua_register_classes(L, false); /* Load custom classes */
#ifndef NTOPNG_PRO
rc = luaL_dofile(L, script_path);
#else
if(ntop->getPro()->has_valid_license())
rc = __ntop_lua_handlefile(L, script_path, true);
else
rc = luaL_dofile(L, script_path);
#endif
if(rc != 0) {
const char *err = lua_tostring(L, -1);
ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err);
rc = -1;
}
} catch(...) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s]", script_path);
rc = -2;
}
return(rc);
}
/* ****************************************** */
/* http://www.geekhideout.com/downloads/urlcode.c */
#if 0
/* Converts an integer value to its hex character*/
static char to_hex(char code) {
static char hex[] = "0123456789abcdef";
return hex[code & 15];
}
/* ****************************************** */
/* Returns a url-encoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
static char* http_encode(char *str) {
char *pstr = str, *buf = (char*)malloc(strlen(str) * 3 + 1), *pbuf = buf;
while (*pstr) {
if(isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
*pbuf++ = *pstr;
else if(*pstr == ' ')
*pbuf++ = '+';
else
*pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
pstr++;
}
*pbuf = '\0';
return buf;
}
#endif
/* ****************************************** */
void Lua::purifyHTTPParameter(char *param) {
char *ampercent;
if((ampercent = strchr(param, '%')) != NULL) {
/* We allow only a few chars, removing all the others */
if((ampercent[1] != 0) && (ampercent[2] != 0)) {
char c;
char b = ampercent[3];
ampercent[3] = '\0';
c = (char)strtol(&ercent[1], NULL, 16);
ampercent[3] = b;
switch(c) {
case '/':
case ':':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case '?':
case '!':
case '$':
case ',':
case '^':
case '*':
case '_':
case '&':
case ' ':
case '=':
case '<':
case '>':
case '@':
case '#':
break;
default:
if(!Utils::isPrintableChar(c)) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded char '0x%02x' in URI [%s]", c, param);
ampercent[0] = '\0';
return;
}
}
purifyHTTPParameter(&ercent[3]);
} else
ampercent[0] = '\0';
}
}
/* ****************************************** */
void Lua::setInterface(const char *user) {
char key[64], ifname[MAX_INTERFACE_NAME_LEN];
bool enforce_allowed_interface = false;
if(user[0] != '\0') {
// check if the user is restricted to browse only a given interface
if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user)
&& !ntop->getRedis()->get(key, ifname, sizeof(ifname))) {
// there is only one allowed interface for the user
enforce_allowed_interface = true;
goto set_preferred_interface;
} else if(snprintf(key, sizeof(key), "ntopng.prefs.%s.ifname", user)
&& ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) {
// no allowed interface and no default set interface
set_default_if_name_in_session:
snprintf(ifname, sizeof(ifname), "%s",
ntop->getInterfaceAtId(NULL /* allowed user interface check already enforced */,
0)->get_name());
lua_push_str_table_entry(L, "ifname", ifname);
ntop->getRedis()->set(key, ifname, 3600 /* 1h */);
} else {
goto set_preferred_interface;
}
} else {
// We need to check if ntopng is running with the option --disable-login
snprintf(key, sizeof(key), "ntopng.prefs.ifname");
if(ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) {
goto set_preferred_interface;
}
set_preferred_interface:
NetworkInterface *iface;
if((iface = ntop->getNetworkInterface(NULL /* allowed user interface check already enforced */,
ifname)) != NULL) {
/* The specified interface still exists */
lua_push_str_table_entry(L, "ifname", iface->get_name());
} else if(!enforce_allowed_interface) {
goto set_default_if_name_in_session;
} else {
// TODO: handle the case where the user has
// an allowed interface that is not presently available
// (e.g., not running?)
}
}
}
/* ****************************************** */
void Lua::setParamsTable(lua_State* vm, const char* table_name,
const char* query) const {
char outbuf[FILENAME_MAX];
char *where;
char *tok;
char *query_string = query ? strdup(query) : NULL;
lua_newtable(L);
if (query_string) {
// ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] %s", query_string);
tok = strtok_r(query_string, "&", &where);
while(tok != NULL) {
char *_equal;
if(strncmp(tok, "csrf", strlen("csrf")) /* Do not put csrf into the params table */
&& (_equal = strchr(tok, '='))
&& (strlen(_equal) > 1)) {
char *decoded_buf;
int len;
_equal[0] = '\0';
_equal = &_equal[1];
len = strlen(_equal);
purifyHTTPParameter(tok), purifyHTTPParameter(_equal);
// ntop->getTrace()->traceEvent(TRACE_WARNING, "%s = %s", tok, _equal);
if((decoded_buf = (char*)malloc(len+1)) != NULL) {
Utils::urlDecode(_equal, decoded_buf, len+1);
Utils::purifyHTTPparam(tok, true, false);
Utils::purifyHTTPparam(decoded_buf, false, false);
/* Now make sure that decoded_buf is not a file path */
FILE *fd;
if((decoded_buf[0] == '.')
&& ((fd = fopen(decoded_buf, "r"))
|| (fd = fopen(realpath(decoded_buf, outbuf), "r")))) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded '%s'='%s' as argument is a valid file path",
tok, decoded_buf);
decoded_buf[0] = '\0';
fclose(fd);
}
/* ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, decoded_buf); */
/* put tok and the decoded buffer in to the table */
lua_push_str_table_entry(vm, tok, decoded_buf);
free(decoded_buf);
} else
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
}
tok = strtok_r(NULL, "&", &where);
} /* while */
}
if(query_string) free(query_string);
if(table_name)
lua_setglobal(L, table_name);
else
lua_setglobal(L, (char*)"_GET"); /* Default */
}
/* ****************************************** */
int Lua::handle_script_request(struct mg_connection *conn,
const struct mg_request_info *request_info,
char *script_path) {
char buf[64], key[64], ifname[MAX_INTERFACE_NAME_LEN];
char *_cookies, user[64] = { '\0' };
AddressTree ptree;
int rc;
const char * content_type;
if(!L) return(-1);
luaL_openlibs(L); /* Load base libraries */
lua_register_classes(L, true); /* Load custom classes */
lua_pushlightuserdata(L, (char*)conn);
lua_setglobal(L, CONST_HTTP_CONN);
content_type = mg_get_header(conn, "Content-Type");
/* Check for POST requests */
if((strcmp(request_info->request_method, "POST") == 0) &&
((content_type != NULL) && (strstr(content_type, "application/x-www-form-urlencoded") == content_type))) {
char post_data[1024] = { '\0' };
char rsp[32];
char csrf[64] = { '\0' };
char user[64] = { '\0' };
int post_data_len = mg_read(conn, post_data, sizeof(post_data));
u_int8_t valid_csrf = 1;
post_data[sizeof(post_data)-1] = '\0';
/* CSRF is mandatory in POST request */
mg_get_var(post_data, post_data_len, "csrf", csrf, sizeof(csrf));
mg_get_cookie(conn, "user", user, sizeof(user));
if((ntop->getRedis()->get(csrf, rsp, sizeof(rsp)) == -1)
|| (strcmp(rsp, user) != 0)) {
#if 0
const char *msg = "The submitted form is expired. Please reload the page and try again. <p>[ <A HREF=/>Home</A> ]";
ntop->getTrace()->traceEvent(TRACE_WARNING,
"Invalid CSRF parameter specified [%s][%s][%s][%s]: page expired?",
csrf, rsp, user, "csrf");
return(send_error(conn, 500 /* Internal server error */,
msg, PAGE_ERROR, script_path, msg));
#else
valid_csrf = 0;
#endif
} else {
/* Invalidate csrf */
ntop->getRedis()->del(csrf);
}
if(valid_csrf)
setParamsTable(L, "_POST", post_data); /* CSRF is valid here, now fill the _POST table with POST parameters */
else
setParamsTable(L, "_POST", NULL /* Empty */);
} else
setParamsTable(L, "_POST", NULL /* Empty */);
/* Put the GET params into the environment */
if(request_info->query_string)
setParamsTable(L, "_GET", request_info->query_string);
else
setParamsTable(L, "_GET", NULL /* Empty */);
/* _SERVER */
lua_newtable(L);
lua_push_str_table_entry(L, "REQUEST_METHOD", (char*)request_info->request_method);
lua_push_str_table_entry(L, "URI", (char*)request_info->uri ? (char*)request_info->uri : (char*)"");
lua_push_str_table_entry(L, "REFERER", (char*)mg_get_header(conn, "Referer") ? (char*)mg_get_header(conn, "Referer") : (char*)"");
if(request_info->remote_user) lua_push_str_table_entry(L, "REMOTE_USER", (char*)request_info->remote_user);
if(request_info->query_string) lua_push_str_table_entry(L, "QUERY_STRING", (char*)request_info->query_string);
for(int i=0; ((request_info->http_headers[i].name != NULL)
&& request_info->http_headers[i].name[0] != '\0'); i++)
lua_push_str_table_entry(L,
request_info->http_headers[i].name,
(char*)request_info->http_headers[i].value);
lua_setglobal(L, (char*)"_SERVER");
/* Cookies */
lua_newtable(L);
if((_cookies = (char*)mg_get_header(conn, "Cookie")) != NULL) {
char *cookies = strdup(_cookies);
char *tok, *where;
// ntop->getTrace()->traceEvent(TRACE_WARNING, "=> '%s'", cookies);
tok = strtok_r(cookies, "=", &where);
while(tok != NULL) {
char *val;
while(tok[0] == ' ') tok++;
if((val = strtok_r(NULL, ";", &where)) != NULL) {
lua_push_str_table_entry(L, tok, val);
// ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, val);
} else
break;
tok = strtok_r(NULL, "=", &where);
}
free(cookies);
}
lua_setglobal(L, "_COOKIE"); /* Like in php */
/* Put the _SESSION params into the environment */
lua_newtable(L);
mg_get_cookie(conn, "user", user, sizeof(user));
lua_push_str_table_entry(L, "user", user);
mg_get_cookie(conn, "session", buf, sizeof(buf));
lua_push_str_table_entry(L, "session", buf);
// now it's time to set the interface.
setInterface(user);
lua_setglobal(L, "_SESSION"); /* Like in php */
if(user[0] != '\0') {
char val[255];
lua_pushlightuserdata(L, user);
lua_setglobal(L, "user");
snprintf(key, sizeof(key), "ntopng.user.%s.allowed_nets", user);
if((ntop->getRedis()->get(key, val, sizeof(val)) != -1)
&& (val[0] != '\0')) {
ptree.addAddresses(val);
lua_pushlightuserdata(L, &ptree);
lua_setglobal(L, CONST_ALLOWED_NETS);
// ntop->getTrace()->traceEvent(TRACE_WARNING, "SET %p", ptree);
}
snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user);
if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user)
&& !ntop->getRedis()->get(key, ifname, sizeof(ifname))) {
lua_pushlightuserdata(L, ifname);
lua_setglobal(L, CONST_ALLOWED_IFNAME);
}
}
#ifndef NTOPNG_PRO
rc = luaL_dofile(L, script_path);
#else
if(ntop->getPro()->has_valid_license())
rc = __ntop_lua_handlefile(L, script_path, true);
else
rc = luaL_dofile(L, script_path);
#endif
if(rc != 0) {
const char *err = lua_tostring(L, -1);
ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err);
return(send_error(conn, 500 /* Internal server error */,
"Internal server error", PAGE_ERROR, script_path, err));
}
return(CONST_LUA_OK);
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_3266_0 |
crossvul-cpp_data_bad_2609_0 | /*****************************************************************
|
| AP4 - Atom Based Sample Tables
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This atom is part of AP4 (MP4 Audio Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the atom COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4AtomSampleTable.h"
#include "Ap4ByteStream.h"
#include "Ap4StsdAtom.h"
#include "Ap4StscAtom.h"
#include "Ap4StcoAtom.h"
#include "Ap4Co64Atom.h"
#include "Ap4StszAtom.h"
#include "Ap4Stz2Atom.h"
#include "Ap4SttsAtom.h"
#include "Ap4CttsAtom.h"
#include "Ap4StssAtom.h"
#include "Ap4Sample.h"
#include "Ap4Atom.h"
/*----------------------------------------------------------------------
| AP4_AtomSampleTable Dynamic Cast Anchor
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AtomSampleTable)
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::AP4_AtomSampleTable
+---------------------------------------------------------------------*/
AP4_AtomSampleTable::AP4_AtomSampleTable(AP4_ContainerAtom* stbl,
AP4_ByteStream& sample_stream) :
m_SampleStream(sample_stream)
{
m_StscAtom = AP4_DYNAMIC_CAST(AP4_StscAtom, stbl->GetChild(AP4_ATOM_TYPE_STSC));
m_StcoAtom = AP4_DYNAMIC_CAST(AP4_StcoAtom, stbl->GetChild(AP4_ATOM_TYPE_STCO));
m_StszAtom = AP4_DYNAMIC_CAST(AP4_StszAtom, stbl->GetChild(AP4_ATOM_TYPE_STSZ));
m_Stz2Atom = AP4_DYNAMIC_CAST(AP4_Stz2Atom, stbl->GetChild(AP4_ATOM_TYPE_STZ2));
m_CttsAtom = AP4_DYNAMIC_CAST(AP4_CttsAtom, stbl->GetChild(AP4_ATOM_TYPE_CTTS));
m_SttsAtom = AP4_DYNAMIC_CAST(AP4_SttsAtom, stbl->GetChild(AP4_ATOM_TYPE_STTS));
m_StssAtom = AP4_DYNAMIC_CAST(AP4_StssAtom, stbl->GetChild(AP4_ATOM_TYPE_STSS));
m_StsdAtom = AP4_DYNAMIC_CAST(AP4_StsdAtom, stbl->GetChild(AP4_ATOM_TYPE_STSD));
m_Co64Atom = AP4_DYNAMIC_CAST(AP4_Co64Atom, stbl->GetChild(AP4_ATOM_TYPE_CO64));
// keep a reference to the sample stream
m_SampleStream.AddReference();
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::~AP4_AtomSampleTable
+---------------------------------------------------------------------*/
AP4_AtomSampleTable::~AP4_AtomSampleTable()
{
m_SampleStream.Release();
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
AP4_Sample& sample)
{
AP4_Result result;
// check that we have a chunk offset table
if (m_StcoAtom == NULL && m_Co64Atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// MP4 uses 1-based indexes internally, so adjust by one
index++;
// find out in which chunk this sample is located
AP4_Ordinal chunk, skip, desc;
result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);
if (AP4_FAILED(result)) return result;
// check that the result is within bounds
if (skip > index) return AP4_ERROR_INTERNAL;
// get the atom offset for this chunk
AP4_UI64 offset;
if (m_StcoAtom) {
AP4_UI32 offset_32;
result = m_StcoAtom->GetChunkOffset(chunk, offset_32);
offset = offset_32;
} else {
result = m_Co64Atom->GetChunkOffset(chunk, offset);
}
if (AP4_FAILED(result)) return result;
// compute the additional offset inside the chunk
for (unsigned int i = index-skip; i < index; i++) {
AP4_Size size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(i, size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(i, size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
offset += size;
}
// set the description index
sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes
// set the dts and cts
AP4_UI32 cts_offset = 0;
AP4_UI64 dts = 0;
AP4_UI32 duration = 0;
result = m_SttsAtom->GetDts(index, dts, &duration);
if (AP4_FAILED(result)) return result;
sample.SetDuration(duration);
sample.SetDts(dts);
if (m_CttsAtom == NULL) {
sample.SetCts(dts);
} else {
result = m_CttsAtom->GetCtsOffset(index, cts_offset);
if (AP4_FAILED(result)) return result;
sample.SetCtsDelta(cts_offset);
}
// set the size
AP4_Size sample_size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(index, sample_size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(index, sample_size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
sample.SetSize(sample_size);
// set the sync flag
if (m_StssAtom == NULL) {
sample.SetSync(true);
} else {
sample.SetSync(m_StssAtom->IsSampleSync(index));
}
// set the offset
sample.SetOffset(offset);
// set the data stream
sample.SetDataStream(m_SampleStream);
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleCount
+---------------------------------------------------------------------*/
AP4_Cardinal
AP4_AtomSampleTable::GetSampleCount()
{
if (m_StszAtom) {
return m_StszAtom->GetSampleCount();
} else if (m_Stz2Atom) {
return m_Stz2Atom->GetSampleCount();
} else {
return 0;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleDescription
+---------------------------------------------------------------------*/
AP4_SampleDescription*
AP4_AtomSampleTable::GetSampleDescription(AP4_Ordinal index)
{
return m_StsdAtom ? m_StsdAtom->GetSampleDescription(index) : NULL;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleDescriptionCount
+---------------------------------------------------------------------*/
AP4_Cardinal
AP4_AtomSampleTable::GetSampleDescriptionCount()
{
return m_StsdAtom ? m_StsdAtom->GetSampleDescriptionCount() : 0;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleChunkPosition
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
AP4_Ordinal sample_description_index;
return GetChunkForSample(sample_index,
chunk_index,
position_in_chunk,
sample_description_index);
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkForSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetChunkForSample(AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk,
AP4_Ordinal& sample_description_index)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
sample_description_index = 0;
// check that we an stsc atom
if (m_StscAtom == NULL) return AP4_ERROR_INVALID_STATE;
// get the chunk info from the stsc atom
AP4_Ordinal chunk = 0;
AP4_Result result = m_StscAtom->GetChunkForSample(sample_index+1, // the atom API is 1-based
chunk,
position_in_chunk,
sample_description_index);
if (AP4_FAILED(result)) return result;
if (chunk == 0) return AP4_ERROR_INTERNAL;
// the atom sample and chunk indexes are 1-based, so we need to translate
chunk_index = chunk-1;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkOffset
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position& offset)
{
if (m_StcoAtom) {
AP4_UI32 offset_32;
AP4_Result result = m_StcoAtom->GetChunkOffset(chunk_index+1, offset_32);
if (AP4_SUCCEEDED(result)) {
offset = offset_32;
} else {
offset = 0;
}
return result;
} else if (m_Co64Atom) {
return m_Co64Atom->GetChunkOffset(chunk_index+1, offset);
} else {
offset = 0;
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetChunkOffset
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::SetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position offset)
{
if (m_StcoAtom) {
if ((offset >> 32) != 0) return AP4_ERROR_OUT_OF_RANGE;
return m_StcoAtom->SetChunkOffset(chunk_index+1, (AP4_UI32)offset);
} else if (m_Co64Atom) {
return m_Co64Atom->SetChunkOffset(chunk_index+1, offset);
} else {
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetSampleSize
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::SetSampleSize(AP4_Ordinal sample_index, AP4_Size size)
{
if (m_StszAtom) {
return m_StszAtom->SetSampleSize(sample_index+1, size);
} else if (m_Stz2Atom) {
return m_Stz2Atom->SetSampleSize(sample_index+1, size);
} else {
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleIndexForTimeStamp
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 ts,
AP4_Ordinal& sample_index)
{
return m_SttsAtom ? m_SttsAtom->GetSampleIndexForTimeStamp(ts, sample_index)
: AP4_FAILURE;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetNearestSyncSampleIndex
+---------------------------------------------------------------------*/
AP4_Ordinal
AP4_AtomSampleTable::GetNearestSyncSampleIndex(AP4_Ordinal sample_index, bool before)
{
// if we don't have an stss table, all samples match
if (m_StssAtom == NULL) return sample_index;
sample_index += 1; // the table is 1-based
AP4_Cardinal entry_count = m_StssAtom->GetEntries().ItemCount();
if (before) {
AP4_Ordinal cursor = 0;
for (unsigned int i=0; i<entry_count; i++) {
if (m_StssAtom->GetEntries()[i] >= sample_index) return cursor;
if (m_StssAtom->GetEntries()[i]) cursor = m_StssAtom->GetEntries()[i]-1;
}
// not found?
return cursor;
} else {
for (unsigned int i=0; i<entry_count; i++) {
if (m_StssAtom->GetEntries()[i] >= sample_index) {
return m_StssAtom->GetEntries()[i]?m_StssAtom->GetEntries()[i]-1:sample_index-1;
}
}
// not found?
return GetSampleCount();
}
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_2609_0 |
crossvul-cpp_data_bad_2609_1 | /*****************************************************************
|
| AP4 - avcC Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4AvccAtom.h"
#include "Ap4AtomFactory.h"
#include "Ap4Utils.h"
#include "Ap4Types.h"
/*----------------------------------------------------------------------
| dynamic cast support
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AvccAtom)
/*----------------------------------------------------------------------
| AP4_AvccAtom::GetProfileName
+---------------------------------------------------------------------*/
const char*
AP4_AvccAtom::GetProfileName(AP4_UI08 profile)
{
switch (profile) {
case AP4_AVC_PROFILE_BASELINE: return "Baseline";
case AP4_AVC_PROFILE_MAIN: return "Main";
case AP4_AVC_PROFILE_EXTENDED: return "Extended";
case AP4_AVC_PROFILE_HIGH: return "High";
case AP4_AVC_PROFILE_HIGH_10: return "High 10";
case AP4_AVC_PROFILE_HIGH_422: return "High 4:2:2";
case AP4_AVC_PROFILE_HIGH_444: return "High 4:4:4";
}
return NULL;
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::Create
+---------------------------------------------------------------------*/
AP4_AvccAtom*
AP4_AvccAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
// read the raw bytes in a buffer
unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
AP4_DataBuffer payload_data(payload_size);
AP4_Result result = stream.Read(payload_data.UseData(), payload_size);
if (AP4_FAILED(result)) return NULL;
// check the version
const AP4_UI08* payload = payload_data.GetData();
if (payload[0] != 1) {
return NULL;
}
// check the size
if (payload_size < 6) return NULL;
unsigned int num_seq_params = payload[5]&31;
unsigned int cursor = 6;
for (unsigned int i=0; i<num_seq_params; i++) {
if (cursor+2 > payload_size) return NULL;
cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);
if (cursor > payload_size) return NULL;
}
unsigned int num_pic_params = payload[cursor++];
if (cursor > payload_size) return NULL;
for (unsigned int i=0; i<num_pic_params; i++) {
if (cursor+2 > payload_size) return NULL;
cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);
if (cursor > payload_size) return NULL;
}
return new AP4_AvccAtom(size, payload);
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::AP4_AvccAtom
+---------------------------------------------------------------------*/
AP4_AvccAtom::AP4_AvccAtom() :
AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE),
m_ConfigurationVersion(1),
m_Profile(0),
m_Level(0),
m_ProfileCompatibility(0),
m_NaluLengthSize(0)
{
UpdateRawBytes();
m_Size32 += m_RawBytes.GetDataSize();
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::AP4_AvccAtom
+---------------------------------------------------------------------*/
AP4_AvccAtom::AP4_AvccAtom(const AP4_AvccAtom& other) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, other.m_Size32),
m_ConfigurationVersion(other.m_ConfigurationVersion),
m_Profile(other.m_Profile),
m_Level(other.m_Level),
m_ProfileCompatibility(other.m_ProfileCompatibility),
m_NaluLengthSize(other.m_NaluLengthSize),
m_RawBytes(other.m_RawBytes)
{
// deep copy of the parameters
unsigned int i = 0;
for (i=0; i<other.m_SequenceParameters.ItemCount(); i++) {
m_SequenceParameters.Append(other.m_SequenceParameters[i]);
}
for (i=0; i<other.m_PictureParameters.ItemCount(); i++) {
m_PictureParameters.Append(other.m_PictureParameters[i]);
}
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::AP4_AvccAtom
+---------------------------------------------------------------------*/
AP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, size)
{
// make a copy of our configuration bytes
unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
m_RawBytes.SetData(payload, payload_size);
// parse the payload
m_ConfigurationVersion = payload[0];
m_Profile = payload[1];
m_ProfileCompatibility = payload[2];
m_Level = payload[3];
m_NaluLengthSize = 1+(payload[4]&3);
AP4_UI08 num_seq_params = payload[5]&31;
m_SequenceParameters.EnsureCapacity(num_seq_params);
unsigned int cursor = 6;
for (unsigned int i=0; i<num_seq_params; i++) {
m_SequenceParameters.Append(AP4_DataBuffer());
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
m_SequenceParameters[i].SetData(&payload[cursor]+2, param_length);
cursor += 2+param_length;
}
AP4_UI08 num_pic_params = payload[cursor++];
m_PictureParameters.EnsureCapacity(num_pic_params);
for (unsigned int i=0; i<num_pic_params; i++) {
m_PictureParameters.Append(AP4_DataBuffer());
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
m_PictureParameters[i].SetData(&payload[cursor]+2, param_length);
cursor += 2+param_length;
}
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::AP4_AvccAtom
+---------------------------------------------------------------------*/
AP4_AvccAtom::AP4_AvccAtom(AP4_UI08 profile,
AP4_UI08 level,
AP4_UI08 profile_compatibility,
AP4_UI08 length_size,
const AP4_Array<AP4_DataBuffer>& sequence_parameters,
const AP4_Array<AP4_DataBuffer>& picture_parameters) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE),
m_ConfigurationVersion(1),
m_Profile(profile),
m_Level(level),
m_ProfileCompatibility(profile_compatibility),
m_NaluLengthSize(length_size)
{
// deep copy of the parameters
unsigned int i = 0;
for (i=0; i<sequence_parameters.ItemCount(); i++) {
m_SequenceParameters.Append(sequence_parameters[i]);
}
for (i=0; i<picture_parameters.ItemCount(); i++) {
m_PictureParameters.Append(picture_parameters[i]);
}
// compute the raw bytes
UpdateRawBytes();
// update the size
m_Size32 += m_RawBytes.GetDataSize();
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::UpdateRawBytes
+---------------------------------------------------------------------*/
void
AP4_AvccAtom::UpdateRawBytes()
{
// compute the payload size
unsigned int payload_size = 6;
for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
payload_size += 2+m_SequenceParameters[i].GetDataSize();
}
++payload_size;
for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {
payload_size += 2+m_PictureParameters[i].GetDataSize();
}
m_RawBytes.SetDataSize(payload_size);
AP4_UI08* payload = m_RawBytes.UseData();
payload[0] = m_ConfigurationVersion;
payload[1] = m_Profile;
payload[2] = m_ProfileCompatibility;
payload[3] = m_Level;
payload[4] = 0xFC | (m_NaluLengthSize-1);
payload[5] = 0xE0 | (AP4_UI08)m_SequenceParameters.ItemCount();
unsigned int cursor = 6;
for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
AP4_UI16 param_length = (AP4_UI16)m_SequenceParameters[i].GetDataSize();
AP4_BytesFromUInt16BE(&payload[cursor], param_length);
cursor += 2;
AP4_CopyMemory(&payload[cursor], m_SequenceParameters[i].GetData(), param_length);
cursor += param_length;
}
payload[cursor++] = (AP4_UI08)m_PictureParameters.ItemCount();
for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {
AP4_UI16 param_length = (AP4_UI16)m_PictureParameters[i].GetDataSize();
AP4_BytesFromUInt16BE(&payload[cursor], param_length);
cursor += 2;
AP4_CopyMemory(&payload[cursor], m_PictureParameters[i].GetData(), param_length);
cursor += param_length;
}
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_AvccAtom::WriteFields(AP4_ByteStream& stream)
{
return stream.Write(m_RawBytes.GetData(), m_RawBytes.GetDataSize());
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("Configuration Version", m_ConfigurationVersion);
const char* profile_name = GetProfileName(m_Profile);
if (profile_name) {
inspector.AddField("Profile", profile_name);
} else {
inspector.AddField("Profile", m_Profile);
}
inspector.AddField("Profile Compatibility", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX);
inspector.AddField("Level", m_Level);
inspector.AddField("NALU Length Size", m_NaluLengthSize);
for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
inspector.AddField("Sequence Parameter", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize());
}
for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
inspector.AddField("Picture Parameter", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize());
}
return AP4_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_2609_1 |
crossvul-cpp_data_bad_2809_0 | /*****************************************************************
|
| AP4 - Atom Based Sample Tables
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This atom is part of AP4 (MP4 Audio Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the atom COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4AtomSampleTable.h"
#include "Ap4ByteStream.h"
#include "Ap4StsdAtom.h"
#include "Ap4StscAtom.h"
#include "Ap4StcoAtom.h"
#include "Ap4Co64Atom.h"
#include "Ap4StszAtom.h"
#include "Ap4Stz2Atom.h"
#include "Ap4SttsAtom.h"
#include "Ap4CttsAtom.h"
#include "Ap4StssAtom.h"
#include "Ap4Sample.h"
#include "Ap4Atom.h"
/*----------------------------------------------------------------------
| AP4_AtomSampleTable Dynamic Cast Anchor
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AtomSampleTable)
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::AP4_AtomSampleTable
+---------------------------------------------------------------------*/
AP4_AtomSampleTable::AP4_AtomSampleTable(AP4_ContainerAtom* stbl,
AP4_ByteStream& sample_stream) :
m_SampleStream(sample_stream)
{
m_StscAtom = AP4_DYNAMIC_CAST(AP4_StscAtom, stbl->GetChild(AP4_ATOM_TYPE_STSC));
m_StcoAtom = AP4_DYNAMIC_CAST(AP4_StcoAtom, stbl->GetChild(AP4_ATOM_TYPE_STCO));
m_StszAtom = AP4_DYNAMIC_CAST(AP4_StszAtom, stbl->GetChild(AP4_ATOM_TYPE_STSZ));
m_Stz2Atom = AP4_DYNAMIC_CAST(AP4_Stz2Atom, stbl->GetChild(AP4_ATOM_TYPE_STZ2));
m_CttsAtom = AP4_DYNAMIC_CAST(AP4_CttsAtom, stbl->GetChild(AP4_ATOM_TYPE_CTTS));
m_SttsAtom = AP4_DYNAMIC_CAST(AP4_SttsAtom, stbl->GetChild(AP4_ATOM_TYPE_STTS));
m_StssAtom = AP4_DYNAMIC_CAST(AP4_StssAtom, stbl->GetChild(AP4_ATOM_TYPE_STSS));
m_StsdAtom = AP4_DYNAMIC_CAST(AP4_StsdAtom, stbl->GetChild(AP4_ATOM_TYPE_STSD));
m_Co64Atom = AP4_DYNAMIC_CAST(AP4_Co64Atom, stbl->GetChild(AP4_ATOM_TYPE_CO64));
// keep a reference to the sample stream
m_SampleStream.AddReference();
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::~AP4_AtomSampleTable
+---------------------------------------------------------------------*/
AP4_AtomSampleTable::~AP4_AtomSampleTable()
{
m_SampleStream.Release();
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
AP4_Sample& sample)
{
AP4_Result result;
// check that we have an stsc atom
if (!m_StscAtom) {
return AP4_ERROR_INVALID_FORMAT;
}
// check that we have a chunk offset table
if (m_StcoAtom == NULL && m_Co64Atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// MP4 uses 1-based indexes internally, so adjust by one
index++;
// find out in which chunk this sample is located
AP4_Ordinal chunk, skip, desc;
result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);
if (AP4_FAILED(result)) return result;
// check that the result is within bounds
if (skip > index) return AP4_ERROR_INTERNAL;
// get the atom offset for this chunk
AP4_UI64 offset;
if (m_StcoAtom) {
AP4_UI32 offset_32;
result = m_StcoAtom->GetChunkOffset(chunk, offset_32);
offset = offset_32;
} else {
result = m_Co64Atom->GetChunkOffset(chunk, offset);
}
if (AP4_FAILED(result)) return result;
// compute the additional offset inside the chunk
for (unsigned int i = index-skip; i < index; i++) {
AP4_Size size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(i, size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(i, size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
offset += size;
}
// set the description index
sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes
// set the dts and cts
AP4_UI32 cts_offset = 0;
AP4_UI64 dts = 0;
AP4_UI32 duration = 0;
result = m_SttsAtom->GetDts(index, dts, &duration);
if (AP4_FAILED(result)) return result;
sample.SetDuration(duration);
sample.SetDts(dts);
if (m_CttsAtom == NULL) {
sample.SetCts(dts);
} else {
result = m_CttsAtom->GetCtsOffset(index, cts_offset);
if (AP4_FAILED(result)) return result;
sample.SetCtsDelta(cts_offset);
}
// set the size
AP4_Size sample_size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(index, sample_size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(index, sample_size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
sample.SetSize(sample_size);
// set the sync flag
if (m_StssAtom == NULL) {
sample.SetSync(true);
} else {
sample.SetSync(m_StssAtom->IsSampleSync(index));
}
// set the offset
sample.SetOffset(offset);
// set the data stream
sample.SetDataStream(m_SampleStream);
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleCount
+---------------------------------------------------------------------*/
AP4_Cardinal
AP4_AtomSampleTable::GetSampleCount()
{
if (m_StszAtom) {
return m_StszAtom->GetSampleCount();
} else if (m_Stz2Atom) {
return m_Stz2Atom->GetSampleCount();
} else {
return 0;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleDescription
+---------------------------------------------------------------------*/
AP4_SampleDescription*
AP4_AtomSampleTable::GetSampleDescription(AP4_Ordinal index)
{
return m_StsdAtom ? m_StsdAtom->GetSampleDescription(index) : NULL;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleDescriptionCount
+---------------------------------------------------------------------*/
AP4_Cardinal
AP4_AtomSampleTable::GetSampleDescriptionCount()
{
return m_StsdAtom ? m_StsdAtom->GetSampleDescriptionCount() : 0;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleChunkPosition
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
AP4_Ordinal sample_description_index;
return GetChunkForSample(sample_index,
chunk_index,
position_in_chunk,
sample_description_index);
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkForSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetChunkForSample(AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk,
AP4_Ordinal& sample_description_index)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
sample_description_index = 0;
// check that we an stsc atom
if (m_StscAtom == NULL) return AP4_ERROR_INVALID_STATE;
// get the chunk info from the stsc atom
AP4_Ordinal chunk = 0;
AP4_Result result = m_StscAtom->GetChunkForSample(sample_index+1, // the atom API is 1-based
chunk,
position_in_chunk,
sample_description_index);
if (AP4_FAILED(result)) return result;
if (chunk == 0) return AP4_ERROR_INTERNAL;
// the atom sample and chunk indexes are 1-based, so we need to translate
chunk_index = chunk-1;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkOffset
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position& offset)
{
if (m_StcoAtom) {
AP4_UI32 offset_32;
AP4_Result result = m_StcoAtom->GetChunkOffset(chunk_index+1, offset_32);
if (AP4_SUCCEEDED(result)) {
offset = offset_32;
} else {
offset = 0;
}
return result;
} else if (m_Co64Atom) {
return m_Co64Atom->GetChunkOffset(chunk_index+1, offset);
} else {
offset = 0;
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetChunkOffset
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::SetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position offset)
{
if (m_StcoAtom) {
if ((offset >> 32) != 0) return AP4_ERROR_OUT_OF_RANGE;
return m_StcoAtom->SetChunkOffset(chunk_index+1, (AP4_UI32)offset);
} else if (m_Co64Atom) {
return m_Co64Atom->SetChunkOffset(chunk_index+1, offset);
} else {
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetSampleSize
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::SetSampleSize(AP4_Ordinal sample_index, AP4_Size size)
{
if (m_StszAtom) {
return m_StszAtom->SetSampleSize(sample_index+1, size);
} else if (m_Stz2Atom) {
return m_Stz2Atom->SetSampleSize(sample_index+1, size);
} else {
return AP4_FAILURE;
}
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleIndexForTimeStamp
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 ts,
AP4_Ordinal& sample_index)
{
return m_SttsAtom ? m_SttsAtom->GetSampleIndexForTimeStamp(ts, sample_index)
: AP4_FAILURE;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetNearestSyncSampleIndex
+---------------------------------------------------------------------*/
AP4_Ordinal
AP4_AtomSampleTable::GetNearestSyncSampleIndex(AP4_Ordinal sample_index, bool before)
{
// if we don't have an stss table, all samples match
if (m_StssAtom == NULL) return sample_index;
sample_index += 1; // the table is 1-based
AP4_Cardinal entry_count = m_StssAtom->GetEntries().ItemCount();
if (before) {
AP4_Ordinal cursor = 0;
for (unsigned int i=0; i<entry_count; i++) {
if (m_StssAtom->GetEntries()[i] >= sample_index) return cursor;
if (m_StssAtom->GetEntries()[i]) cursor = m_StssAtom->GetEntries()[i]-1;
}
// not found?
return cursor;
} else {
for (unsigned int i=0; i<entry_count; i++) {
if (m_StssAtom->GetEntries()[i] >= sample_index) {
return m_StssAtom->GetEntries()[i]?m_StssAtom->GetEntries()[i]-1:sample_index-1;
}
}
// not found?
return GetSampleCount();
}
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_2809_0 |
crossvul-cpp_data_bad_4038_0 | /*
* Copyright (C) 2004-2020 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Query.h>
using std::set;
using std::map;
using std::vector;
#define CALLMOD(MOD, CLIENT, USER, NETWORK, FUNC) \
{ \
CModule* pModule = nullptr; \
if (NETWORK && (pModule = (NETWORK)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
pModule->SetClient(CLIENT); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(NETWORK)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = (USER)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(USER)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = CZNC::Get().GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
CUser* pOldUser = pModule->GetUser(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->SetUser(USER); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
pModule->SetUser(pOldUser); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
CZNC::Get().GetModules().UnloadModule(MOD); \
} \
} \
} else { \
PutStatus(t_f("No such module {1}")(MOD)); \
} \
}
CClient::~CClient() {
if (m_spAuth) {
CClientAuth* pAuth = (CClientAuth*)&(*m_spAuth);
pAuth->Invalidate();
}
if (m_pUser != nullptr) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CClient::SendRequiredPasswordNotice() {
PutClient(":irc.znc.in 464 " + GetNick() + " :Password required");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"You need to send your password. "
"Configure your client to send a server password.");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"To connect now, you can use /quote PASS <username>:<password>, "
"or /quote PASS <username>/<network>:<password> to connect to a "
"specific network.");
}
void CClient::ReadLine(const CString& sData) {
CLanguageScope user_lang(GetUser() ? GetUser()->GetLanguage() : "");
CString sLine = sData;
sLine.Replace("\n", "");
sLine.Replace("\r", "");
DEBUG("(" << GetFullName() << ") CLI -> ZNC ["
<< CDebug::Filter(sLine) << "]");
bool bReturn = false;
if (IsAttached()) {
NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRaw(this, sLine), &bReturn);
}
if (bReturn) return;
CMessage Message(sLine);
Message.SetClient(this);
if (IsAttached()) {
NETWORKMODULECALL(OnUserRawMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRawMessage(Message), &bReturn);
}
if (bReturn) return;
CString sCommand = Message.GetCommand();
if (!IsAttached()) {
// The following commands happen before authentication with ZNC
if (sCommand.Equals("PASS")) {
m_bGotPass = true;
CString sAuthLine = Message.GetParam(0);
ParsePass(sAuthLine);
AuthUser();
// Don't forward this msg. ZNC has already registered us.
return;
} else if (sCommand.Equals("NICK")) {
CString sNick = Message.GetParam(0);
m_sNick = sNick;
m_bGotNick = true;
AuthUser();
// Don't forward this msg. ZNC will handle nick changes until auth
// is complete
return;
} else if (sCommand.Equals("USER")) {
CString sAuthLine = Message.GetParam(0);
if (m_sUser.empty() && !sAuthLine.empty()) {
ParseUser(sAuthLine);
}
m_bGotUser = true;
if (m_bGotPass) {
AuthUser();
} else if (!m_bInCap) {
SendRequiredPasswordNotice();
}
// Don't forward this msg. ZNC has already registered us.
return;
}
}
if (Message.GetType() == CMessage::Type::Capability) {
HandleCap(Message);
// Don't let the client talk to the server directly about CAP,
// we don't want anything enabled that ZNC does not support.
return;
}
if (!m_pUser) {
// Only CAP, NICK, USER and PASS are allowed before login
return;
}
switch (Message.GetType()) {
case CMessage::Type::Action:
bReturn = OnActionMessage(Message);
break;
case CMessage::Type::CTCP:
bReturn = OnCTCPMessage(Message);
break;
case CMessage::Type::Join:
bReturn = OnJoinMessage(Message);
break;
case CMessage::Type::Mode:
bReturn = OnModeMessage(Message);
break;
case CMessage::Type::Notice:
bReturn = OnNoticeMessage(Message);
break;
case CMessage::Type::Part:
bReturn = OnPartMessage(Message);
break;
case CMessage::Type::Ping:
bReturn = OnPingMessage(Message);
break;
case CMessage::Type::Pong:
bReturn = OnPongMessage(Message);
break;
case CMessage::Type::Quit:
bReturn = OnQuitMessage(Message);
break;
case CMessage::Type::Text:
bReturn = OnTextMessage(Message);
break;
case CMessage::Type::Topic:
bReturn = OnTopicMessage(Message);
break;
default:
bReturn = OnOtherMessage(Message);
break;
}
if (bReturn) return;
PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags));
}
void CClient::SetNick(const CString& s) { m_sNick = s; }
void CClient::SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect,
bool bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientDisconnected(this);
if (bDisconnect) {
ClearServerDependentCaps();
// Tell the client they are no longer in these channels.
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (const CChan* pChan : vChans) {
if (!(pChan->IsDetached())) {
PutClient(":" + m_pNetwork->GetIRCNick().GetNickMask() +
" PART " + pChan->GetName());
}
}
}
} else if (m_pUser) {
m_pUser->UserDisconnected(this);
}
m_pNetwork = pNetwork;
if (bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientConnected(this);
} else if (m_pUser) {
m_pUser->UserConnected(this);
}
}
}
const vector<CClient*>& CClient::GetClients() const {
if (m_pNetwork) {
return m_pNetwork->GetClients();
}
return m_pUser->GetUserClients();
}
const CIRCSock* CClient::GetIRCSock() const {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
CIRCSock* CClient::GetIRCSock() {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
void CClient::StatusCTCP(const CString& sLine) {
CString sCommand = sLine.Token(0);
if (sCommand.Equals("PING")) {
PutStatusNotice("\001PING " + sLine.Token(1, true) + "\001");
} else if (sCommand.Equals("VERSION")) {
PutStatusNotice("\001VERSION " + CZNC::GetTag() + "\001");
}
}
bool CClient::SendMotd() {
const VCString& vsMotd = CZNC::Get().GetMotd();
if (!vsMotd.size()) {
return false;
}
for (const CString& sLine : vsMotd) {
if (m_pNetwork) {
PutStatusNotice(m_pNetwork->ExpandString(sLine));
} else {
PutStatusNotice(m_pUser->ExpandString(sLine));
}
}
return true;
}
void CClient::AuthUser() {
if (!m_bGotNick || !m_bGotUser || !m_bGotPass || m_bInCap || IsAttached())
return;
m_spAuth = std::make_shared<CClientAuth>(this, m_sUser, m_sPass);
CZNC::Get().AuthUser(m_spAuth);
}
CClientAuth::CClientAuth(CClient* pClient, const CString& sUsername,
const CString& sPassword)
: CAuthBase(sUsername, sPassword, pClient), m_pClient(pClient) {}
void CClientAuth::RefusedLogin(const CString& sReason) {
if (m_pClient) {
m_pClient->RefuseLogin(sReason);
}
}
CString CAuthBase::GetRemoteIP() const {
if (m_pSock) return m_pSock->GetRemoteIP();
return "";
}
void CAuthBase::Invalidate() { m_pSock = nullptr; }
void CAuthBase::AcceptLogin(CUser& User) {
if (m_pSock) {
AcceptedLogin(User);
Invalidate();
}
}
void CAuthBase::RefuseLogin(const CString& sReason) {
if (!m_pSock) return;
CUser* pUser = CZNC::Get().FindUser(GetUsername());
// If the username is valid, notify that user that someone tried to
// login. Use sReason because there are other reasons than "wrong
// password" for a login to be rejected (e.g. fail2ban).
if (pUser) {
pUser->PutStatusNotice(t_f(
"A client from {1} attempted to login as you, but was rejected: "
"{2}")(GetRemoteIP(), sReason));
}
GLOBALMODULECALL(OnFailedLogin(GetUsername(), GetRemoteIP()), NOTHING);
RefusedLogin(sReason);
Invalidate();
}
void CClient::RefuseLogin(const CString& sReason) {
PutStatus("Bad username and/or password.");
PutClient(":irc.znc.in 464 " + GetNick() + " :" + sReason);
Close(Csock::CLT_AFTERWRITE);
}
void CClientAuth::AcceptedLogin(CUser& User) {
if (m_pClient) {
m_pClient->AcceptLogin(User);
}
}
void CClient::AcceptLogin(CUser& User) {
m_sPass = "";
m_pUser = &User;
// Set our proper timeout and set back our proper timeout mode
// (constructor set a different timeout and mode)
SetTimeout(User.GetNoTrafficTimeout(), TMO_READ);
SetSockName("USR::" + m_pUser->GetUsername());
SetEncoding(m_pUser->GetClientEncoding());
if (!m_sNetwork.empty()) {
m_pNetwork = m_pUser->FindNetwork(m_sNetwork);
if (!m_pNetwork) {
PutStatus(t_f("Network {1} doesn't exist.")(m_sNetwork));
}
} else if (!m_pUser->GetNetworks().empty()) {
// If a user didn't supply a network, and they have a network called
// "default" then automatically use this network.
m_pNetwork = m_pUser->FindNetwork("default");
// If no "default" network, try "user" network. It's for compatibility
// with early network stuff in ZNC, which converted old configs to
// "user" network.
if (!m_pNetwork) m_pNetwork = m_pUser->FindNetwork("user");
// Otherwise, just try any network of the user.
if (!m_pNetwork) m_pNetwork = *m_pUser->GetNetworks().begin();
if (m_pNetwork && m_pUser->GetNetworks().size() > 1) {
PutStatusNotice(
t_s("You have several networks configured, but no network was "
"specified for the connection."));
PutStatusNotice(
t_f("Selecting network {1}. To see list of all configured "
"networks, use /znc ListNetworks")(m_pNetwork->GetName()));
PutStatusNotice(t_f(
"If you want to choose another network, use /znc JumpNetwork "
"<network>, or connect to ZNC with username {1}/<network> "
"(instead of just {1})")(m_pUser->GetUsername()));
}
} else {
PutStatusNotice(
t_s("You have no networks configured. Use /znc AddNetwork "
"<network> to add one."));
}
SetNetwork(m_pNetwork, false);
SendMotd();
NETWORKMODULECALL(OnClientLogin(), m_pUser, m_pNetwork, this, NOTHING);
}
void CClient::Timeout() { PutClient("ERROR :" + t_s("Closing link: Timeout")); }
void CClient::Connected() { DEBUG(GetSockName() << " == Connected();"); }
void CClient::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
}
void CClient::Disconnected() {
DEBUG(GetSockName() << " == Disconnected()");
CIRCNetwork* pNetwork = m_pNetwork;
SetNetwork(nullptr, false, false);
if (m_pUser) {
NETWORKMODULECALL(OnClientDisconnect(), m_pUser, pNetwork, this,
NOTHING);
}
}
void CClient::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
if (IsAttached()) {
PutClient("ERROR :" + t_s("Closing link: Too long raw line"));
}
Close();
}
void CClient::BouncedOff() {
PutStatusNotice(
t_s("You are being disconnected because another user just "
"authenticated as you."));
Close(Csock::CLT_AFTERWRITE);
}
void CClient::PutIRC(const CString& sLine) {
if (m_pNetwork) {
m_pNetwork->PutIRC(sLine);
}
}
CString CClient::GetFullName() const {
if (!m_pUser) return GetRemoteIP();
CString sFullName = m_pUser->GetUsername();
if (!m_sIdentifier.empty()) sFullName += "@" + m_sIdentifier;
if (m_pNetwork) sFullName += "/" + m_pNetwork->GetName();
return sFullName;
}
void CClient::PutClient(const CString& sLine) {
PutClient(CMessage(sLine));
}
bool CClient::PutClient(const CMessage& Message) {
if (!m_bAwayNotify && Message.GetType() == CMessage::Type::Away) {
return false;
} else if (!m_bAccountNotify &&
Message.GetType() == CMessage::Type::Account) {
return false;
}
CMessage Msg(Message);
const CIRCSock* pIRCSock = GetIRCSock();
if (pIRCSock) {
if (Msg.GetType() == CMessage::Type::Numeric) {
unsigned int uCode = Msg.As<CNumericMessage>().GetCode();
if (uCode == 352) { // RPL_WHOREPLY
if (!m_bNamesx && pIRCSock->HasNamesx()) {
// The server has NAMESX, but the client doesn't, so we need
// to remove extra prefixes
CString sNick = Msg.GetParam(6);
if (sNick.size() > 1 && pIRCSock->IsPermChar(sNick[1])) {
CString sNewNick = sNick;
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNewNick = sNick[0] + sNick.substr(pos);
}
Msg.SetParam(6, sNewNick);
}
}
} else if (uCode == 353) { // RPL_NAMES
if ((!m_bNamesx && pIRCSock->HasNamesx()) ||
(!m_bUHNames && pIRCSock->HasUHNames())) {
// The server has either UHNAMES or NAMESX, but the client
// is missing either or both
CString sNicks = Msg.GetParam(3);
VCString vsNicks;
sNicks.Split(" ", vsNicks, false);
for (CString& sNick : vsNicks) {
if (sNick.empty()) break;
if (!m_bNamesx && pIRCSock->HasNamesx() &&
pIRCSock->IsPermChar(sNick[0])) {
// The server has NAMESX, but the client doesn't, so
// we just use the first perm char
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNick = sNick[0] + sNick.substr(pos);
}
}
if (!m_bUHNames && pIRCSock->HasUHNames()) {
// The server has UHNAMES, but the client doesn't,
// so we strip away ident and host
sNick = sNick.Token(0, false, "!");
}
}
Msg.SetParam(
3, CString(" ").Join(vsNicks.begin(), vsNicks.end()));
}
}
} else if (Msg.GetType() == CMessage::Type::Join) {
if (!m_bExtendedJoin && pIRCSock->HasExtendedJoin()) {
Msg.SetParams({Msg.As<CJoinMessage>().GetTarget()});
}
}
}
MCString mssTags;
for (const auto& it : Msg.GetTags()) {
if (IsTagEnabled(it.first)) {
mssTags[it.first] = it.second;
}
}
if (HasServerTime()) {
// If the server didn't set the time tag, manually set it
mssTags.emplace("time", CUtils::FormatServerTime(Msg.GetTime()));
}
Msg.SetTags(mssTags);
Msg.SetClient(this);
Msg.SetNetwork(m_pNetwork);
bool bReturn = false;
NETWORKMODULECALL(OnSendToClientMessage(Msg), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
return PutClientRaw(Msg.ToString());
}
bool CClient::PutClientRaw(const CString& sLine) {
CString sCopy = sLine;
bool bReturn = false;
NETWORKMODULECALL(OnSendToClient(sCopy, *this), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
DEBUG("(" << GetFullName() << ") ZNC -> CLI ["
<< CDebug::Filter(sCopy) << "]");
Write(sCopy + "\r\n");
return true;
}
void CClient::PutStatusNotice(const CString& sLine) {
PutModNotice("status", sLine);
}
unsigned int CClient::PutStatus(const CTable& table) {
unsigned int idx = 0;
CString sLine;
while (table.GetLine(idx++, sLine)) PutStatus(sLine);
return idx - 1;
}
void CClient::PutStatus(const CString& sLine) { PutModule("status", sLine); }
void CClient::PutModNotice(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in NOTICE " << GetNick() << " :" << sLine
<< "]");
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) + "!znc@znc.in NOTICE " +
GetNick() + " :" + sLine + "\r\n");
}
void CClient::PutModule(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " << GetNick() << " :" << sLine
<< "]");
VCString vsLines;
sLine.Split("\n", vsLines);
for (const CString& s : vsLines) {
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " + GetNick() + " :" + s + "\r\n");
}
}
CString CClient::GetNick(bool bAllowIRCNick) const {
CString sRet;
const CIRCSock* pSock = GetIRCSock();
if (bAllowIRCNick && pSock && pSock->IsAuthed()) {
sRet = pSock->GetNick();
}
return (sRet.empty()) ? m_sNick : sRet;
}
CString CClient::GetNickMask() const {
if (GetIRCSock() && GetIRCSock()->IsAuthed()) {
return GetIRCSock()->GetNickMask();
}
CString sHost =
m_pNetwork ? m_pNetwork->GetBindHost() : m_pUser->GetBindHost();
if (sHost.empty()) {
sHost = "irc.znc.in";
}
return GetNick() + "!" +
(m_pNetwork ? m_pNetwork->GetIdent() : m_pUser->GetIdent()) + "@" +
sHost;
}
bool CClient::IsValidIdentifier(const CString& sIdentifier) {
// ^[-\w]+$
if (sIdentifier.empty()) {
return false;
}
const char* p = sIdentifier.c_str();
while (*p) {
if (*p != '_' && *p != '-' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
void CClient::RespondCap(const CString& sResponse) {
PutClient(":irc.znc.in CAP " + GetNick() + " " + sResponse);
}
void CClient::HandleCap(const CMessage& Message) {
CString sSubCmd = Message.GetParam(0);
if (sSubCmd.Equals("LS")) {
SCString ssOfferCaps;
for (const auto& it : m_mCoreCaps) {
bool bServerDependent = std::get<0>(it.second);
if (!bServerDependent ||
m_ssServerDependentCaps.count(it.first) > 0)
ssOfferCaps.insert(it.first);
}
GLOBALMODULECALL(OnClientCapLs(this, ssOfferCaps), NOTHING);
CString sRes =
CString(" ").Join(ssOfferCaps.begin(), ssOfferCaps.end());
RespondCap("LS :" + sRes);
m_bInCap = true;
if (Message.GetParam(1).ToInt() >= 302) {
m_bCapNotify = true;
}
} else if (sSubCmd.Equals("END")) {
m_bInCap = false;
if (!IsAttached()) {
if (!m_pUser && m_bGotUser && !m_bGotPass) {
SendRequiredPasswordNotice();
} else {
AuthUser();
}
}
} else if (sSubCmd.Equals("REQ")) {
VCString vsTokens;
Message.GetParam(1).Split(" ", vsTokens, false);
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
bool bAccepted = false;
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
bAccepted = !bServerDependent ||
m_ssServerDependentCaps.count(sCap) > 0;
}
GLOBALMODULECALL(IsClientCapSupported(this, sCap, bVal),
&bAccepted);
if (!bAccepted) {
// Some unsupported capability is requested
RespondCap("NAK :" + Message.GetParam(1));
return;
}
}
// All is fine, we support what was requested
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
auto handler_it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != handler_it) {
const auto& handler = std::get<1>(handler_it->second);
handler(bVal);
}
GLOBALMODULECALL(OnClientCapRequest(this, sCap, bVal), NOTHING);
if (bVal) {
m_ssAcceptedCaps.insert(sCap);
} else {
m_ssAcceptedCaps.erase(sCap);
}
}
RespondCap("ACK :" + Message.GetParam(1));
} else if (sSubCmd.Equals("LIST")) {
CString sList =
CString(" ").Join(m_ssAcceptedCaps.begin(), m_ssAcceptedCaps.end());
RespondCap("LIST :" + sList);
} else {
PutClient(":irc.znc.in 410 " + GetNick() + " " + sSubCmd +
" :Invalid CAP subcommand");
}
}
void CClient::ParsePass(const CString& sAuthLine) {
// [user[@identifier][/network]:]password
const size_t uColon = sAuthLine.find(":");
if (uColon != CString::npos) {
m_sPass = sAuthLine.substr(uColon + 1);
ParseUser(sAuthLine.substr(0, uColon));
} else {
m_sPass = sAuthLine;
}
}
void CClient::ParseUser(const CString& sAuthLine) {
// user[@identifier][/network]
const size_t uSlash = sAuthLine.rfind("/");
if (uSlash != CString::npos) {
m_sNetwork = sAuthLine.substr(uSlash + 1);
ParseIdentifier(sAuthLine.substr(0, uSlash));
} else {
ParseIdentifier(sAuthLine);
}
}
void CClient::ParseIdentifier(const CString& sAuthLine) {
// user[@identifier]
const size_t uAt = sAuthLine.rfind("@");
if (uAt != CString::npos) {
const CString sId = sAuthLine.substr(uAt + 1);
if (IsValidIdentifier(sId)) {
m_sIdentifier = sId;
m_sUser = sAuthLine.substr(0, uAt);
} else {
m_sUser = sAuthLine;
}
} else {
m_sUser = sAuthLine;
}
}
void CClient::SetTagSupport(const CString& sTag, bool bState) {
if (bState) {
m_ssSupportedTags.insert(sTag);
} else {
m_ssSupportedTags.erase(sTag);
}
}
void CClient::NotifyServerDependentCaps(const SCString& ssCaps) {
for (const CString& sCap : ssCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
if (bServerDependent) {
m_ssServerDependentCaps.insert(sCap);
}
}
}
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " NEW :" + sCaps);
}
}
void CClient::ClearServerDependentCaps() {
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " DEL :" + sCaps);
for (const CString& sCap : m_ssServerDependentCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
const auto& handler = std::get<1>(it->second);
handler(false);
}
}
}
m_ssServerDependentCaps.clear();
}
template <typename T>
void CClient::AddBuffer(const T& Message) {
const CString sTarget = Message.GetTarget();
T Format;
Format.Clone(Message);
Format.SetNick(CNick(_NAMEDFMT(GetNickMask())));
Format.SetTarget(_NAMEDFMT(sTarget));
Format.SetText("{text}");
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline()) {
pChan->AddBuffer(Format, Message.GetText());
}
} else if (Message.GetType() != CMessage::Type::Notice) {
if (!m_pUser->AutoClearQueryBuffer() || !m_pNetwork->IsUserOnline()) {
CQuery* pQuery = m_pNetwork->AddQuery(sTarget);
if (pQuery) {
pQuery->AddBuffer(Format, Message.GetText());
}
}
}
}
void CClient::EchoMessage(const CMessage& Message) {
CMessage EchoedMessage = Message;
for (CClient* pClient : GetClients()) {
if (pClient->HasEchoMessage() ||
(pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) ||
pClient->HasSelfMessage()))) {
EchoedMessage.SetNick(GetNickMask());
pClient->PutClient(EchoedMessage);
}
}
}
set<CChan*> CClient::MatchChans(const CString& sPatterns) const {
VCString vsPatterns;
sPatterns.Replace_n(",", " ")
.Split(" ", vsPatterns, false, "", "", true, true);
set<CChan*> sChans;
for (const CString& sPattern : vsPatterns) {
vector<CChan*> vChans = m_pNetwork->FindChans(sPattern);
sChans.insert(vChans.begin(), vChans.end());
}
return sChans;
}
unsigned int CClient::AttachChans(const std::set<CChan*>& sChans) {
unsigned int uAttached = 0;
for (CChan* pChan : sChans) {
if (!pChan->IsDetached()) continue;
uAttached++;
pChan->AttachUser();
}
return uAttached;
}
unsigned int CClient::DetachChans(const std::set<CChan*>& sChans) {
unsigned int uDetached = 0;
for (CChan* pChan : sChans) {
if (pChan->IsDetached()) continue;
uDetached++;
pChan->DetachUser();
}
return uDetached;
}
bool CClient::OnActionMessage(CActionMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserActionMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnCTCPMessage(CCTCPMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
if (Message.IsReply()) {
CString sCTCP = Message.GetText();
if (sCTCP.Token(0) == "VERSION") {
// There are 2 different scenarios:
//
// a) CTCP reply for VERSION is not set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC forwards CTCP VERSION to client
// 3. Client replies with something
// 4. ZNC adds itself to the reply
// 5. ZNC sends the modified reply to whoever asked
//
// b) CTCP reply for VERSION is set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC replies with the configured reply (or just drops it if
// empty), without forwarding anything to client
// 3. Client does not see any CTCP request, and does not reply
//
// So, if user doesn't want "via ZNC" in CTCP VERSION reply, they
// can set custom reply.
//
// See more bikeshedding at github issues #820 and #1012
Message.SetText(sCTCP + " via " + CZNC::GetTag(false));
}
}
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
if (Message.IsReply()) {
NETWORKMODULECALL(OnUserCTCPReplyMessage(Message), m_pUser,
m_pNetwork, this, &bContinue);
} else {
NETWORKMODULECALL(OnUserCTCPMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
}
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(t_f(
"Your CTCP to {1} got lost, you are not connected to IRC!")(
Message.GetTarget()));
continue;
}
if (m_pNetwork) {
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnJoinMessage(CJoinMessage& Message) {
CString sChans = Message.GetTarget();
CString sKeys = Message.GetKey();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
VCString vsKeys;
sKeys.Split(",", vsKeys, true);
sKeys.clear();
for (unsigned int a = 0; a < vsChans.size(); a++) {
Message.SetTarget(vsChans[a]);
Message.SetKey((a < vsKeys.size()) ? vsKeys[a] : "");
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(vsChans[a]));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserJoinMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
CString sChannel = Message.GetTarget();
CString sKey = Message.GetKey();
if (m_pNetwork) {
CChan* pChan = m_pNetwork->FindChan(sChannel);
if (pChan) {
if (pChan->IsDetached())
pChan->AttachUser(this);
else
pChan->JoinUser(sKey);
continue;
} else if (!sChannel.empty()) {
pChan = new CChan(sChannel, m_pNetwork, false);
if (m_pNetwork->AddChan(pChan)) {
pChan->SetKey(sKey);
}
}
}
if (!sChannel.empty()) {
sChans += (sChans.empty()) ? sChannel : CString("," + sChannel);
if (!vsKeys.empty()) {
sKeys += (sKeys.empty()) ? sKey : CString("," + sKey);
}
}
}
Message.SetTarget(sChans);
Message.SetKey(sKeys);
return sChans.empty();
}
bool CClient::OnModeMessage(CModeMessage& Message) {
CString sTarget = Message.GetTarget();
if (m_pNetwork && m_pNetwork->IsChan(sTarget) && !Message.HasModes()) {
// If we are on that channel and already received a
// /mode reply from the server, we can answer this
// request ourself.
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan && pChan->IsOn() && !pChan->GetModeString().empty()) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 324 " + GetNick() +
" " + sTarget + " " + pChan->GetModeString());
if (pChan->GetCreationDate() > 0) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 329 " +
GetNick() + " " + sTarget + " " +
CString(pChan->GetCreationDate()));
}
return true;
}
}
return false;
}
bool CClient::OnNoticeMessage(CNoticeMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
if (!sTarget.Equals("status")) {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModNotice(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserNoticeMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your notice to {1} got lost, you are not connected to "
"IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnPartMessage(CPartMessage& Message) {
CString sChans = Message.GetTarget();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
for (CString& sChan : vsChans) {
bool bContinue = false;
Message.SetTarget(sChan);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
NETWORKMODULECALL(OnUserPartMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
sChan = Message.GetTarget();
CChan* pChan = m_pNetwork ? m_pNetwork->FindChan(sChan) : nullptr;
if (pChan && !pChan->IsOn()) {
PutStatusNotice(t_f("Removing channel {1}")(sChan));
m_pNetwork->DelChan(sChan);
} else {
sChans += (sChans.empty()) ? sChan : CString("," + sChan);
}
}
if (sChans.empty()) {
return true;
}
Message.SetTarget(sChans);
return false;
}
bool CClient::OnPingMessage(CMessage& Message) {
// All PONGs are generated by ZNC. We will still forward this to
// the ircd, but all PONGs from irc will be blocked.
if (!Message.GetParams().empty())
PutClient(":irc.znc.in PONG irc.znc.in " + Message.GetParamsColon(0));
else
PutClient(":irc.znc.in PONG irc.znc.in");
return false;
}
bool CClient::OnPongMessage(CMessage& Message) {
// Block PONGs, we already responded to the pings
return true;
}
bool CClient::OnQuitMessage(CQuitMessage& Message) {
bool bReturn = false;
NETWORKMODULECALL(OnUserQuitMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
if (!bReturn) {
Close(Csock::CLT_AFTERWRITE); // Treat a client quit as a detach
}
// Don't forward this msg. We don't want the client getting us
// disconnected.
return true;
}
bool CClient::OnTextMessage(CTextMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
if (sTarget.Equals("status")) {
CString sMsg = Message.GetText();
UserCommand(sMsg);
} else {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a PRIVMSG to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your message to {1} got lost, you are not connected "
"to IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnTopicMessage(CTopicMessage& Message) {
bool bReturn = false;
CString sChan = Message.GetTarget();
CString sTopic = Message.GetTopic();
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
if (!sTopic.empty()) {
NETWORKMODULECALL(OnUserTopicMessage(Message), m_pUser, m_pNetwork,
this, &bReturn);
} else {
NETWORKMODULECALL(OnUserTopicRequest(sChan), m_pUser, m_pNetwork, this,
&bReturn);
Message.SetTarget(sChan);
}
return bReturn;
}
bool CClient::OnOtherMessage(CMessage& Message) {
const CString& sCommand = Message.GetCommand();
if (sCommand.Equals("ZNC")) {
CString sTarget = Message.GetParam(0);
CString sModCommand;
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
sModCommand = Message.GetParamsColon(1);
} else {
sTarget = "status";
sModCommand = Message.GetParamsColon(0);
}
if (sTarget.Equals("status")) {
if (sModCommand.empty())
PutStatus(t_s("Hello. How may I help you?"));
else
UserCommand(sModCommand);
} else {
if (sModCommand.empty())
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
PutModule(t_s("Hello. How may I help you?")))
else
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(sModCommand))
}
return true;
} else if (sCommand.Equals("ATTACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /attach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uAttachedChans = AttachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Attached {1} channel", "Attached {1} channels",
uAttachedChans)(uAttachedChans));
return true;
} else if (sCommand.Equals("DETACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /detach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uDetached = DetachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Detached {1} channel", "Detached {1} channels",
uDetached)(uDetached));
return true;
} else if (sCommand.Equals("PROTOCTL")) {
for (const CString& sParam : Message.GetParams()) {
if (sParam == "NAMESX") {
m_bNamesx = true;
} else if (sParam == "UHNAMES") {
m_bUHNames = true;
}
}
return true; // If the server understands it, we already enabled namesx
// / uhnames
}
return false;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_4038_0 |
crossvul-cpp_data_good_656_1 | /* GRAPHITE2 LICENSING
Copyright 2012, SIL International
All rights reserved.
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 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
Lesser General Public License for more details.
You should also have received a copy of the GNU Lesser General Public
License along with this library in the file named "LICENSE".
If not, write to the Free Software Foundation, 51 Franklin Street,
Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
internet at http://www.fsf.org/licenses/lgpl.html.
Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or 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 "graphite2/Font.h"
#include "inc/Main.h"
#include "inc/Face.h" //for the tags
#include "inc/GlyphCache.h"
#include "inc/GlyphFace.h"
#include "inc/Endian.h"
#include "inc/bits.h"
using namespace graphite2;
namespace
{
// Iterator over version 1 or 2 glat entries which consist of a series of
// +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+
// v1 |k|n|v1 |v2 |...|vN | or v2 | k | n |v1 |v2 |...|vN |
// +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+
// variable length structures.
template<typename W>
class _glat_iterator : public std::iterator<std::input_iterator_tag, std::pair<sparse::key_type, sparse::mapped_type> >
{
unsigned short key() const { return be::peek<W>(_e) + _n; }
unsigned int run() const { return be::peek<W>(_e+sizeof(W)); }
void advance_entry() { _n = 0; _e = _v; be::skip<W>(_v,2); }
public:
_glat_iterator(const void * glat=0) : _e(reinterpret_cast<const byte *>(glat)), _v(_e+2*sizeof(W)), _n(0) {}
_glat_iterator<W> & operator ++ () {
++_n; be::skip<uint16>(_v);
if (_n == run()) advance_entry();
return *this;
}
_glat_iterator<W> operator ++ (int) { _glat_iterator<W> tmp(*this); operator++(); return tmp; }
// This is strictly a >= operator. A true == operator could be
// implemented that test for overlap but it would be more expensive a
// test.
bool operator == (const _glat_iterator<W> & rhs) { return _v >= rhs._e - 1; }
bool operator != (const _glat_iterator<W> & rhs) { return !operator==(rhs); }
value_type operator * () const {
return value_type(key(), be::peek<uint16>(_v));
}
protected:
const byte * _e, * _v;
size_t _n;
};
typedef _glat_iterator<uint8> glat_iterator;
typedef _glat_iterator<uint16> glat2_iterator;
}
const SlantBox SlantBox::empty = {0,0,0,0};
class GlyphCache::Loader
{
public:
Loader(const Face & face); //return result indicates success. Do not use if failed.
operator bool () const throw();
unsigned short int units_per_em() const throw();
unsigned short int num_glyphs() const throw();
unsigned short int num_attrs() const throw();
bool has_boxes() const throw();
const GlyphFace * read_glyph(unsigned short gid, GlyphFace &, int *numsubs) const throw();
GlyphBox * read_box(uint16 gid, GlyphBox *curr, const GlyphFace & face) const throw();
CLASS_NEW_DELETE;
private:
Face::Table _head,
_hhea,
_hmtx,
_glyf,
_loca,
m_pGlat,
m_pGloc;
bool _long_fmt;
bool _has_boxes;
unsigned short _num_glyphs_graphics, //i.e. boundary box and advance
_num_glyphs_attributes,
_num_attrs; // number of glyph attributes per glyph
};
GlyphCache::GlyphCache(const Face & face, const uint32 face_options)
: _glyph_loader(new Loader(face)),
_glyphs(_glyph_loader && *_glyph_loader && _glyph_loader->num_glyphs()
? grzeroalloc<const GlyphFace *>(_glyph_loader->num_glyphs()) : 0),
_boxes(_glyph_loader && _glyph_loader->has_boxes() && _glyph_loader->num_glyphs()
? grzeroalloc<GlyphBox *>(_glyph_loader->num_glyphs()) : 0),
_num_glyphs(_glyphs ? _glyph_loader->num_glyphs() : 0),
_num_attrs(_glyphs ? _glyph_loader->num_attrs() : 0),
_upem(_glyphs ? _glyph_loader->units_per_em() : 0)
{
if ((face_options & gr_face_preloadGlyphs) && _glyph_loader && _glyphs)
{
int numsubs = 0;
GlyphFace * const glyphs = new GlyphFace [_num_glyphs];
if (!glyphs)
return;
// The 0 glyph is definately required.
_glyphs[0] = _glyph_loader->read_glyph(0, glyphs[0], &numsubs);
// glyphs[0] has the same address as the glyphs array just allocated,
// thus assigning the &glyphs[0] to _glyphs[0] means _glyphs[0] points
// to the entire array.
const GlyphFace * loaded = _glyphs[0];
for (uint16 gid = 1; loaded && gid != _num_glyphs; ++gid)
_glyphs[gid] = loaded = _glyph_loader->read_glyph(gid, glyphs[gid], &numsubs);
if (!loaded)
{
_glyphs[0] = 0;
delete [] glyphs;
}
else if (numsubs > 0 && _boxes)
{
GlyphBox * boxes = (GlyphBox *)gralloc<char>(_num_glyphs * sizeof(GlyphBox) + numsubs * 8 * sizeof(float));
GlyphBox * currbox = boxes;
for (uint16 gid = 0; currbox && gid != _num_glyphs; ++gid)
{
_boxes[gid] = currbox;
currbox = _glyph_loader->read_box(gid, currbox, *_glyphs[gid]);
}
if (!currbox)
{
free(boxes);
_boxes[0] = 0;
}
}
delete _glyph_loader;
_glyph_loader = 0;
}
if (_glyphs && glyph(0) == 0)
{
free(_glyphs);
_glyphs = 0;
if (_boxes)
{
free(_boxes);
_boxes = 0;
}
_num_glyphs = _num_attrs = _upem = 0;
}
}
GlyphCache::~GlyphCache()
{
if (_glyphs)
{
if (_glyph_loader)
{
const GlyphFace * * g = _glyphs;
for(unsigned short n = _num_glyphs; n; --n, ++g)
delete *g;
}
else
delete [] _glyphs[0];
free(_glyphs);
}
if (_boxes)
{
if (_glyph_loader)
{
GlyphBox * * g = _boxes;
for (uint16 n = _num_glyphs; n; --n, ++g)
free(*g);
}
else
free(_boxes[0]);
free(_boxes);
}
delete _glyph_loader;
}
const GlyphFace *GlyphCache::glyph(unsigned short glyphid) const //result may be changed by subsequent call with a different glyphid
{
if (glyphid >= numGlyphs())
return _glyphs[0];
const GlyphFace * & p = _glyphs[glyphid];
if (p == 0 && _glyph_loader)
{
int numsubs = 0;
GlyphFace * g = new GlyphFace();
if (g) p = _glyph_loader->read_glyph(glyphid, *g, &numsubs);
if (!p)
{
delete g;
return *_glyphs;
}
if (_boxes)
{
_boxes[glyphid] = (GlyphBox *)gralloc<char>(sizeof(GlyphBox) + 8 * numsubs * sizeof(float));
if (!_glyph_loader->read_box(glyphid, _boxes[glyphid], *_glyphs[glyphid]))
{
free(_boxes[glyphid]);
_boxes[glyphid] = 0;
}
}
}
return p;
}
GlyphCache::Loader::Loader(const Face & face)
: _head(face, Tag::head),
_hhea(face, Tag::hhea),
_hmtx(face, Tag::hmtx),
_glyf(face, Tag::glyf),
_loca(face, Tag::loca),
_long_fmt(false),
_has_boxes(false),
_num_glyphs_graphics(0),
_num_glyphs_attributes(0),
_num_attrs(0)
{
if (!operator bool())
return;
const Face::Table maxp = Face::Table(face, Tag::maxp);
if (!maxp) { _head = Face::Table(); return; }
_num_glyphs_graphics = TtfUtil::GlyphCount(maxp);
// This will fail if the number of glyphs is wildly out of range.
if (_glyf && TtfUtil::LocaLookup(_num_glyphs_graphics-1, _loca, _loca.size(), _head) == size_t(-2))
{
_head = Face::Table();
return;
}
if ((m_pGlat = Face::Table(face, Tag::Glat, 0x00030000)) == NULL
|| (m_pGloc = Face::Table(face, Tag::Gloc)) == NULL
|| m_pGloc.size() < 8)
{
_head = Face::Table();
return;
}
const byte * p = m_pGloc;
int version = be::read<uint32>(p);
const uint16 flags = be::read<uint16>(p);
_num_attrs = be::read<uint16>(p);
// We can accurately calculate the number of attributed glyphs by
// subtracting the length of the attribids array (numAttribs long if present)
// and dividing by either 2 or 4 depending on shor or lonf format
_long_fmt = flags & 1;
int tmpnumgattrs = (m_pGloc.size()
- (p - m_pGloc)
- sizeof(uint16)*(flags & 0x2 ? _num_attrs : 0))
/ (_long_fmt ? sizeof(uint32) : sizeof(uint16)) - 1;
if (version >= 0x00020000 || tmpnumgattrs < 0 || tmpnumgattrs > 65535
|| _num_attrs == 0 || _num_attrs > 0x3000 // is this hard limit appropriate?
|| _num_glyphs_graphics > tmpnumgattrs
|| m_pGlat.size() < 4)
{
_head = Face::Table();
return;
}
_num_glyphs_attributes = static_cast<unsigned short>(tmpnumgattrs);
p = m_pGlat;
version = be::read<uint32>(p);
if (version >= 0x00040000 || (version >= 0x00030000 && m_pGlat.size() < 8)) // reject Glat tables that are too new
{
_head = Face::Table();
return;
}
else if (version >= 0x00030000)
{
unsigned int glatflags = be::read<uint32>(p);
_has_boxes = glatflags & 1;
// delete this once the compiler is fixed
_has_boxes = true;
}
}
inline
GlyphCache::Loader::operator bool () const throw()
{
return _head && _hhea && _hmtx && !(bool(_glyf) != bool(_loca));
}
inline
unsigned short int GlyphCache::Loader::units_per_em() const throw()
{
return _head ? TtfUtil::DesignUnits(_head) : 0;
}
inline
unsigned short int GlyphCache::Loader::num_glyphs() const throw()
{
return max(_num_glyphs_graphics, _num_glyphs_attributes);
}
inline
unsigned short int GlyphCache::Loader::num_attrs() const throw()
{
return _num_attrs;
}
inline
bool GlyphCache::Loader::has_boxes () const throw()
{
return _has_boxes;
}
const GlyphFace * GlyphCache::Loader::read_glyph(unsigned short glyphid, GlyphFace & glyph, int *numsubs) const throw()
{
Rect bbox;
Position advance;
if (glyphid < _num_glyphs_graphics)
{
int nLsb;
unsigned int nAdvWid;
if (_glyf)
{
int xMin, yMin, xMax, yMax;
size_t locidx = TtfUtil::LocaLookup(glyphid, _loca, _loca.size(), _head);
void *pGlyph = TtfUtil::GlyfLookup(_glyf, locidx, _glyf.size());
if (pGlyph && TtfUtil::GlyfBox(pGlyph, xMin, yMin, xMax, yMax))
{
if ((xMin > xMax) || (yMin > yMax))
return 0;
bbox = Rect(Position(static_cast<float>(xMin), static_cast<float>(yMin)),
Position(static_cast<float>(xMax), static_cast<float>(yMax)));
}
}
if (TtfUtil::HorMetrics(glyphid, _hmtx, _hmtx.size(), _hhea, nLsb, nAdvWid))
advance = Position(static_cast<float>(nAdvWid), 0);
}
if (glyphid < _num_glyphs_attributes)
{
const byte * gloc = m_pGloc;
size_t glocs = 0, gloce = 0;
be::skip<uint32>(gloc);
be::skip<uint16>(gloc,2);
if (_long_fmt)
{
if (8 + glyphid * sizeof(uint32) > m_pGloc.size())
return 0;
be::skip<uint32>(gloc, glyphid);
glocs = be::read<uint32>(gloc);
gloce = be::peek<uint32>(gloc);
}
else
{
if (8 + glyphid * sizeof(uint16) > m_pGloc.size())
return 0;
be::skip<uint16>(gloc, glyphid);
glocs = be::read<uint16>(gloc);
gloce = be::peek<uint16>(gloc);
}
if (glocs >= m_pGlat.size() - 1 || gloce > m_pGlat.size())
return 0;
const uint32 glat_version = be::peek<uint32>(m_pGlat);
if (glat_version >= 0x00030000)
{
if (glocs >= gloce)
return 0;
const byte * p = m_pGlat + glocs;
uint16 bmap = be::read<uint16>(p);
int num = bit_set_count((uint32)bmap);
if (numsubs) *numsubs += num;
glocs += 6 + 8 * num;
if (glocs > gloce)
return 0;
}
if (glat_version < 0x00020000)
{
if (gloce - glocs < 2*sizeof(byte)+sizeof(uint16)
|| gloce - glocs > _num_attrs*(2*sizeof(byte)+sizeof(uint16)))
return 0;
new (&glyph) GlyphFace(bbox, advance, glat_iterator(m_pGlat + glocs), glat_iterator(m_pGlat + gloce));
}
else
{
if (gloce - glocs < 3*sizeof(uint16) // can a glyph have no attributes? why not?
|| gloce - glocs > _num_attrs*3*sizeof(uint16)
|| glocs > m_pGlat.size() - 2*sizeof(uint16))
return 0;
new (&glyph) GlyphFace(bbox, advance, glat2_iterator(m_pGlat + glocs), glat2_iterator(m_pGlat + gloce));
}
if (!glyph.attrs() || glyph.attrs().capacity() > _num_attrs)
return 0;
}
return &glyph;
}
inline float scale_to(uint8 t, float zmin, float zmax)
{
return (zmin + t * (zmax - zmin) / 255);
}
Rect readbox(Rect &b, uint8 zxmin, uint8 zymin, uint8 zxmax, uint8 zymax)
{
return Rect(Position(scale_to(zxmin, b.bl.x, b.tr.x), scale_to(zymin, b.bl.y, b.tr.y)),
Position(scale_to(zxmax, b.bl.x, b.tr.x), scale_to(zymax, b.bl.y, b.tr.y)));
}
GlyphBox * GlyphCache::Loader::read_box(uint16 gid, GlyphBox *curr, const GlyphFace & glyph) const throw()
{
if (gid >= _num_glyphs_attributes) return 0;
const byte * gloc = m_pGloc;
size_t glocs = 0, gloce = 0;
be::skip<uint32>(gloc);
be::skip<uint16>(gloc,2);
if (_long_fmt)
{
be::skip<uint32>(gloc, gid);
glocs = be::read<uint32>(gloc);
gloce = be::peek<uint32>(gloc);
}
else
{
be::skip<uint16>(gloc, gid);
glocs = be::read<uint16>(gloc);
gloce = be::peek<uint16>(gloc);
}
if (gloce > m_pGlat.size() || glocs + 6 >= gloce)
return 0;
const byte * p = m_pGlat + glocs;
uint16 bmap = be::read<uint16>(p);
int num = bit_set_count((uint32)bmap);
Rect bbox = glyph.theBBox();
Rect diamax(Position(bbox.bl.x + bbox.bl.y, bbox.bl.x - bbox.tr.y),
Position(bbox.tr.x + bbox.tr.y, bbox.tr.x - bbox.bl.y));
Rect diabound = readbox(diamax, p[0], p[2], p[1], p[3]);
::new (curr) GlyphBox(num, bmap, &diabound);
be::skip<uint8>(p, 4);
if (glocs + 6 + num * 8 >= gloce)
return 0;
for (int i = 0; i < num * 2; ++i)
{
Rect box = readbox((i & 1) ? diamax : bbox, p[0], p[2], p[1], p[3]);
curr->addSubBox(i >> 1, i & 1, &box);
be::skip<uint8>(p, 4);
}
return (GlyphBox *)((char *)(curr) + sizeof(GlyphBox) + 2 * num * sizeof(Rect));
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_656_1 |
crossvul-cpp_data_good_4037_0 | /*
* Copyright (C) 2004-2020 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Query.h>
using std::set;
using std::map;
using std::vector;
#define CALLMOD(MOD, CLIENT, USER, NETWORK, FUNC) \
{ \
CModule* pModule = nullptr; \
if (NETWORK && (pModule = (NETWORK)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
pModule->SetClient(CLIENT); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(NETWORK)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = (USER)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(USER)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = CZNC::Get().GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
CUser* pOldUser = pModule->GetUser(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->SetUser(USER); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
pModule->SetUser(pOldUser); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
CZNC::Get().GetModules().UnloadModule(MOD); \
} \
} \
} else { \
PutStatus(t_f("No such module {1}")(MOD)); \
} \
}
CClient::~CClient() {
if (m_spAuth) {
CClientAuth* pAuth = (CClientAuth*)&(*m_spAuth);
pAuth->Invalidate();
}
if (m_pUser != nullptr) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CClient::SendRequiredPasswordNotice() {
PutClient(":irc.znc.in 464 " + GetNick() + " :Password required");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"You need to send your password. "
"Configure your client to send a server password.");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"To connect now, you can use /quote PASS <username>:<password>, "
"or /quote PASS <username>/<network>:<password> to connect to a "
"specific network.");
}
void CClient::ReadLine(const CString& sData) {
CLanguageScope user_lang(GetUser() ? GetUser()->GetLanguage() : "");
CString sLine = sData;
sLine.Replace("\n", "");
sLine.Replace("\r", "");
DEBUG("(" << GetFullName() << ") CLI -> ZNC ["
<< CDebug::Filter(sLine) << "]");
bool bReturn = false;
if (IsAttached()) {
NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRaw(this, sLine), &bReturn);
}
if (bReturn) return;
CMessage Message(sLine);
Message.SetClient(this);
if (IsAttached()) {
NETWORKMODULECALL(OnUserRawMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRawMessage(Message), &bReturn);
}
if (bReturn) return;
CString sCommand = Message.GetCommand();
if (!IsAttached()) {
// The following commands happen before authentication with ZNC
if (sCommand.Equals("PASS")) {
m_bGotPass = true;
CString sAuthLine = Message.GetParam(0);
ParsePass(sAuthLine);
AuthUser();
// Don't forward this msg. ZNC has already registered us.
return;
} else if (sCommand.Equals("NICK")) {
CString sNick = Message.GetParam(0);
m_sNick = sNick;
m_bGotNick = true;
AuthUser();
// Don't forward this msg. ZNC will handle nick changes until auth
// is complete
return;
} else if (sCommand.Equals("USER")) {
CString sAuthLine = Message.GetParam(0);
if (m_sUser.empty() && !sAuthLine.empty()) {
ParseUser(sAuthLine);
}
m_bGotUser = true;
if (m_bGotPass) {
AuthUser();
} else if (!m_bInCap) {
SendRequiredPasswordNotice();
}
// Don't forward this msg. ZNC has already registered us.
return;
}
}
if (Message.GetType() == CMessage::Type::Capability) {
HandleCap(Message);
// Don't let the client talk to the server directly about CAP,
// we don't want anything enabled that ZNC does not support.
return;
}
if (!m_pUser) {
// Only CAP, NICK, USER and PASS are allowed before login
return;
}
switch (Message.GetType()) {
case CMessage::Type::Action:
bReturn = OnActionMessage(Message);
break;
case CMessage::Type::CTCP:
bReturn = OnCTCPMessage(Message);
break;
case CMessage::Type::Join:
bReturn = OnJoinMessage(Message);
break;
case CMessage::Type::Mode:
bReturn = OnModeMessage(Message);
break;
case CMessage::Type::Notice:
bReturn = OnNoticeMessage(Message);
break;
case CMessage::Type::Part:
bReturn = OnPartMessage(Message);
break;
case CMessage::Type::Ping:
bReturn = OnPingMessage(Message);
break;
case CMessage::Type::Pong:
bReturn = OnPongMessage(Message);
break;
case CMessage::Type::Quit:
bReturn = OnQuitMessage(Message);
break;
case CMessage::Type::Text:
bReturn = OnTextMessage(Message);
break;
case CMessage::Type::Topic:
bReturn = OnTopicMessage(Message);
break;
default:
bReturn = OnOtherMessage(Message);
break;
}
if (bReturn) return;
PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags));
}
void CClient::SetNick(const CString& s) { m_sNick = s; }
void CClient::SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect,
bool bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientDisconnected(this);
if (bDisconnect) {
ClearServerDependentCaps();
// Tell the client they are no longer in these channels.
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (const CChan* pChan : vChans) {
if (!(pChan->IsDetached())) {
PutClient(":" + m_pNetwork->GetIRCNick().GetNickMask() +
" PART " + pChan->GetName());
}
}
}
} else if (m_pUser) {
m_pUser->UserDisconnected(this);
}
m_pNetwork = pNetwork;
if (bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientConnected(this);
} else if (m_pUser) {
m_pUser->UserConnected(this);
}
}
}
const vector<CClient*>& CClient::GetClients() const {
if (m_pNetwork) {
return m_pNetwork->GetClients();
}
return m_pUser->GetUserClients();
}
const CIRCSock* CClient::GetIRCSock() const {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
CIRCSock* CClient::GetIRCSock() {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
void CClient::StatusCTCP(const CString& sLine) {
CString sCommand = sLine.Token(0);
if (sCommand.Equals("PING")) {
PutStatusNotice("\001PING " + sLine.Token(1, true) + "\001");
} else if (sCommand.Equals("VERSION")) {
PutStatusNotice("\001VERSION " + CZNC::GetTag() + "\001");
}
}
bool CClient::SendMotd() {
const VCString& vsMotd = CZNC::Get().GetMotd();
if (!vsMotd.size()) {
return false;
}
for (const CString& sLine : vsMotd) {
if (m_pNetwork) {
PutStatusNotice(m_pNetwork->ExpandString(sLine));
} else {
PutStatusNotice(m_pUser->ExpandString(sLine));
}
}
return true;
}
void CClient::AuthUser() {
if (!m_bGotNick || !m_bGotUser || !m_bGotPass || m_bInCap || IsAttached())
return;
m_spAuth = std::make_shared<CClientAuth>(this, m_sUser, m_sPass);
CZNC::Get().AuthUser(m_spAuth);
}
CClientAuth::CClientAuth(CClient* pClient, const CString& sUsername,
const CString& sPassword)
: CAuthBase(sUsername, sPassword, pClient), m_pClient(pClient) {}
void CClientAuth::RefusedLogin(const CString& sReason) {
if (m_pClient) {
m_pClient->RefuseLogin(sReason);
}
}
CString CAuthBase::GetRemoteIP() const {
if (m_pSock) return m_pSock->GetRemoteIP();
return "";
}
void CAuthBase::Invalidate() { m_pSock = nullptr; }
void CAuthBase::AcceptLogin(CUser& User) {
if (m_pSock) {
AcceptedLogin(User);
Invalidate();
}
}
void CAuthBase::RefuseLogin(const CString& sReason) {
if (!m_pSock) return;
CUser* pUser = CZNC::Get().FindUser(GetUsername());
// If the username is valid, notify that user that someone tried to
// login. Use sReason because there are other reasons than "wrong
// password" for a login to be rejected (e.g. fail2ban).
if (pUser) {
pUser->PutStatusNotice(t_f(
"A client from {1} attempted to login as you, but was rejected: "
"{2}")(GetRemoteIP(), sReason));
}
GLOBALMODULECALL(OnFailedLogin(GetUsername(), GetRemoteIP()), NOTHING);
RefusedLogin(sReason);
Invalidate();
}
void CClient::RefuseLogin(const CString& sReason) {
PutStatus("Bad username and/or password.");
PutClient(":irc.znc.in 464 " + GetNick() + " :" + sReason);
Close(Csock::CLT_AFTERWRITE);
}
void CClientAuth::AcceptedLogin(CUser& User) {
if (m_pClient) {
m_pClient->AcceptLogin(User);
}
}
void CClient::AcceptLogin(CUser& User) {
m_sPass = "";
m_pUser = &User;
// Set our proper timeout and set back our proper timeout mode
// (constructor set a different timeout and mode)
SetTimeout(User.GetNoTrafficTimeout(), TMO_READ);
SetSockName("USR::" + m_pUser->GetUsername());
SetEncoding(m_pUser->GetClientEncoding());
if (!m_sNetwork.empty()) {
m_pNetwork = m_pUser->FindNetwork(m_sNetwork);
if (!m_pNetwork) {
PutStatus(t_f("Network {1} doesn't exist.")(m_sNetwork));
}
} else if (!m_pUser->GetNetworks().empty()) {
// If a user didn't supply a network, and they have a network called
// "default" then automatically use this network.
m_pNetwork = m_pUser->FindNetwork("default");
// If no "default" network, try "user" network. It's for compatibility
// with early network stuff in ZNC, which converted old configs to
// "user" network.
if (!m_pNetwork) m_pNetwork = m_pUser->FindNetwork("user");
// Otherwise, just try any network of the user.
if (!m_pNetwork) m_pNetwork = *m_pUser->GetNetworks().begin();
if (m_pNetwork && m_pUser->GetNetworks().size() > 1) {
PutStatusNotice(
t_s("You have several networks configured, but no network was "
"specified for the connection."));
PutStatusNotice(
t_f("Selecting network {1}. To see list of all configured "
"networks, use /znc ListNetworks")(m_pNetwork->GetName()));
PutStatusNotice(t_f(
"If you want to choose another network, use /znc JumpNetwork "
"<network>, or connect to ZNC with username {1}/<network> "
"(instead of just {1})")(m_pUser->GetUsername()));
}
} else {
PutStatusNotice(
t_s("You have no networks configured. Use /znc AddNetwork "
"<network> to add one."));
}
SetNetwork(m_pNetwork, false);
SendMotd();
NETWORKMODULECALL(OnClientLogin(), m_pUser, m_pNetwork, this, NOTHING);
}
void CClient::Timeout() { PutClient("ERROR :" + t_s("Closing link: Timeout")); }
void CClient::Connected() { DEBUG(GetSockName() << " == Connected();"); }
void CClient::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
}
void CClient::Disconnected() {
DEBUG(GetSockName() << " == Disconnected()");
CIRCNetwork* pNetwork = m_pNetwork;
SetNetwork(nullptr, false, false);
if (m_pUser) {
NETWORKMODULECALL(OnClientDisconnect(), m_pUser, pNetwork, this,
NOTHING);
}
}
void CClient::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
if (IsAttached()) {
PutClient("ERROR :" + t_s("Closing link: Too long raw line"));
}
Close();
}
void CClient::BouncedOff() {
PutStatusNotice(
t_s("You are being disconnected because another user just "
"authenticated as you."));
Close(Csock::CLT_AFTERWRITE);
}
void CClient::PutIRC(const CString& sLine) {
if (m_pNetwork) {
m_pNetwork->PutIRC(sLine);
}
}
CString CClient::GetFullName() const {
if (!m_pUser) return GetRemoteIP();
CString sFullName = m_pUser->GetUsername();
if (!m_sIdentifier.empty()) sFullName += "@" + m_sIdentifier;
if (m_pNetwork) sFullName += "/" + m_pNetwork->GetName();
return sFullName;
}
void CClient::PutClient(const CString& sLine) {
PutClient(CMessage(sLine));
}
bool CClient::PutClient(const CMessage& Message) {
if (!m_bAwayNotify && Message.GetType() == CMessage::Type::Away) {
return false;
} else if (!m_bAccountNotify &&
Message.GetType() == CMessage::Type::Account) {
return false;
}
CMessage Msg(Message);
const CIRCSock* pIRCSock = GetIRCSock();
if (pIRCSock) {
if (Msg.GetType() == CMessage::Type::Numeric) {
unsigned int uCode = Msg.As<CNumericMessage>().GetCode();
if (uCode == 352) { // RPL_WHOREPLY
if (!m_bNamesx && pIRCSock->HasNamesx()) {
// The server has NAMESX, but the client doesn't, so we need
// to remove extra prefixes
CString sNick = Msg.GetParam(6);
if (sNick.size() > 1 && pIRCSock->IsPermChar(sNick[1])) {
CString sNewNick = sNick;
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNewNick = sNick[0] + sNick.substr(pos);
}
Msg.SetParam(6, sNewNick);
}
}
} else if (uCode == 353) { // RPL_NAMES
if ((!m_bNamesx && pIRCSock->HasNamesx()) ||
(!m_bUHNames && pIRCSock->HasUHNames())) {
// The server has either UHNAMES or NAMESX, but the client
// is missing either or both
CString sNicks = Msg.GetParam(3);
VCString vsNicks;
sNicks.Split(" ", vsNicks, false);
for (CString& sNick : vsNicks) {
if (sNick.empty()) break;
if (!m_bNamesx && pIRCSock->HasNamesx() &&
pIRCSock->IsPermChar(sNick[0])) {
// The server has NAMESX, but the client doesn't, so
// we just use the first perm char
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNick = sNick[0] + sNick.substr(pos);
}
}
if (!m_bUHNames && pIRCSock->HasUHNames()) {
// The server has UHNAMES, but the client doesn't,
// so we strip away ident and host
sNick = sNick.Token(0, false, "!");
}
}
Msg.SetParam(
3, CString(" ").Join(vsNicks.begin(), vsNicks.end()));
}
}
} else if (Msg.GetType() == CMessage::Type::Join) {
if (!m_bExtendedJoin && pIRCSock->HasExtendedJoin()) {
Msg.SetParams({Msg.As<CJoinMessage>().GetTarget()});
}
}
}
MCString mssTags;
for (const auto& it : Msg.GetTags()) {
if (IsTagEnabled(it.first)) {
mssTags[it.first] = it.second;
}
}
if (HasServerTime()) {
// If the server didn't set the time tag, manually set it
mssTags.emplace("time", CUtils::FormatServerTime(Msg.GetTime()));
}
Msg.SetTags(mssTags);
Msg.SetClient(this);
Msg.SetNetwork(m_pNetwork);
bool bReturn = false;
NETWORKMODULECALL(OnSendToClientMessage(Msg), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
return PutClientRaw(Msg.ToString());
}
bool CClient::PutClientRaw(const CString& sLine) {
CString sCopy = sLine;
bool bReturn = false;
NETWORKMODULECALL(OnSendToClient(sCopy, *this), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
DEBUG("(" << GetFullName() << ") ZNC -> CLI ["
<< CDebug::Filter(sCopy) << "]");
Write(sCopy + "\r\n");
return true;
}
void CClient::PutStatusNotice(const CString& sLine) {
PutModNotice("status", sLine);
}
unsigned int CClient::PutStatus(const CTable& table) {
unsigned int idx = 0;
CString sLine;
while (table.GetLine(idx++, sLine)) PutStatus(sLine);
return idx - 1;
}
void CClient::PutStatus(const CString& sLine) { PutModule("status", sLine); }
void CClient::PutModNotice(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in NOTICE " << GetNick() << " :" << sLine
<< "]");
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) + "!znc@znc.in NOTICE " +
GetNick() + " :" + sLine + "\r\n");
}
void CClient::PutModule(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " << GetNick() << " :" << sLine
<< "]");
VCString vsLines;
sLine.Split("\n", vsLines);
for (const CString& s : vsLines) {
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " + GetNick() + " :" + s + "\r\n");
}
}
CString CClient::GetNick(bool bAllowIRCNick) const {
CString sRet;
const CIRCSock* pSock = GetIRCSock();
if (bAllowIRCNick && pSock && pSock->IsAuthed()) {
sRet = pSock->GetNick();
}
return (sRet.empty()) ? m_sNick : sRet;
}
CString CClient::GetNickMask() const {
if (GetIRCSock() && GetIRCSock()->IsAuthed()) {
return GetIRCSock()->GetNickMask();
}
CString sHost =
m_pNetwork ? m_pNetwork->GetBindHost() : m_pUser->GetBindHost();
if (sHost.empty()) {
sHost = "irc.znc.in";
}
return GetNick() + "!" +
(m_pNetwork ? m_pNetwork->GetIdent() : m_pUser->GetIdent()) + "@" +
sHost;
}
bool CClient::IsValidIdentifier(const CString& sIdentifier) {
// ^[-\w]+$
if (sIdentifier.empty()) {
return false;
}
const char* p = sIdentifier.c_str();
while (*p) {
if (*p != '_' && *p != '-' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
void CClient::RespondCap(const CString& sResponse) {
PutClient(":irc.znc.in CAP " + GetNick() + " " + sResponse);
}
void CClient::HandleCap(const CMessage& Message) {
CString sSubCmd = Message.GetParam(0);
if (sSubCmd.Equals("LS")) {
SCString ssOfferCaps;
for (const auto& it : m_mCoreCaps) {
bool bServerDependent = std::get<0>(it.second);
if (!bServerDependent ||
m_ssServerDependentCaps.count(it.first) > 0)
ssOfferCaps.insert(it.first);
}
GLOBALMODULECALL(OnClientCapLs(this, ssOfferCaps), NOTHING);
CString sRes =
CString(" ").Join(ssOfferCaps.begin(), ssOfferCaps.end());
RespondCap("LS :" + sRes);
m_bInCap = true;
if (Message.GetParam(1).ToInt() >= 302) {
m_bCapNotify = true;
}
} else if (sSubCmd.Equals("END")) {
m_bInCap = false;
if (!IsAttached()) {
if (!m_pUser && m_bGotUser && !m_bGotPass) {
SendRequiredPasswordNotice();
} else {
AuthUser();
}
}
} else if (sSubCmd.Equals("REQ")) {
VCString vsTokens;
Message.GetParam(1).Split(" ", vsTokens, false);
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
bool bAccepted = false;
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
bAccepted = !bServerDependent ||
m_ssServerDependentCaps.count(sCap) > 0;
}
GLOBALMODULECALL(IsClientCapSupported(this, sCap, bVal),
&bAccepted);
if (!bAccepted) {
// Some unsupported capability is requested
RespondCap("NAK :" + Message.GetParam(1));
return;
}
}
// All is fine, we support what was requested
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
auto handler_it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != handler_it) {
const auto& handler = std::get<1>(handler_it->second);
handler(bVal);
}
GLOBALMODULECALL(OnClientCapRequest(this, sCap, bVal), NOTHING);
if (bVal) {
m_ssAcceptedCaps.insert(sCap);
} else {
m_ssAcceptedCaps.erase(sCap);
}
}
RespondCap("ACK :" + Message.GetParam(1));
} else if (sSubCmd.Equals("LIST")) {
CString sList =
CString(" ").Join(m_ssAcceptedCaps.begin(), m_ssAcceptedCaps.end());
RespondCap("LIST :" + sList);
} else {
PutClient(":irc.znc.in 410 " + GetNick() + " " + sSubCmd +
" :Invalid CAP subcommand");
}
}
void CClient::ParsePass(const CString& sAuthLine) {
// [user[@identifier][/network]:]password
const size_t uColon = sAuthLine.find(":");
if (uColon != CString::npos) {
m_sPass = sAuthLine.substr(uColon + 1);
ParseUser(sAuthLine.substr(0, uColon));
} else {
m_sPass = sAuthLine;
}
}
void CClient::ParseUser(const CString& sAuthLine) {
// user[@identifier][/network]
const size_t uSlash = sAuthLine.rfind("/");
if (uSlash != CString::npos) {
m_sNetwork = sAuthLine.substr(uSlash + 1);
ParseIdentifier(sAuthLine.substr(0, uSlash));
} else {
ParseIdentifier(sAuthLine);
}
}
void CClient::ParseIdentifier(const CString& sAuthLine) {
// user[@identifier]
const size_t uAt = sAuthLine.rfind("@");
if (uAt != CString::npos) {
const CString sId = sAuthLine.substr(uAt + 1);
if (IsValidIdentifier(sId)) {
m_sIdentifier = sId;
m_sUser = sAuthLine.substr(0, uAt);
} else {
m_sUser = sAuthLine;
}
} else {
m_sUser = sAuthLine;
}
}
void CClient::SetTagSupport(const CString& sTag, bool bState) {
if (bState) {
m_ssSupportedTags.insert(sTag);
} else {
m_ssSupportedTags.erase(sTag);
}
}
void CClient::NotifyServerDependentCaps(const SCString& ssCaps) {
for (const CString& sCap : ssCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
if (bServerDependent) {
m_ssServerDependentCaps.insert(sCap);
}
}
}
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " NEW :" + sCaps);
}
}
void CClient::ClearServerDependentCaps() {
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " DEL :" + sCaps);
for (const CString& sCap : m_ssServerDependentCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
const auto& handler = std::get<1>(it->second);
handler(false);
}
}
}
m_ssServerDependentCaps.clear();
}
template <typename T>
void CClient::AddBuffer(const T& Message) {
const CString sTarget = Message.GetTarget();
T Format;
Format.Clone(Message);
Format.SetNick(CNick(_NAMEDFMT(GetNickMask())));
Format.SetTarget(_NAMEDFMT(sTarget));
Format.SetText("{text}");
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline()) {
pChan->AddBuffer(Format, Message.GetText());
}
} else if (Message.GetType() != CMessage::Type::Notice) {
if (!m_pUser->AutoClearQueryBuffer() || !m_pNetwork->IsUserOnline()) {
CQuery* pQuery = m_pNetwork->AddQuery(sTarget);
if (pQuery) {
pQuery->AddBuffer(Format, Message.GetText());
}
}
}
}
void CClient::EchoMessage(const CMessage& Message) {
CMessage EchoedMessage = Message;
for (CClient* pClient : GetClients()) {
if (pClient->HasEchoMessage() ||
(pClient != this && ((m_pNetwork && m_pNetwork->IsChan(Message.GetParam(0))) ||
pClient->HasSelfMessage()))) {
EchoedMessage.SetNick(GetNickMask());
pClient->PutClient(EchoedMessage);
}
}
}
set<CChan*> CClient::MatchChans(const CString& sPatterns) const {
VCString vsPatterns;
sPatterns.Replace_n(",", " ")
.Split(" ", vsPatterns, false, "", "", true, true);
set<CChan*> sChans;
for (const CString& sPattern : vsPatterns) {
vector<CChan*> vChans = m_pNetwork->FindChans(sPattern);
sChans.insert(vChans.begin(), vChans.end());
}
return sChans;
}
unsigned int CClient::AttachChans(const std::set<CChan*>& sChans) {
unsigned int uAttached = 0;
for (CChan* pChan : sChans) {
if (!pChan->IsDetached()) continue;
uAttached++;
pChan->AttachUser();
}
return uAttached;
}
unsigned int CClient::DetachChans(const std::set<CChan*>& sChans) {
unsigned int uDetached = 0;
for (CChan* pChan : sChans) {
if (pChan->IsDetached()) continue;
uDetached++;
pChan->DetachUser();
}
return uDetached;
}
bool CClient::OnActionMessage(CActionMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserActionMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnCTCPMessage(CCTCPMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
if (Message.IsReply()) {
CString sCTCP = Message.GetText();
if (sCTCP.Token(0) == "VERSION") {
// There are 2 different scenarios:
//
// a) CTCP reply for VERSION is not set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC forwards CTCP VERSION to client
// 3. Client replies with something
// 4. ZNC adds itself to the reply
// 5. ZNC sends the modified reply to whoever asked
//
// b) CTCP reply for VERSION is set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC replies with the configured reply (or just drops it if
// empty), without forwarding anything to client
// 3. Client does not see any CTCP request, and does not reply
//
// So, if user doesn't want "via ZNC" in CTCP VERSION reply, they
// can set custom reply.
//
// See more bikeshedding at github issues #820 and #1012
Message.SetText(sCTCP + " via " + CZNC::GetTag(false));
}
}
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
if (Message.IsReply()) {
NETWORKMODULECALL(OnUserCTCPReplyMessage(Message), m_pUser,
m_pNetwork, this, &bContinue);
} else {
NETWORKMODULECALL(OnUserCTCPMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
}
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(t_f(
"Your CTCP to {1} got lost, you are not connected to IRC!")(
Message.GetTarget()));
continue;
}
if (m_pNetwork) {
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnJoinMessage(CJoinMessage& Message) {
CString sChans = Message.GetTarget();
CString sKeys = Message.GetKey();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
VCString vsKeys;
sKeys.Split(",", vsKeys, true);
sKeys.clear();
for (unsigned int a = 0; a < vsChans.size(); a++) {
Message.SetTarget(vsChans[a]);
Message.SetKey((a < vsKeys.size()) ? vsKeys[a] : "");
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(vsChans[a]));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserJoinMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
CString sChannel = Message.GetTarget();
CString sKey = Message.GetKey();
if (m_pNetwork) {
CChan* pChan = m_pNetwork->FindChan(sChannel);
if (pChan) {
if (pChan->IsDetached())
pChan->AttachUser(this);
else
pChan->JoinUser(sKey);
continue;
} else if (!sChannel.empty()) {
pChan = new CChan(sChannel, m_pNetwork, false);
if (m_pNetwork->AddChan(pChan)) {
pChan->SetKey(sKey);
}
}
}
if (!sChannel.empty()) {
sChans += (sChans.empty()) ? sChannel : CString("," + sChannel);
if (!vsKeys.empty()) {
sKeys += (sKeys.empty()) ? sKey : CString("," + sKey);
}
}
}
Message.SetTarget(sChans);
Message.SetKey(sKeys);
return sChans.empty();
}
bool CClient::OnModeMessage(CModeMessage& Message) {
CString sTarget = Message.GetTarget();
if (m_pNetwork && m_pNetwork->IsChan(sTarget) && !Message.HasModes()) {
// If we are on that channel and already received a
// /mode reply from the server, we can answer this
// request ourself.
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan && pChan->IsOn() && !pChan->GetModeString().empty()) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 324 " + GetNick() +
" " + sTarget + " " + pChan->GetModeString());
if (pChan->GetCreationDate() > 0) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 329 " +
GetNick() + " " + sTarget + " " +
CString(pChan->GetCreationDate()));
}
return true;
}
}
return false;
}
bool CClient::OnNoticeMessage(CNoticeMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
if (!sTarget.Equals("status")) {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModNotice(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserNoticeMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your notice to {1} got lost, you are not connected to "
"IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnPartMessage(CPartMessage& Message) {
CString sChans = Message.GetTarget();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
for (CString& sChan : vsChans) {
bool bContinue = false;
Message.SetTarget(sChan);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
NETWORKMODULECALL(OnUserPartMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
sChan = Message.GetTarget();
CChan* pChan = m_pNetwork ? m_pNetwork->FindChan(sChan) : nullptr;
if (pChan && !pChan->IsOn()) {
PutStatusNotice(t_f("Removing channel {1}")(sChan));
m_pNetwork->DelChan(sChan);
} else {
sChans += (sChans.empty()) ? sChan : CString("," + sChan);
}
}
if (sChans.empty()) {
return true;
}
Message.SetTarget(sChans);
return false;
}
bool CClient::OnPingMessage(CMessage& Message) {
// All PONGs are generated by ZNC. We will still forward this to
// the ircd, but all PONGs from irc will be blocked.
if (!Message.GetParams().empty())
PutClient(":irc.znc.in PONG irc.znc.in " + Message.GetParamsColon(0));
else
PutClient(":irc.znc.in PONG irc.znc.in");
return false;
}
bool CClient::OnPongMessage(CMessage& Message) {
// Block PONGs, we already responded to the pings
return true;
}
bool CClient::OnQuitMessage(CQuitMessage& Message) {
bool bReturn = false;
NETWORKMODULECALL(OnUserQuitMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
if (!bReturn) {
Close(Csock::CLT_AFTERWRITE); // Treat a client quit as a detach
}
// Don't forward this msg. We don't want the client getting us
// disconnected.
return true;
}
bool CClient::OnTextMessage(CTextMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
EchoMessage(Message);
if (sTarget.Equals("status")) {
CString sMsg = Message.GetText();
UserCommand(sMsg);
} else {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a PRIVMSG to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your message to {1} got lost, you are not connected "
"to IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnTopicMessage(CTopicMessage& Message) {
bool bReturn = false;
CString sChan = Message.GetTarget();
CString sTopic = Message.GetTopic();
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
if (!sTopic.empty()) {
NETWORKMODULECALL(OnUserTopicMessage(Message), m_pUser, m_pNetwork,
this, &bReturn);
} else {
NETWORKMODULECALL(OnUserTopicRequest(sChan), m_pUser, m_pNetwork, this,
&bReturn);
Message.SetTarget(sChan);
}
return bReturn;
}
bool CClient::OnOtherMessage(CMessage& Message) {
const CString& sCommand = Message.GetCommand();
if (sCommand.Equals("ZNC")) {
CString sTarget = Message.GetParam(0);
CString sModCommand;
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
sModCommand = Message.GetParamsColon(1);
} else {
sTarget = "status";
sModCommand = Message.GetParamsColon(0);
}
if (sTarget.Equals("status")) {
if (sModCommand.empty())
PutStatus(t_s("Hello. How may I help you?"));
else
UserCommand(sModCommand);
} else {
if (sModCommand.empty())
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
PutModule(t_s("Hello. How may I help you?")))
else
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(sModCommand))
}
return true;
} else if (sCommand.Equals("ATTACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /attach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uAttachedChans = AttachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Attached {1} channel", "Attached {1} channels",
uAttachedChans)(uAttachedChans));
return true;
} else if (sCommand.Equals("DETACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /detach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uDetached = DetachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Detached {1} channel", "Detached {1} channels",
uDetached)(uDetached));
return true;
} else if (sCommand.Equals("PROTOCTL")) {
for (const CString& sParam : Message.GetParams()) {
if (sParam == "NAMESX") {
m_bNamesx = true;
} else if (sParam == "UHNAMES") {
m_bUHNames = true;
}
}
return true; // If the server understands it, we already enabled namesx
// / uhnames
}
return false;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_4037_0 |
crossvul-cpp_data_bad_4038_1 | /*
* Copyright (C) 2004-2020 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "znctest.h"
#include <gmock/gmock.h>
using testing::HasSubstr;
namespace znc_inttest {
namespace {
TEST(Config, AlreadyExists) {
QTemporaryDir dir;
WriteConfig(dir.path());
Process p(ZNC_BIN_DIR "/znc", QStringList() << "--debug"
<< "--datadir" << dir.path()
<< "--makeconf");
p.ReadUntil("already exists");
p.CanDie();
}
TEST_F(ZNCTest, Connect) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.ReadUntil("CAP LS");
auto client = ConnectClient();
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
client.ReadUntil("Welcome");
client.Close();
client = ConnectClient();
client.Write("PASS :user:hunter2");
client.Write("NICK nick");
client.Write("USER u x x x");
client.ReadUntil("Welcome");
client.Close();
client = ConnectClient();
client.Write("NICK nick");
client.Write("USER user x x x");
client.ReadUntil("Configure your client to send a server password");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("WHO");
}
TEST_F(ZNCTest, Channel) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.ReadUntil("Welcome");
client.Write("JOIN #znc");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc");
ircd.Write(":nick JOIN :#znc");
ircd.Write(":server 353 nick #znc :nick");
ircd.Write(":server 366 nick #znc :End of /NAMES list");
ircd.Write(":server PING :1");
ircd.ReadUntil("PONG 1");
client = LoginClient();
client.ReadUntil(":nick JOIN :#znc");
}
TEST_F(ZNCTest, HTTP) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto reply = HttpGet(QNetworkRequest(QUrl("http://127.0.0.1:12345/")));
EXPECT_THAT(reply->rawHeader("Server").toStdString(), HasSubstr("ZNC"));
}
TEST_F(ZNCTest, FixCVE20149403) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.Write(":server 005 nick CHANTYPES=# :supports");
ircd.Write(":server PING :1");
ircd.ReadUntil("PONG 1");
QNetworkRequest request;
request.setRawHeader("Authorization",
"Basic " + QByteArray("user:hunter2").toBase64());
request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
HttpPost(request, {
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "znc"},
{"enabled", "1"},
});
EXPECT_THAT(HttpPost(request,
{
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "znc"},
{"enabled", "1"},
})
->readAll()
.toStdString(),
HasSubstr("Channel [#znc] already exists"));
}
TEST_F(ZNCTest, FixFixOfCVE20149403) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.Write(":nick JOIN @#znc");
ircd.ReadUntil("MODE @#znc");
ircd.Write(":server 005 nick STATUSMSG=@ :supports");
ircd.Write(":server PING :12345");
ircd.ReadUntil("PONG 12345");
QNetworkRequest request;
request.setRawHeader("Authorization",
"Basic " + QByteArray("user:hunter2").toBase64());
request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
auto reply = HttpPost(request, {
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "@#znc"},
{"enabled", "1"},
});
EXPECT_THAT(reply->readAll().toStdString(),
HasSubstr("Could not add channel [@#znc]"));
}
TEST_F(ZNCTest, InvalidConfigInChan) {
QFile conf(m_dir.path() + "/configs/znc.conf");
ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
QTextStream out(&conf);
out << R"(
<User foo>
<Network bar>
<Chan #baz>
Invalid = Line
</Chan>
</Network>
</User>
)";
out.flush();
auto znc = Run();
znc->ShouldFinishItself(1);
}
TEST_F(ZNCTest, Encoding) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
ircd.Write(":server 001 nick :hello");
// legacy
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xE6world");
client.Write("PRIVMSG *controlpanel :SetNetwork Encoding $me $net UTF-8");
client.ReadUntil("Encoding = UTF-8");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xEF\xBF\xBDworld");
client.Write(
"PRIVMSG *controlpanel :SetNetwork Encoding $me $net ^CP-1251");
client.ReadUntil("Encoding = ^CP-1251");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xD0\xB6world");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xD0\xB6world");
client.ReadUntil("Hello\xD0\xB6world");
}
TEST_F(ZNCTest, BuildMod) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
QTemporaryDir srcd;
QDir srcdir(srcd.path());
QFile file(srcdir.filePath("testmod.cpp"));
ASSERT_TRUE(file.open(QIODevice::WriteOnly | QIODevice::Text));
QTextStream out(&file);
out << R"(
#include <znc/Modules.h>
class TestModule : public CModule {
public:
MODCONSTRUCTOR(TestModule) {}
void OnModCommand(const CString& sLine) override {
PutModule("Lorem ipsum");
}
};
MODULEDEFS(TestModule, "Test")
)";
file.close();
QDir dir(m_dir.path());
EXPECT_TRUE(dir.mkdir("modules"));
EXPECT_TRUE(dir.cd("modules"));
{
Process p(ZNC_BIN_DIR "/znc-buildmod",
QStringList() << srcdir.filePath("file-not-found.cpp"),
[&](QProcess* proc) {
proc->setWorkingDirectory(dir.absolutePath());
proc->setProcessChannelMode(QProcess::ForwardedChannels);
});
p.ShouldFinishItself(1);
p.ShouldFinishInSec(300);
}
{
Process p(ZNC_BIN_DIR "/znc-buildmod",
QStringList() << srcdir.filePath("testmod.cpp"),
[&](QProcess* proc) {
proc->setWorkingDirectory(dir.absolutePath());
proc->setProcessChannelMode(QProcess::ForwardedChannels);
});
p.ShouldFinishItself();
p.ShouldFinishInSec(300);
}
client.Write("znc loadmod testmod");
client.Write("PRIVMSG *testmod :hi");
client.ReadUntil("Lorem ipsum");
}
TEST_F(ZNCTest, AwayNotify) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = ConnectClient();
client.Write("CAP LS");
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
QByteArray cap_ls;
client.ReadUntilAndGet(" LS :", cap_ls);
ASSERT_THAT(cap_ls.toStdString(), AllOf(HasSubstr("cap-notify"), Not(HasSubstr("away-notify"))));
client.Write("CAP REQ :cap-notify");
client.ReadUntil("ACK :cap-notify");
client.Write("CAP END");
client.ReadUntil(" 001 ");
ircd.ReadUntil("USER");
ircd.Write("CAP user LS :away-notify");
ircd.ReadUntil("CAP REQ :away-notify");
ircd.Write("CAP user ACK :away-notify");
ircd.ReadUntil("CAP END");
ircd.Write(":server 001 user :welcome");
client.ReadUntil("CAP user NEW :away-notify");
client.Write("CAP REQ :away-notify");
client.ReadUntil("ACK :away-notify");
ircd.Write(":x!y@z AWAY :reason");
client.ReadUntil(":x!y@z AWAY :reason");
ircd.Close();
client.ReadUntil("DEL :away-notify");
}
TEST_F(ZNCTest, JoinKey) {
QFile conf(m_dir.path() + "/configs/znc.conf");
ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
QTextStream(&conf) << "ServerThrottle = 1\n";
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
ircd.Write(":server 001 nick :Hello");
client.Write("JOIN #znc secret");
ircd.ReadUntil("JOIN #znc secret");
ircd.Write(":nick JOIN :#znc");
client.ReadUntil("JOIN :#znc");
ircd.Close();
ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc secret");
}
} // namespace
} // namespace znc_inttest
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_4038_1 |
crossvul-cpp_data_good_3266_1 | /*
*
* (C) 2013-17 - ntop.org
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include "ntop_includes.h"
#ifdef __APPLE__
#include <uuid/uuid.h>
#endif
/* UserActivityStats.cpp */
extern const char* activity_names[];
/* Lua.cpp */
extern int ntop_lua_cli_print(lua_State* vm);
extern int ntop_lua_check(lua_State* vm, const char* func, int pos, int expected_type);
static bool help_printed = false;
/* **************************************************** */
/* Method used for collateral activities */
NetworkInterface::NetworkInterface() { init(); }
/* **************************************************** */
NetworkInterface::NetworkInterface(const char *name,
const char *custom_interface_type) {
NDPI_PROTOCOL_BITMASK all;
char _ifname[64];
bool isViewInterface = (strncmp(name, "view:", 5) == 0) ? 1 : 0; /* We need to do it as isView() is not yet initialized */
customIftype = custom_interface_type, flowHashingMode = flowhashing_none;
init();
#ifdef WIN32
if(name == NULL) name = "1"; /* First available interface */
#endif
scalingFactor = 1, remoteIfname = remoteIfIPaddr = remoteProbeIPaddr = remoteProbePublicIPaddr = NULL;
if(strcmp(name, "-") == 0) name = "stdin";
if(strcmp(name, "-") == 0) name = "stdin";
if(ntop->getRedis())
id = Utils::ifname2id(name);
else
id = -1;
purge_idle_flows_hosts = true;
if(name == NULL) {
char pcap_error_buffer[PCAP_ERRBUF_SIZE];
if(!help_printed)
ntop->getTrace()->traceEvent(TRACE_WARNING, "No capture interface specified");
printAvailableInterfaces(false, 0, NULL, 0);
name = pcap_lookupdev(pcap_error_buffer);
if(name == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR,
"Unable to locate default interface (%s)\n",
pcap_error_buffer);
exit(0);
}
} else {
if(isNumber(name)) {
/* We need to convert this numeric index into an interface name */
int id = atoi(name);
_ifname[0] = '\0';
printAvailableInterfaces(false, id, _ifname, sizeof(_ifname));
if(_ifname[0] == '\0') {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unable to locate interface Id %d", id);
printAvailableInterfaces(false, 0, NULL, 0);
exit(0);
}
name = _ifname;
}
}
pkt_dumper_tap = NULL, lastSecUpdate = 0;
ifname = strdup(name);
if(id >= 0) {
u_int32_t num_hashes;
ndpi_port_range d_port[MAX_DEFAULT_PORTS];
u_int16_t no_master[2] = { NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO };
num_hashes = max_val(4096, ntop->getPrefs()->get_max_num_flows()/4);
flows_hash = new FlowHash(this, num_hashes, ntop->getPrefs()->get_max_num_flows());
num_hashes = max_val(4096, ntop->getPrefs()->get_max_num_hosts()/4);
hosts_hash = new HostHash(this, num_hashes, ntop->getPrefs()->get_max_num_hosts());
macs_hash = new MacHash(this, 4, ntop->getPrefs()->get_max_num_hosts());
// init global detection structure
ndpi_struct = ndpi_init_detection_module();
if(ndpi_struct == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "Global structure initialization failed");
exit(-1);
}
if(ntop->getCustomnDPIProtos() != NULL)
ndpi_load_protocols_file(ndpi_struct, ntop->getCustomnDPIProtos());
ndpi_struct->http_dont_dissect_response = 1;
memset(d_port, 0, sizeof(d_port));
ndpi_set_proto_defaults(ndpi_struct, NDPI_PROTOCOL_UNRATED, NTOPNG_NDPI_OS_PROTO_ID,
no_master, no_master,
(char*)"Operating System",
NDPI_PROTOCOL_CATEGORY_SYSTEM,
d_port, d_port);
// enable all protocols
NDPI_BITMASK_SET_ALL(all);
ndpi_set_protocol_detection_bitmask2(ndpi_struct, &all);
last_pkt_rcvd = last_pkt_rcvd_remote = 0, pollLoopCreated = false, bridge_interface = false;
next_idle_flow_purge = next_idle_host_purge = 0;
cpu_affinity = -1 /* no affinity */, has_vlan_packets = false, pkt_dumper = NULL;
if(ntop->getPrefs()->are_taps_enabled())
pkt_dumper_tap = new PacketDumperTuntap(this);
running = false, sprobe_interface = false, inline_interface = false, db = NULL;
if((!isViewInterface) && (ntop->getPrefs()->do_dump_flows_on_mysql())) {
#ifdef NTOPNG_PRO
if(ntop->getPrefs()->is_enterprise_edition()) db = new BatchedMySQLDB(this);
#endif
if(db == NULL)
db = new MySQLDB(this);
if(!db) throw "Not enough memory";
}
checkIdle();
ifSpeed = Utils::getMaxIfSpeed(name);
ifMTU = Utils::getIfMTU(name), mtuWarningShown = false;
} else {
flows_hash = NULL, hosts_hash = NULL;
ndpi_struct = NULL, db = NULL, ifSpeed = 0;
pkt_dumper = NULL, pkt_dumper_tap = NULL;
}
networkStats = NULL;
#ifdef NTOPNG_PRO
policer = NULL; /* possibly instantiated by subclass PacketBridge */
flow_profiles = ntop->getPro()->has_valid_license() ? new FlowProfiles(id) : NULL;
if(flow_profiles) flow_profiles->loadProfiles();
shadow_flow_profiles = NULL;
#endif
loadDumpPrefs();
loadScalingFactorPrefs();
if(((statsManager = new StatsManager(id, STATS_MANAGER_STORE_NAME)) == NULL)
|| ((alertsManager = new AlertsManager(id, ALERTS_MANAGER_STORE_NAME)) == NULL))
throw "Not enough memory";
if((host_pools = new HostPools(this)) == NULL)
throw "Not enough memory";
alertLevel = alertsManager->getNumAlerts(true);
#ifdef linux
/*
A bit aggressive but as people usually
ignore warnings let's be proactive
*/
if(ifname
&& (!isViewInterface)
&& (!strstr(ifname, ":"))
&& (!strstr(ifname, ".pcap"))
&& strncmp(ifname, "lo", 2)
) {
char buf[64];
snprintf(buf, sizeof(buf), "ethtool -K %s gro off gso off tso off", ifname);
system(buf);
ntop->getTrace()->traceEvent(TRACE_NORMAL, "Executing %s", buf);
}
#endif
}
/* **************************************************** */
void NetworkInterface::init() {
ifname = remoteIfname = remoteIfIPaddr = remoteProbeIPaddr = NULL,
remoteProbePublicIPaddr = NULL, flows_hash = NULL, hosts_hash = NULL,
ndpi_struct = NULL, zmq_initial_bytes = 0, zmq_initial_pkts = 0,
sprobe_interface = inline_interface = false, has_vlan_packets = false,
last_pkt_rcvd = last_pkt_rcvd_remote = 0,
next_idle_flow_purge = next_idle_host_purge = 0,
running = false, numSubInterfaces = 0,
numVirtualInterfaces = 0, flowHashing = NULL,
pcap_datalink_type = 0, mtuWarningShown = false, lastSecUpdate = 0,
purge_idle_flows_hosts = true, id = (u_int8_t)-1,
last_remote_pps = 0, last_remote_bps = 0,
sprobe_interface = false, has_vlan_packets = false,
pcap_datalink_type = 0, cpu_affinity = -1 /* no affinity */,
inline_interface = false, running = false, interfaceStats = NULL,
tooManyFlowsAlertTriggered = tooManyHostsAlertTriggered = false,
pkt_dumper = NULL, numL2Devices = 0,
checkpointPktCount = checkpointBytesCount = checkpointPktDropCount = 0,
pollLoopCreated = false, bridge_interface = false;
if(ntop && ntop->getPrefs() && ntop->getPrefs()->are_taps_enabled())
pkt_dumper_tap = new PacketDumperTuntap(this);
else
pkt_dumper_tap = NULL;
memset(subInterfaces, 0, sizeof(subInterfaces));
ip_addresses = "", networkStats = NULL,
pcap_datalink_type = 0, cpu_affinity = -1,
pkt_dumper = NULL;
memset(lastMinuteTraffic, 0, sizeof(lastMinuteTraffic));
resetSecondTraffic();
reloadLuaInterpreter = true, L_flow_create_delete_ndpi = L_flow_update = NULL;
db = NULL;
#ifdef NTOPNG_PRO
policer = NULL;
#endif
statsManager = NULL, alertsManager = NULL, ifSpeed = 0;
host_pools = NULL;
checkIdle();
dump_all_traffic = dump_to_disk = dump_unknown_traffic
= dump_security_packets = dump_to_tap = false;
dump_sampling_rate = CONST_DUMP_SAMPLING_RATE;
dump_max_pkts_file = CONST_MAX_NUM_PACKETS_PER_DUMP;
dump_max_duration = CONST_MAX_DUMP_DURATION;
dump_max_files = CONST_MAX_DUMP;
ifMTU = CONST_DEFAULT_MAX_PACKET_SIZE, mtuWarningShown = false;
#ifdef NTOPNG_PRO
flow_profiles = shadow_flow_profiles = NULL;
#endif
}
/* **************************************************** */
#ifdef NTOPNG_PRO
void NetworkInterface::initL7Policer() {
/* Instantiate the policer */
policer = new L7Policer(this);
}
#endif
/* **************************************************** */
void NetworkInterface::checkAggregationMode() {
if(!customIftype) {
char rsp[32];
if(!strcmp(get_type(), CONST_INTERFACE_TYPE_ZMQ)) {
if(ntop->getRedis()->get((char*)CONST_RUNTIME_PREFS_IFACE_FLOW_COLLECTION, rsp, sizeof(rsp)) == 0) {
if(!strcmp(rsp, "probe_ip")) flowHashingMode = flowhashing_probe_ip;
else if(!strcmp(rsp, "ingress_iface_idx")) flowHashingMode = flowhashing_ingress_iface_idx;
}
} else {
if((ntop->getRedis()->get((char*)CONST_RUNTIME_PREFS_IFACE_VLAN_CREATION, rsp, sizeof(rsp)) == 0)
&& (!strncmp(rsp, "1", 1)))
flowHashingMode = flowhashing_vlan;
}
}
}
/* **************************************************** */
void NetworkInterface::loadDumpPrefs() {
if(ntop->getRedis() != NULL) {
updateDumpAllTrafficPolicy();
updateDumpTrafficDiskPolicy();
updateDumpTrafficTapPolicy();
updateDumpTrafficSamplingRate();
updateDumpTrafficMaxPktsPerFile();
updateDumpTrafficMaxSecPerFile();
updateDumpTrafficMaxFiles();
}
}
/* **************************************************** */
void NetworkInterface::loadScalingFactorPrefs() {
if(ntop->getRedis() != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), CONST_IFACE_SCALING_FACTOR_PREFS, id);
if((ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0) && (rsp[0] != '\0'))
scalingFactor = atol(rsp);
if(scalingFactor == 0) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "INTERNAL ERROR: scalingFactor can't be 0!");
scalingFactor = 1;
}
}
}
/* **************************************************** */
bool NetworkInterface::updateDumpTrafficTapPolicy(void) {
bool retval = false;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_tap", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = !strncmp(rsp, "true", 5);
else
retval = false;
}
dump_to_tap = retval;
return retval;
}
/* **************************************************** */
bool NetworkInterface::updateDumpAllTrafficPolicy(void) {
bool retval = false;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_all_traffic", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = !strncmp(rsp, "true", 5);
}
dump_all_traffic = retval;
return retval;
}
/* **************************************************** */
bool NetworkInterface::updateDumpTrafficDiskPolicy(void) {
bool retval = false, retval_u = false, retval_s = false;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_disk", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = !strncmp(rsp, "true", 5);
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_unknown_disk", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval_u = !strncmp(rsp, "true", 5);
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_security_disk", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval_s = !strncmp(rsp, "true", 5);
}
dump_to_disk = retval;
dump_unknown_traffic = retval_u;
dump_security_packets = retval_s;
return retval;
}
/* **************************************************** */
int NetworkInterface::updateDumpTrafficSamplingRate(void) {
int retval = 1;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_sampling_rate", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = atoi(rsp);
}
dump_sampling_rate = retval;
return retval;
}
/* **************************************************** */
int NetworkInterface::updateDumpTrafficMaxPktsPerFile(void) {
int retval = 0;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_max_pkts_file", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = atoi(rsp);
}
retval = retval > 0 ? retval : CONST_MAX_NUM_PACKETS_PER_DUMP;
dump_max_pkts_file = retval;
return retval;
}
/* **************************************************** */
int NetworkInterface::updateDumpTrafficMaxSecPerFile(void) {
int retval = 0;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_max_sec_file", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = atoi(rsp);
}
retval = retval > 0 ? retval : CONST_MAX_DUMP_DURATION;
dump_max_duration = retval;
return retval;
}
/* **************************************************** */
int NetworkInterface::updateDumpTrafficMaxFiles(void) {
int retval = 0;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_max_files", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = atoi(rsp);
}
retval = retval > 0 ? retval : CONST_MAX_DUMP;
dump_max_files = retval;
return retval;
}
/* **************************************************** */
bool NetworkInterface::checkIdle() {
is_idle = false;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s_not_idle", ifname);
if((ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0) && (rsp[0] != '\0')) {
int val = atoi(rsp);
if(val == 0) is_idle = true;
}
}
return(is_idle);
}
/* **************************************************** */
void NetworkInterface::deleteDataStructures() {
if(flows_hash) { delete(flows_hash); flows_hash = NULL; }
if(hosts_hash) { delete(hosts_hash); hosts_hash = NULL; }
if(macs_hash) { delete(macs_hash); macs_hash = NULL; }
if(ndpi_struct) {
ndpi_exit_detection_module(ndpi_struct);
ndpi_struct = NULL;
}
if(ifname) {
//ntop->getTrace()->traceEvent(TRACE_NORMAL, "Interface %s shutdown", ifname);
free(ifname);
ifname = NULL;
}
}
/* **************************************************** */
NetworkInterface::~NetworkInterface() {
if(getNumPackets() > 0) {
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"Flushing host contacts for interface %s",
get_name());
cleanup();
}
if(host_pools) delete host_pools; /* note: this requires ndpi_struct */
deleteDataStructures();
if(remoteIfname) free(remoteIfname);
if(remoteIfIPaddr) free(remoteIfIPaddr);
if(remoteProbeIPaddr) free(remoteProbeIPaddr);
if(remoteProbePublicIPaddr) free(remoteProbePublicIPaddr);
if(db) delete db;
if(statsManager) delete statsManager;
if(alertsManager) delete alertsManager;
if(networkStats) delete []networkStats;
if(pkt_dumper) delete pkt_dumper;
if(pkt_dumper_tap) delete pkt_dumper_tap;
if(interfaceStats) delete interfaceStats;
if(flowHashing) {
FlowHashing *current, *tmp;
HASH_ITER(hh, flowHashing, current, tmp) {
/* Interfaces are deleted by the main termination function */
HASH_DEL(flowHashing, current);
free(current);
}
}
#ifdef NTOPNG_PRO
if(policer) delete(policer);
if(flow_profiles) delete(flow_profiles);
if(shadow_flow_profiles) delete(shadow_flow_profiles);
#endif
termLuaInterpreter();
}
/* **************************************************** */
int NetworkInterface::dumpFlow(time_t when, bool idle_flow, Flow *f) {
if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
return(dumpDBFlow(when, idle_flow, f));
} else if(ntop->getPrefs()->do_dump_flows_on_es())
return(dumpEsFlow(when, f));
else {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Internal error");
return(-1);
}
}
/* **************************************************** */
int NetworkInterface::dumpEsFlow(time_t when, Flow *f) {
char *json = f->serialize(true);
int rc;
if(json) {
ntop->getTrace()->traceEvent(TRACE_INFO, "[ES] %s", json);
rc = ntop->getElasticSearch()->sendToES(json);
free(json);
} else
rc = -1;
return(rc);
}
/* **************************************************** */
int NetworkInterface::dumpDBFlow(time_t when, bool idle_flow, Flow *f) {
char *json = f->serialize(false);
int rc;
if(json) {
rc = db->dumpFlow(when, idle_flow, f, json);
free(json);
} else
rc = -1;
return(rc);
}
/* **************************************************** */
static bool local_hosts_2_redis_walker(GenericHashEntry *h, void *user_data) {
Host *host = (Host*)h;
if(host && (host->isLocalHost() || host->isSystemHost()))
host->serialize2redis();
return(false); /* false = keep on walking */
}
/* **************************************************** */
int NetworkInterface::dumpLocalHosts2redis(bool disable_purge) {
int rc;
if(disable_purge) disablePurge(false /* on hosts */);
rc = walker(walker_hosts, local_hosts_2_redis_walker, NULL) ? 0 : -1;
if(disable_purge) enablePurge(false /* on hosts */);
return rc;
}
/* **************************************************** */
u_int32_t NetworkInterface::getHostsHashSize() {
if(!isView())
return(hosts_hash->getNumEntries());
else {
u_int32_t tot = 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++)
tot += subInterfaces[s]->get_hosts_hash()->getNumEntries();
return(tot);
}
}
/* **************************************************** */
u_int32_t NetworkInterface::getFlowsHashSize() {
if(!isView())
return(flows_hash->getNumEntries());
else {
u_int32_t tot = 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++)
tot += subInterfaces[s]->get_flows_hash()->getNumEntries();
return(tot);
}
}
/* **************************************************** */
u_int32_t NetworkInterface::getMacsHashSize() {
if(!isView())
return(macs_hash->getNumEntries());
else {
u_int32_t tot = 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++)
tot += subInterfaces[s]->get_macs_hash()->getNumEntries();
return(tot);
}
}
/* **************************************************** */
bool NetworkInterface::walker(WalkerType wtype,
bool (*walker)(GenericHashEntry *h, void *user_data),
void *user_data) {
bool ret = false;
switch(wtype) {
case walker_hosts:
if(!isView())
ret = hosts_hash->walk(walker, user_data);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++)
ret |= subInterfaces[s]->get_hosts_hash()->walk(walker, user_data);
}
break;
case walker_flows:
if(!isView())
ret = flows_hash->walk(walker, user_data);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++)
ret |= subInterfaces[s]->get_flows_hash()->walk(walker, user_data);
}
break;
case walker_macs:
if(!isView())
ret = macs_hash->walk(walker, user_data);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++)
ret |= subInterfaces[s]->get_macs_hash()->walk(walker, user_data);
}
break;
}
return(ret);
}
/* **************************************************** */
Flow* NetworkInterface::getFlow(u_int8_t *src_eth, u_int8_t *dst_eth,
u_int16_t vlan_id,
u_int32_t deviceIP, u_int16_t inIndex, u_int16_t outIndex,
IpAddress *src_ip, IpAddress *dst_ip,
u_int16_t src_port, u_int16_t dst_port,
u_int8_t l4_proto,
bool *src2dst_direction,
time_t first_seen, time_t last_seen,
bool *new_flow) {
Flow *ret;
if(vlan_id != 0) setSeenVlanTaggedPackets();
ret = flows_hash->find(src_ip, dst_ip, src_port, dst_port,
vlan_id, l4_proto, src2dst_direction);
if(ret == NULL) {
*new_flow = true;
try {
ret = new Flow(this, vlan_id, l4_proto,
src_eth, src_ip, src_port,
dst_eth, dst_ip, dst_port,
first_seen, last_seen);
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
triggerTooManyFlowsAlert();
return(NULL);
}
if(flows_hash->add(ret)) {
*src2dst_direction = true;
if(inIndex && ret->get_cli_host()) {
Host *host = (Host*)ret->get_cli_host();
if(host->isLocalHost() || host->isSystemHost())
ret->get_cli_host()->setDeviceIfIdx(deviceIP, inIndex);
}
/*
We have decided to set only ingress traffic to make sure we do not mix truth with invalid data
if(outIndex && ret->get_srv_host()) ret->get_srv_host()->setDeviceIfIdx(deviceIP, outIndex);
*/
return(ret);
} else {
delete ret;
// ntop->getTrace()->traceEvent(TRACE_WARNING, "Too many flows");
return(NULL);
}
} else {
*new_flow = false;
return(ret);
}
}
/* **************************************************** */
void NetworkInterface::triggerTooManyFlowsAlert() {
if(!tooManyFlowsAlertTriggered) {
char alert_msg[512];
snprintf(alert_msg, sizeof(alert_msg),
"Interface <A HREF='%s/lua/if_stats.lua?ifid=%d'>%s</A> has too many flows. Please extend the --max-num-flows/-X command line option",
ntop->getPrefs()->get_http_prefix(),
id, get_name());
alertsManager->engageInterfaceAlert(this,
(char*)"app_misconfiguration",
alert_app_misconfiguration, alert_level_error, alert_msg);
tooManyFlowsAlertTriggered = true;
}
}
/* **************************************************** */
void NetworkInterface::triggerTooManyHostsAlert() {
if(!tooManyHostsAlertTriggered) {
char alert_msg[512];
snprintf(alert_msg, sizeof(alert_msg),
"Interface <A HREF='%s/lua/if_stats.lua?ifid=%d'>%s</A> has too many hosts. Please extend the --max-num-hosts/-x command line option",
ntop->getPrefs()->get_http_prefix(),
id, get_name());
alertsManager->releaseInterfaceAlert(this,
(char*)"app_misconfiguration",
alert_app_misconfiguration, alert_level_error, alert_msg);
tooManyHostsAlertTriggered = true;
}
}
/* **************************************************** */
NetworkInterface* NetworkInterface::getSubInterface(u_int32_t criteria) {
FlowHashing *h = NULL;
HASH_FIND_INT(flowHashing, &criteria, h);
if(h == NULL) {
/* Interface not found */
if(numVirtualInterfaces < MAX_NUM_VIRTUAL_INTERFACES) {
if((h = (FlowHashing*)malloc(sizeof(FlowHashing))) != NULL) {
char buf[64], buf1[48];
const char *vIface_type;
h->criteria = criteria;
switch(flowHashingMode) {
case flowhashing_vlan:
vIface_type = CONST_INTERFACE_TYPE_VLAN;
snprintf(buf, sizeof(buf), "%s [vlanId: %u]", ifname, criteria);
break;
case flowhashing_probe_ip:
vIface_type = CONST_INTERFACE_TYPE_FLOW;
snprintf(buf, sizeof(buf), "%s [probeIP: %s]", ifname,
Utils::intoaV4(criteria, buf1, sizeof(buf1)));
break;
case flowhashing_ingress_iface_idx:
vIface_type = CONST_INTERFACE_TYPE_FLOW;
snprintf(buf, sizeof(buf), "%s [ifIdx: %u]", ifname, criteria);
break;
default:
free(h);
return(NULL);
break;
}
if((h->iface = new NetworkInterface(buf, vIface_type)) != NULL) {
HASH_ADD_INT(flowHashing, criteria, h);
ntop->registerInterface(h->iface);
numVirtualInterfaces++;
}
} else
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
}
}
if(h) return(h->iface);
return(NULL);
}
/* **************************************************** */
void NetworkInterface::processFlow(ZMQ_Flow *zflow) {
bool src2dst_direction, new_flow;
Flow *flow;
ndpi_protocol p;
time_t now = time(NULL);
if(flowHashingMode != flowhashing_none) {
NetworkInterface *vIface;
switch(flowHashingMode) {
case flowhashing_probe_ip:
vIface = getSubInterface((u_int32_t)zflow->deviceIP);
break;
case flowhashing_ingress_iface_idx:
vIface = getSubInterface((u_int32_t)zflow->inIndex);
break;
default:
vIface = NULL;
break;
}
if(vIface) {
vIface->setTimeLastPktRcvd(getTimeLastPktRcvd());
vIface->processFlow(zflow);
return;
}
}
if(last_pkt_rcvd_remote > 0) {
int drift = now - last_pkt_rcvd_remote;
if(drift >= 0)
zflow->last_switched += drift, zflow->first_switched += drift;
else {
u_int32_t d = (u_int32_t)-drift;
if(d < zflow->last_switched) zflow->last_switched += drift;
if(d < zflow->first_switched) zflow->first_switched += drift;
}
#ifdef DEBUG
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"[first=%u][last=%u][duration: %u][drift: %d][now: %u][remote: %u]",
zflow->first_switched, zflow->last_switched,
zflow->last_switched-zflow->first_switched, drift,
now, last_pkt_rcvd_remote);
#endif
} else {
/* Old nProbe */
if((time_t)zflow->last_switched > (time_t)last_pkt_rcvd_remote)
last_pkt_rcvd_remote = zflow->last_switched;
#ifdef DEBUG
ntop->getTrace()->traceEvent(TRACE_NORMAL, "[first=%u][last=%u][duration: %u]",
zflow->first_switched, zflow->last_switched,
zflow->last_switched- zflow->first_switched);
#endif
}
/* Updating Flow */
flow = getFlow((u_int8_t*)zflow->src_mac, (u_int8_t*)zflow->dst_mac, zflow->vlan_id,
zflow->deviceIP, zflow->inIndex, zflow->outIndex,
&zflow->src_ip, &zflow->dst_ip,
zflow->src_port, zflow->dst_port,
zflow->l4_proto, &src2dst_direction,
zflow->first_switched,
zflow->last_switched, &new_flow);
incStats(now, zflow->src_ip.isIPv4() ? ETHERTYPE_IP : ETHERTYPE_IPV6,
flow ? flow->get_detected_protocol().protocol : NDPI_PROTOCOL_UNKNOWN,
zflow->pkt_sampling_rate*(zflow->in_bytes + zflow->out_bytes),
zflow->pkt_sampling_rate*(zflow->in_pkts + zflow->out_pkts),
24 /* 8 Preamble + 4 CRC + 12 IFG */ + 14 /* Ethernet header */);
if(flow == NULL)
return;
if(zflow->l4_proto == IPPROTO_TCP) {
struct timeval when;
when.tv_sec = (long)now, when.tv_usec = 0;
flow->updateTcpFlags((const struct bpf_timeval*)&when,
zflow->tcp_flags, src2dst_direction);
flow->incTcpBadStats(true,
zflow->tcp.ooo_in_pkts, zflow->tcp.retr_in_pkts, zflow->tcp.lost_in_pkts);
flow->incTcpBadStats(false,
zflow->tcp.ooo_out_pkts, zflow->tcp.retr_out_pkts, zflow->tcp.lost_out_pkts);
}
flow->addFlowStats(src2dst_direction,
zflow->pkt_sampling_rate*zflow->in_pkts,
zflow->pkt_sampling_rate*zflow->in_bytes, 0,
zflow->pkt_sampling_rate*zflow->out_pkts,
zflow->pkt_sampling_rate*zflow->out_bytes, 0,
zflow->last_switched);
p.protocol = zflow->l7_proto, p.master_protocol = NDPI_PROTOCOL_UNKNOWN;
flow->setDetectedProtocol(p, true);
flow->setJSONInfo(json_object_to_json_string(zflow->additional_fields));
flow->updateActivities();
flow->updateInterfaceLocalStats(src2dst_direction,
zflow->pkt_sampling_rate*(zflow->in_pkts+zflow->out_pkts),
zflow->pkt_sampling_rate*(zflow->in_bytes+zflow->out_bytes));
if(zflow->src_process.pid || zflow->dst_process.pid) {
if(zflow->src_process.pid) flow->handle_process(&zflow->src_process, src2dst_direction ? true : false);
if(zflow->dst_process.pid) flow->handle_process(&zflow->dst_process, src2dst_direction ? false : true);
if(zflow->l7_proto == NDPI_PROTOCOL_UNKNOWN)
flow->guessProtocol();
}
if(zflow->dns_query) flow->setDNSQuery(zflow->dns_query);
if(zflow->http_url) flow->setHTTPURL(zflow->http_url);
if(zflow->http_site) flow->setServerName(zflow->http_site);
if(zflow->ssl_server_name) flow->setServerName(zflow->ssl_server_name);
if(zflow->bittorrent_hash) flow->setBTHash(zflow->bittorrent_hash);
/* purge is actually performed at most one time every FLOW_PURGE_FREQUENCY */
// purgeIdle(zflow->last_switched);
}
/* **************************************************** */
void NetworkInterface::dumpPacketDisk(const struct pcap_pkthdr *h, const u_char *packet,
dump_reason reason) {
if(pkt_dumper == NULL)
pkt_dumper = new PacketDumper(this);
if(pkt_dumper)
pkt_dumper->dumpPacket(h, packet, reason, getDumpTrafficSamplingRate(),
getDumpTrafficMaxPktsPerFile(),
getDumpTrafficMaxSecPerFile());
}
/* **************************************************** */
void NetworkInterface::dumpPacketTap(const struct pcap_pkthdr *h, const u_char *packet,
dump_reason reason) {
if(pkt_dumper_tap)
pkt_dumper_tap->writeTap((unsigned char *)packet, h->len, reason,
getDumpTrafficSamplingRate());
}
/* **************************************************** */
bool NetworkInterface::processPacket(const struct bpf_timeval *when,
const u_int64_t time,
struct ndpi_ethhdr *eth,
u_int16_t vlan_id,
struct ndpi_iphdr *iph,
struct ndpi_ipv6hdr *ip6,
u_int16_t ipsize,
u_int32_t rawsize,
const struct pcap_pkthdr *h,
const u_char *packet,
u_int16_t *ndpiProtocol,
Host **srcHost, Host **dstHost,
Flow **hostFlow) {
bool src2dst_direction;
u_int8_t l4_proto;
Flow *flow;
u_int8_t *eth_src = eth->h_source, *eth_dst = eth->h_dest;
IpAddress src_ip, dst_ip;
u_int16_t src_port = 0, dst_port = 0, payload_len = 0;
struct ndpi_tcphdr *tcph = NULL;
struct ndpi_udphdr *udph = NULL;
u_int16_t l4_packet_len;
u_int8_t *l4, tcp_flags = 0, *payload = NULL;
u_int8_t *ip;
bool is_fragment = false, new_flow;
bool pass_verdict = true;
/* VLAN disaggregation */
if((flowHashingMode == flowhashing_vlan) && (vlan_id > 0)) {
NetworkInterface *vIface;
if((vIface = getSubInterface((u_int32_t)vlan_id)) != NULL) {
vIface->setTimeLastPktRcvd(getTimeLastPktRcvd());
return(vIface->processPacket(when, time, eth, vlan_id,
iph, ip6, ipsize, rawsize,
h, packet, ndpiProtocol,
srcHost, dstHost, hostFlow));
}
}
decode_ip:
if(iph != NULL) {
/* IPv4 */
if(ipsize < 20) {
incStats(when->tv_sec, ETHERTYPE_IP, NDPI_PROTOCOL_UNKNOWN,
rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
if((iph->ihl * 4) > ipsize || ipsize < ntohs(iph->tot_len)
|| (iph->frag_off & htons(0x1FFF /* IP_OFFSET */)) != 0) {
is_fragment = true;
}
l4_packet_len = ntohs(iph->tot_len) - (iph->ihl * 4);
l4_proto = iph->protocol;
l4 = ((u_int8_t *) iph + iph->ihl * 4);
ip = (u_int8_t*)iph;
} else {
/* IPv6 */
u_int ipv6_shift = sizeof(const struct ndpi_ipv6hdr);
if(ipsize < sizeof(const struct ndpi_ipv6hdr)) {
incStats(when->tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize,
1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
l4_packet_len = ntohs(ip6->ip6_ctlun.ip6_un1.ip6_un1_plen);
l4_proto = ip6->ip6_ctlun.ip6_un1.ip6_un1_nxt;
if(l4_proto == 0x3C /* IPv6 destination option */) {
u_int8_t *options = (u_int8_t*)ip6 + ipv6_shift;
l4_proto = options[0];
ipv6_shift = 8 * (options[1] + 1);
if(ipsize < ipv6_shift) {
incStats(when->tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
}
l4 = (u_int8_t*)ip6 + ipv6_shift;
ip = (u_int8_t*)ip6;
}
if(l4_proto == IPPROTO_TCP) {
if(l4_packet_len >= sizeof(struct ndpi_tcphdr)) {
u_int tcp_len;
/* TCP */
tcph = (struct ndpi_tcphdr *)l4;
src_port = tcph->source, dst_port = tcph->dest;
tcp_flags = l4[13];
tcp_len = min_val(4*tcph->doff, l4_packet_len);
payload = &l4[tcp_len];
payload_len = max_val(0, l4_packet_len-4*tcph->doff);
// TODO: check if payload should be set to NULL when payload_len == 0
} else {
/* Packet too short: this is a faked packet */
ntop->getTrace()->traceEvent(TRACE_INFO, "Invalid TCP packet received [%u bytes long]", l4_packet_len);
incStats(when->tv_sec, iph ? ETHERTYPE_IP : ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
} else if(l4_proto == IPPROTO_UDP) {
if(l4_packet_len >= sizeof(struct ndpi_udphdr)) {
/* UDP */
udph = (struct ndpi_udphdr *)l4;
src_port = udph->source, dst_port = udph->dest;
payload = &l4[sizeof(struct ndpi_udphdr)];
payload_len = max_val(0, l4_packet_len-sizeof(struct ndpi_udphdr));
} else {
/* Packet too short: this is a faked packet */
ntop->getTrace()->traceEvent(TRACE_INFO, "Invalid UDP packet received [%u bytes long]", l4_packet_len);
incStats(when->tv_sec, iph ? ETHERTYPE_IP : ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
} else if(l4_proto == IPPROTO_GRE) {
struct grev1_header gre;
int offset = sizeof(struct grev1_header);
memcpy(&gre, l4, sizeof(struct grev1_header));
gre.flags_and_version = ntohs(gre.flags_and_version);
gre.proto = ntohs(gre.proto);
if(gre.flags_and_version & (GRE_HEADER_CHECKSUM | GRE_HEADER_ROUTING)) offset += 4;
if(gre.flags_and_version & GRE_HEADER_KEY) offset += 4;
if(gre.flags_and_version & GRE_HEADER_SEQ_NUM) offset += 4;
if(gre.proto == ETHERTYPE_IP) {
iph = (struct ndpi_iphdr*)(l4 + offset), ip6 = NULL;
goto decode_ip;
} else if(gre.proto == ETHERTYPE_IPV6) {
iph = (struct ndpi_iphdr*)(l4 + offset), ip6 = NULL;
goto decode_ip;
} else {
/* Unknown encapsulation */
}
} else {
/* non TCP/UDP protocols */
}
if(iph != NULL)
src_ip.set(iph->saddr), dst_ip.set(iph->daddr);
else
src_ip.set(&ip6->ip6_src), dst_ip.set(&ip6->ip6_dst);
#if defined(WIN32) && defined(DEMO_WIN32)
if(this->ethStats.getNumPackets() > MAX_NUM_PACKETS) {
static bool showMsg = false;
if(!showMsg) {
ntop->getTrace()->traceEvent(TRACE_NORMAL, "-----------------------------------------------------------");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "WARNING: this demo application is a limited ntopng version able to");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "capture up to %d packets. If you are interested", MAX_NUM_PACKETS);
ntop->getTrace()->traceEvent(TRACE_NORMAL, "in the full version please have a look at the ntop");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "home page http://www.ntop.org/.");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "-----------------------------------------------------------");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "");
showMsg = true;
}
return(pass_verdict);
}
#endif
/* Updating Flow */
flow = getFlow(eth_src, eth_dst, vlan_id, 0, 0, 0, &src_ip, &dst_ip, src_port, dst_port,
l4_proto, &src2dst_direction, last_pkt_rcvd, last_pkt_rcvd, &new_flow);
if(flow == NULL) {
incStats(when->tv_sec, iph ? ETHERTYPE_IP : ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN,
rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
} else {
*srcHost = src2dst_direction ? flow->get_cli_host() : flow->get_srv_host();
*dstHost = src2dst_direction ? flow->get_srv_host() : flow->get_cli_host();
*hostFlow = flow;
switch(l4_proto) {
case IPPROTO_TCP:
flow->updateTcpFlags(when, tcp_flags, src2dst_direction);
flow->updateTcpSeqNum(when, ntohl(tcph->seq), ntohl(tcph->ack_seq), ntohs(tcph->window),
tcp_flags, l4_packet_len - (4 * tcph->doff),
src2dst_direction);
break;
case IPPROTO_ICMP:
case IPPROTO_ICMPV6:
if(l4_packet_len > 2) {
u_int8_t icmp_type = l4[0];
u_int8_t icmp_code = l4[1];
if((flow->get_cli_host()->isLocalHost()) && (flow->get_srv_host()->isLocalHost())) {
/* Set correct direction in localhost ping */
if((icmp_type == 8) || /* ICMP Echo [RFC792] */
(icmp_type == 128)) /* ICMPV6 Echo Request [RFC4443] */
src2dst_direction = true;
else if((icmp_type == 0) || /* ICMP Echo Reply [RFC792] */
(icmp_type == 129)) /* ICMPV6 Echo Reply [RFC4443] */
src2dst_direction = false;
}
flow->setICMP(icmp_type, icmp_code);
}
break;
}
#ifdef __OpenBSD__
struct timeval tv_ts;
tv_ts.tv_sec = h->ts.tv_sec;
tv_ts.tv_usec = h->ts.tv_usec;
flow->incStats(src2dst_direction, rawsize, payload, payload_len, l4_proto, &tv_ts);
#else
flow->incStats(src2dst_direction, rawsize, payload, payload_len, l4_proto, &h->ts);
#endif
}
/* Protocol Detection */
flow->updateActivities();
flow->updateInterfaceLocalStats(src2dst_direction, 1, rawsize);
if(!flow->isDetectionCompleted()) {
if(isSampledTraffic())
flow->guessProtocol();
else {
if(!is_fragment) {
struct ndpi_flow_struct *ndpi_flow = flow->get_ndpi_flow();
struct ndpi_id_struct *cli = (struct ndpi_id_struct*)flow->get_cli_id();
struct ndpi_id_struct *srv = (struct ndpi_id_struct*)flow->get_srv_id();
if(flow->get_packets() >= NDPI_MIN_NUM_PACKETS)
flow->setDetectedProtocol(ndpi_detection_giveup(ndpi_struct, ndpi_flow), false);
else
flow->setDetectedProtocol(ndpi_detection_process_packet(ndpi_struct, ndpi_flow,
ip, ipsize, (u_int32_t)time,
cli, srv), false);
} else {
// FIX - only handle unfragmented packets
// ntop->getTrace()->traceEvent(TRACE_WARNING, "IP fragments are not handled yet!");
}
}
}
if(flow->isDetectionCompleted()
&& (!isSampledTraffic())
&& flow->get_cli_host()
&& flow->get_srv_host()) {
struct ndpi_flow_struct *ndpi_flow;
switch(ndpi_get_lower_proto(flow->get_detected_protocol())) {
case NDPI_PROTOCOL_DHCP:
if(payload_len > 240) {
for(int i = 240; i<payload_len; ) {
u_int8_t id = payload[i], len = payload[i+1];
if(len == 0) break;
if(id == 12 /* Host Name */) {
char name[64], buf[24], *client_mac, key[64];
int j;
j = ndpi_min(len, sizeof(name)-1);
strncpy((char*)name, (char*)&payload[i+2], j);
name[j] = '\0';
client_mac = Utils::formatMac(&payload[28], buf, sizeof(buf)),
ntop->getTrace()->traceEvent(TRACE_INFO, "[DHCP] %s = '%s'", client_mac, name);
snprintf(key, sizeof(key), DHCP_CACHE, get_id());
ntop->getRedis()->hashSet(key, client_mac, name);
break;
} else if(id == 0xFF)
break; /* End of options */
i += len + 2;
}
}
break;
case NDPI_PROTOCOL_BITTORRENT:
if((flow->getBitTorrentHash() == NULL)
&& (l4_proto == IPPROTO_UDP)
&& (flow->get_packets() < 8))
flow->dissectBittorrent((char*)payload, payload_len);
break;
case NDPI_PROTOCOL_HTTP:
if(payload_len > 0)
flow->dissectHTTP(src2dst_direction, (char*)payload, payload_len);
break;
case NDPI_PROTOCOL_DNS:
ndpi_flow = flow->get_ndpi_flow();
/*
DNS-over-TCP flows may carry zero-payload TCP segments
e.g., during three-way-handshake, or when acknowledging.
Make sure only non-zero-payload segments are processed.
*/
if((payload_len > 0) && payload) {
/*
DNS-over-TCP has a 2-bytes field with DNS payload length
at the beginning. See RFC1035 section 4.2.2. TCP usage.
*/
u_int8_t dns_offset = l4_proto == IPPROTO_TCP && payload_len > 1 ? 2 : 0;
struct ndpi_dns_packet_header *header = (struct ndpi_dns_packet_header*)(payload + dns_offset);
u_int16_t dns_flags = ntohs(header->flags);
bool is_query = ((dns_flags & 0x8000) == 0x8000) ? false : true;
if(flow->get_cli_host() && flow->get_srv_host()) {
Host *client = src2dst_direction ? flow->get_cli_host() : flow->get_srv_host();
Host *server = src2dst_direction ? flow->get_srv_host() : flow->get_cli_host();
/*
Inside the DNS packet it is possible to have multiple queries
and mix query types. In general this is not a practice followed
by applications.
*/
if(is_query) {
u_int16_t query_type = ndpi_flow ? ndpi_flow->protos.dns.query_type : 0;
client->incNumDNSQueriesSent(query_type), server->incNumDNSQueriesRcvd(query_type);
} else {
u_int8_t ret_code = (dns_flags & 0x000F);
client->incNumDNSResponsesSent(ret_code), server->incNumDNSResponsesRcvd(ret_code);
}
}
}
if(ndpi_flow) {
struct ndpi_id_struct *cli = (struct ndpi_id_struct*)flow->get_cli_id();
struct ndpi_id_struct *srv = (struct ndpi_id_struct*)flow->get_srv_id();
memset(&ndpi_flow->detected_protocol_stack,
0, sizeof(ndpi_flow->detected_protocol_stack));
ndpi_detection_process_packet(ndpi_struct, ndpi_flow,
ip, ipsize, (u_int32_t)time,
src2dst_direction ? cli : srv,
src2dst_direction ? srv : cli);
/*
We reset the nDPI flow so that it can decode new packets
of the same flow (e.g. the DNS response)
*/
ndpi_flow->detected_protocol_stack[0] = NDPI_PROTOCOL_UNKNOWN;
}
break;
default:
if(flow->isSSLProto())
flow->dissectSSL(payload, payload_len, when, src2dst_direction);
}
flow->processDetectedProtocol();
#ifdef NTOPNG_PRO
if(is_bridge_interface()) {
pass_verdict = flow->isPassVerdict();
if(pass_verdict) {
u_int8_t shaper_ingress, shaper_engress;
char buf[64];
flow->getFlowShapers(src2dst_direction, &shaper_ingress, &shaper_engress);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "[%s] %u / %u ",
flow->get_detected_protocol_name(buf, sizeof(buf)),
shaper_ingress, shaper_engress);
pass_verdict = passShaperPacket(shaper_ingress, shaper_engress, (struct pcap_pkthdr*)h);
}
}
#endif
bool dump_if_unknown = dump_unknown_traffic
&& (!flow->isDetectionCompleted() ||
flow->get_detected_protocol().protocol == NDPI_PROTOCOL_UNKNOWN);
if(dump_if_unknown
|| dump_all_traffic
|| dump_security_packets
|| flow->dumpFlowTraffic()) {
if(dump_to_disk) dumpPacketDisk(h, packet, dump_if_unknown ? UNKNOWN : GUI);
if(dump_to_tap) dumpPacketTap(h, packet, GUI);
}
}
incStats(when->tv_sec, iph ? ETHERTYPE_IP : ETHERTYPE_IPV6,
flow->get_detected_protocol().protocol,
rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
// Detect user activities
if((!isSampledTraffic())
&& (ntop->getPrefs()->is_flow_activity_enabled())) {
Host *cli = flow->get_cli_host();
Host *srv = flow->get_srv_host();
if((cli->isLocalHost() || srv->isLocalHost())
&& (!flow->isSSLProto() || flow->isSSLData())) {
UserActivityID activity;
u_int64_t up = 0, down = 0, backgr = 0, bytes = payload_len;
if(flow->getActivityId(&activity)) {
#ifdef __OpenBSD__
struct timeval* tv_when;
tv_when->tv_sec = when->tv_sec;
tv_when->tv_usec = when->tv_usec;
if(flow->invokeActivityFilter(tv_when, src2dst_direction, payload_len)) {
#else
if(flow->invokeActivityFilter(when, src2dst_direction, payload_len)) {
#endif
if(src2dst_direction)
up = bytes;
else
down = bytes;
} else {
backgr = bytes;
}
if(cli->isLocalHost())
cli->incActivityBytes(activity, up, down, backgr);
if(srv->isLocalHost())
srv->incActivityBytes(activity, down, up, backgr);
}
}
}
return(pass_verdict);
}
/* **************************************************** */
void NetworkInterface::purgeIdle(time_t when) {
if(purge_idle_flows_hosts) {
u_int n;
last_pkt_rcvd = when;
if((n = purgeIdleFlows()) > 0)
ntop->getTrace()->traceEvent(TRACE_INFO, "Purged %u/%u idle flows on %s",
n, getNumFlows(), ifname);
if((n = purgeIdleHostsMacs()) > 0)
ntop->getTrace()->traceEvent(TRACE_INFO, "Purged %u/%u idle hosts/macs on %s",
n, getNumHosts()+getNumMacs(), ifname);
}
if(pkt_dumper) pkt_dumper->idle(when);
updateSecondTraffic(when);
}
/* **************************************************** */
bool NetworkInterface::dissectPacket(const struct pcap_pkthdr *h,
const u_char *packet,
u_int16_t *ndpiProtocol,
Host **srcHost, Host **dstHost,
Flow **flow) {
struct ndpi_ethhdr *ethernet, dummy_ethernet;
u_int64_t time;
u_int16_t eth_type, ip_offset, vlan_id = 0, eth_offset = 0;
u_int32_t null_type;
int pcap_datalink_type = get_datalink();
bool pass_verdict = true;
u_int32_t rawsize = h->len * scalingFactor;
if(h->len > ifMTU) {
if(!mtuWarningShown) {
ntop->getTrace()->traceEvent(TRACE_NORMAL, "Invalid packet received [len: %u][max-len: %u].", h->len, ifMTU);
ntop->getTrace()->traceEvent(TRACE_WARNING, "If you have TSO/GRO enabled, please disable it");
#ifdef linux
ntop->getTrace()->traceEvent(TRACE_WARNING, "Use sudo ethtool -K %s gro off gso off tso off", ifname);
#endif
mtuWarningShown = true;
}
}
setTimeLastPktRcvd(h->ts.tv_sec);
time = ((uint64_t) h->ts.tv_sec) * 1000 + h->ts.tv_usec / 1000;
datalink_check:
if(pcap_datalink_type == DLT_NULL) {
memcpy(&null_type, &packet[eth_offset], sizeof(u_int32_t));
switch(null_type) {
case BSD_AF_INET:
eth_type = ETHERTYPE_IP;
break;
case BSD_AF_INET6_BSD:
case BSD_AF_INET6_FREEBSD:
case BSD_AF_INET6_DARWIN:
eth_type = ETHERTYPE_IPV6;
break;
default:
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict); /* Any other non IP protocol */
}
memset(&dummy_ethernet, 0, sizeof(dummy_ethernet));
ethernet = (struct ndpi_ethhdr *)&dummy_ethernet;
ip_offset = 4 + eth_offset;
} else if(pcap_datalink_type == DLT_EN10MB) {
ethernet = (struct ndpi_ethhdr *)&packet[eth_offset];
ip_offset = sizeof(struct ndpi_ethhdr) + eth_offset;
eth_type = ntohs(ethernet->h_proto);
} else if(pcap_datalink_type == 113 /* Linux Cooked Capture */) {
memset(&dummy_ethernet, 0, sizeof(dummy_ethernet));
ethernet = (struct ndpi_ethhdr *)&dummy_ethernet;
eth_type = (packet[eth_offset+14] << 8) + packet[eth_offset+15];
ip_offset = 16 + eth_offset;
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
#ifdef DLT_RAW
} else if(pcap_datalink_type == DLT_RAW /* Linux TUN/TAP device in TUN mode; Raw IP capture */) {
switch((packet[eth_offset] & 0xf0) >> 4) {
case 4:
eth_type = ETHERTYPE_IP;
break;
case 6:
eth_type = ETHERTYPE_IPV6;
break;
default:
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict); /* Unknown IP protocol version */
}
memset(&dummy_ethernet, 0, sizeof(dummy_ethernet));
ethernet = (struct ndpi_ethhdr *)&dummy_ethernet;
ip_offset = eth_offset;
#endif /* DLT_RAW */
} else if(pcap_datalink_type == DLT_IPV4) {
eth_type = ETHERTYPE_IP;
memset(&dummy_ethernet, 0, sizeof(dummy_ethernet));
ethernet = (struct ndpi_ethhdr *)&dummy_ethernet;
ip_offset = 0;
} else {
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
while(true) {
if(eth_type == 0x8100 /* VLAN */) {
Ether80211q *qType = (Ether80211q*)&packet[ip_offset];
vlan_id = ntohs(qType->vlanId) & 0xFFF;
eth_type = (packet[ip_offset+2] << 8) + packet[ip_offset+3];
ip_offset += 4;
} else if(eth_type == 0x8847 /* MPLS */) {
u_int8_t bos; /* bottom_of_stack */
bos = (((u_int8_t)packet[ip_offset+2]) & 0x1), ip_offset += 4;
if(bos) {
eth_type = ETHERTYPE_IP;
break;
}
} else
break;
}
decode_packet_eth:
switch(eth_type) {
case ETHERTYPE_PPOE:
eth_type = ETHERTYPE_IP;
ip_offset += 8;
goto decode_packet_eth;
break;
case ETHERTYPE_IP:
if(h->caplen >= ip_offset) {
u_int16_t frag_off;
struct ndpi_iphdr *iph = (struct ndpi_iphdr *) &packet[ip_offset];
struct ndpi_ipv6hdr *ip6 = NULL;
if(iph->version != 4) {
/* This is not IPv4 */
incStats(h->ts.tv_sec, ETHERTYPE_IP, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
} else
frag_off = ntohs(iph->frag_off);
if(ntop->getGlobals()->decode_tunnels() && (iph->protocol == IPPROTO_UDP)
&& ((frag_off & 0x3FFF /* IP_MF | IP_OFFSET */ ) == 0)) {
u_short ip_len = ((u_short)iph->ihl * 4);
struct ndpi_udphdr *udp = (struct ndpi_udphdr *)&packet[ip_offset+ip_len];
u_int16_t sport = ntohs(udp->source), dport = ntohs(udp->dest);
if((sport == GTP_U_V1_PORT) || (dport == GTP_U_V1_PORT)) {
/* Check if it's GTPv1 */
u_int offset = (u_int)(ip_offset+ip_len+sizeof(struct ndpi_udphdr));
u_int8_t flags = packet[offset];
u_int8_t message_type = packet[offset+1];
if((((flags & 0xE0) >> 5) == 1 /* GTPv1 */) && (message_type == 0xFF /* T-PDU */)) {
ip_offset = ip_offset+ip_len+sizeof(struct ndpi_udphdr)+8 /* GTPv1 header len */;
if(flags & 0x04) ip_offset += 1; /* next_ext_header is present */
if(flags & 0x02) ip_offset += 4; /* sequence_number is present (it also includes next_ext_header and pdu_number) */
if(flags & 0x01) ip_offset += 1; /* pdu_number is present */
iph = (struct ndpi_iphdr *) &packet[ip_offset];
if(iph->version != 4) {
/* FIX - Add IPv6 support */
incStats(h->ts.tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
}
} else if((sport == TZSP_PORT) || (dport == TZSP_PORT)) {
/* https://en.wikipedia.org/wiki/TZSP */
u_int offset = ip_offset+ip_len+sizeof(struct ndpi_udphdr);
u_int8_t version = packet[offset];
u_int8_t type = packet[offset+1];
u_int16_t encapsulates = ntohs(*((u_int16_t*)&packet[offset+2]));
if((version == 1) && (type == 0) && (encapsulates == 1)) {
u_int8_t stop = 0;
offset += 4;
while((!stop) && (offset < h->caplen)) {
u_int8_t tag_type = packet[offset];
u_int8_t tag_len;
switch(tag_type) {
case 0: /* PADDING Tag */
tag_len = 1;
break;
case 1: /* END Tag */
tag_len = 1, stop = 1;
break;
default:
tag_len = packet[offset+1];
break;
}
offset += tag_len;
if(offset >= h->caplen) {
incStats(h->ts.tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
} else {
eth_offset = offset;
goto datalink_check;
}
}
}
}
if((sport == CAPWAP_DATA_PORT) || (dport == CAPWAP_DATA_PORT)) {
/*
Control And Provisioning of Wireless Access Points
https://www.rfc-editor.org/rfc/rfc5415.txt
CAPWAP Header - variable length (5 MSB of byte 2 of header)
IEEE 802.11 Data Flags - 24 bytes
Logical-Link Control - 8 bytes
Total = CAPWAP_header_length + 24 + 8
*/
u_short eth_type;
ip_offset = ip_offset+ip_len+sizeof(struct ndpi_udphdr);
u_int8_t capwap_header_len = ((*(u_int8_t*)&packet[ip_offset+1])>>3)*4;
ip_offset = ip_offset+capwap_header_len+24+8;
if(ip_offset >= h->len) {
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
eth_type = ntohs(*(u_int16_t*)&packet[ip_offset-2]);
switch(eth_type) {
case ETHERTYPE_IP:
iph = (struct ndpi_iphdr *) &packet[ip_offset];
break;
case ETHERTYPE_IPV6:
iph = NULL;
ip6 = (struct ndpi_ipv6hdr*)&packet[ip_offset];
break;
default:
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
}
}
if((vlan_id == 0) && ntop->getPrefs()->do_simulate_vlans())
vlan_id = (ip6 ? ip6->ip6_src.u6_addr.u6_addr8[15] : iph->saddr) & 0xFF;
try {
pass_verdict = processPacket(&h->ts, time, ethernet, vlan_id, iph,
ip6, h->caplen - ip_offset, rawsize,
h, packet, ndpiProtocol, srcHost, dstHost, flow);
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
}
}
break;
case ETHERTYPE_IPV6:
if(h->caplen >= ip_offset) {
struct ndpi_iphdr *iph = NULL;
struct ndpi_ipv6hdr *ip6 = (struct ndpi_ipv6hdr*)&packet[ip_offset];
if((ntohl(ip6->ip6_ctlun.ip6_un1.ip6_un1_flow) & 0xF0000000) != 0x60000000) {
/* This is not IPv6 */
incStats(h->ts.tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
} else {
u_int ipv6_shift = sizeof(const struct ndpi_ipv6hdr);
u_int8_t l4_proto = ip6->ip6_ctlun.ip6_un1.ip6_un1_nxt;
if(l4_proto == 0x3C /* IPv6 destination option */) {
u_int8_t *options = (u_int8_t*)ip6 + ipv6_shift;
l4_proto = options[0];
ipv6_shift = 8 * (options[1] + 1);
}
if(ntop->getGlobals()->decode_tunnels() && (l4_proto == IPPROTO_UDP)) {
ip_offset += ipv6_shift;
if(ip_offset >= h->len) {
incStats(h->ts.tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
struct ndpi_udphdr *udp = (struct ndpi_udphdr *)&packet[ip_offset];
u_int16_t sport = udp->source, dport = udp->dest;
if((sport == CAPWAP_DATA_PORT) || (dport == CAPWAP_DATA_PORT)) {
/*
Control And Provisioning of Wireless Access Points
https://www.rfc-editor.org/rfc/rfc5415.txt
CAPWAP Header - variable length (5 MSB of byte 2 of header)
IEEE 802.11 Data Flags - 24 bytes
Logical-Link Control - 8 bytes
Total = CAPWAP_header_length + 24 + 8
*/
u_short eth_type;
ip_offset = ip_offset+sizeof(struct ndpi_udphdr);
u_int8_t capwap_header_len = ((*(u_int8_t*)&packet[ip_offset+1])>>3)*4;
ip_offset = ip_offset+capwap_header_len+24+8;
if(ip_offset >= h->len) {
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
eth_type = ntohs(*(u_int16_t*)&packet[ip_offset-2]);
switch(eth_type) {
case ETHERTYPE_IP:
iph = (struct ndpi_iphdr *) &packet[ip_offset];
ip6 = NULL;
break;
case ETHERTYPE_IPV6:
ip6 = (struct ndpi_ipv6hdr*)&packet[ip_offset];
break;
default:
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
}
}
if((vlan_id == 0) && ntop->getPrefs()->do_simulate_vlans())
vlan_id = (ip6 ? ip6->ip6_src.u6_addr.u6_addr8[15] : iph->saddr) & 0xFF;
try {
pass_verdict = processPacket(&h->ts, time, ethernet, vlan_id,
iph, ip6, h->len - ip_offset, rawsize,
h, packet, ndpiProtocol, srcHost, dstHost, flow);
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
}
}
}
break;
default: /* No IPv4 nor IPv6 */
Mac *srcMac = getMac(ethernet->h_source, vlan_id, true);
Mac *dstMac = getMac(ethernet->h_dest, vlan_id, true);
if(srcMac) srcMac->incSentStats(rawsize);
if(dstMac) dstMac->incRcvdStats(rawsize);
incStats(h->ts.tv_sec, eth_type, NDPI_PROTOCOL_UNKNOWN, rawsize,
1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
break;
}
purgeIdle(last_pkt_rcvd);
return(pass_verdict);
}
/* **************************************************** */
void NetworkInterface::startPacketPolling() {
if((cpu_affinity != -1) && (ntop->getNumCPUs() > 1)) {
if(Utils::setThreadAffinity(pollLoop, cpu_affinity))
ntop->getTrace()->traceEvent(TRACE_WARNING, "Could not set affinity of interface %s to core %d",
get_name(), cpu_affinity);
else
ntop->getTrace()->traceEvent(TRACE_NORMAL, "Setting affinity of interface %s to core %d",
get_name(), cpu_affinity);
}
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"Started packet polling on interface %s [id: %u]...",
get_name(), get_id());
running = true;
}
/* **************************************************** */
void NetworkInterface::shutdown() {
running = false;
}
/* **************************************************** */
void NetworkInterface::cleanup() {
next_idle_flow_purge = next_idle_host_purge = 0;
cpu_affinity = -1, has_vlan_packets = false;
running = false, sprobe_interface = false, inline_interface = false;
getStats()->cleanup();
flows_hash->cleanup();
hosts_hash->cleanup();
macs_hash->cleanup();
ntop->getTrace()->traceEvent(TRACE_NORMAL, "Cleanup interface %s", get_name());
}
/* **************************************************** */
void NetworkInterface::findFlowHosts(u_int16_t vlanId,
u_int8_t src_mac[6], IpAddress *_src_ip, Host **src,
u_int8_t dst_mac[6], IpAddress *_dst_ip, Host **dst) {
if(!isView())
(*src) = hosts_hash->get(vlanId, _src_ip);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
if(((*src) = subInterfaces[s]->get_hosts_hash()->get(vlanId, _src_ip)) != NULL)
break;
}
}
if((*src) == NULL) {
if(!hosts_hash->hasEmptyRoom()) {
*src = *dst = NULL;
triggerTooManyHostsAlert();
return;
}
(*src) = new Host(this, src_mac, vlanId, _src_ip);
if(!hosts_hash->add(*src)) {
//ntop->getTrace()->traceEvent(TRACE_WARNING, "Too many hosts in interface %s", ifname);
delete *src;
*src = *dst = NULL;
triggerTooManyHostsAlert();
return;
}
}
/* ***************************** */
(*dst) = hosts_hash->get(vlanId, _dst_ip);
if((*dst) == NULL) {
if(!hosts_hash->hasEmptyRoom()) {
*dst = NULL;
triggerTooManyHostsAlert();
return;
}
(*dst) = new Host(this, dst_mac, vlanId, _dst_ip);
if(!hosts_hash->add(*dst)) {
// ntop->getTrace()->traceEvent(TRACE_WARNING, "Too many hosts in interface %s", ifname);
delete *dst;
*dst = NULL;
triggerTooManyHostsAlert();
return;
}
}
}
/* **************************************************** */
struct ndpiStatsRetrieverData {
nDPIStats *stats;
Host *host;
};
static bool flow_sum_protos(GenericHashEntry *flow, void *user_data) {
ndpiStatsRetrieverData *retriever = (ndpiStatsRetrieverData*)user_data;
nDPIStats *stats = retriever->stats;
Flow *f = (Flow*)flow;
if(retriever->host
&& (retriever->host != f->get_cli_host())
&& (retriever->host != f->get_srv_host()))
return(false); /* false = keep on walking */
f->sumStats(stats);
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::getnDPIStats(nDPIStats *stats, AddressTree *allowed_hosts,
const char *host_ip, u_int16_t vlan_id) {
ndpiStatsRetrieverData retriever;
Host *h = NULL;
if (host_ip)
h = findHostsByIP(allowed_hosts, (char *)host_ip, vlan_id);
retriever.stats = stats;
retriever.host = h;
walker(walker_flows, flow_sum_protos, (void*)&retriever);
}
/* **************************************************** */
static bool flow_update_hosts_stats(GenericHashEntry *node, void *user_data) {
Flow *flow = (Flow*)node;
struct timeval *tv = (struct timeval*)user_data;
flow->update_hosts_stats(tv, false);
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool update_hosts_stats(GenericHashEntry *node, void *user_data) {
Host *host = (Host*)node;
struct timeval *tv = (struct timeval*)user_data;
host->updateStats(tv);
/*
ntop->getTrace()->traceEvent(TRACE_WARNING, "Updated: %s [%d]",
((StringHost*)node)->host_key(),
host->getThptTrend());
*/
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool update_macs_stats(GenericHashEntry *node, void *user_data) {
Mac *mac = (Mac*)node;
struct timeval *tv = (struct timeval*)user_data;
mac->updateStats(tv);
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::periodicStatsUpdate() {
struct timeval tv;
if(isView()) return;
gettimeofday(&tv, NULL);
flows_hash->walk(flow_update_hosts_stats, (void*)&tv);
hosts_hash->walk(update_hosts_stats, (void*)&tv);
macs_hash->walk(update_macs_stats, (void*)&tv);
if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
static_cast<MySQLDB*>(db)->updateStats(&tv);
db->flush(false /* not idle, periodic activities */);
}
#ifdef NTOPNG_PRO
if(host_pools)
host_pools->updateStats(&tv);
#endif
}
/* **************************************************** */
struct update_host_pool_l7policy {
bool update_pool_id;
bool update_l7policy;
};
static bool update_host_host_pool_l7policy(GenericHashEntry *node, void *user_data) {
Host *h = (Host*)node;
update_host_pool_l7policy *up = (update_host_pool_l7policy*)user_data;
#ifdef HOST_POOLS_DEBUG
char buf[128];
u_int16_t cur_pool_id = h->get_host_pool();
#endif
if(up->update_pool_id)
h->updateHostPool();
if(up->update_l7policy)
h->updateHostL7Policy();
#ifdef HOST_POOLS_DEBUG
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"Going to refresh pool for %s "
"[refresh pool id: %i] "
"[refresh l7policy: %i] "
"[host pool id before refresh: %i] "
"[host pool id after refresh: %i] ",
h->get_ip()->print(buf, sizeof(buf)),
up->update_pool_id ? 1 : 0,
up->update_l7policy ? 1 : 0,
cur_pool_id,
h->get_host_pool());
#endif
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::refreshHostPools() {
if(isView()) return;
struct update_host_pool_l7policy update_host;
update_host.update_pool_id = true;
update_host.update_l7policy = false;
#ifdef NTOPNG_PRO
if(is_bridge_interface() && getL7Policer()) {
/* Every pool is associated with a set of L7 rules
so a refresh must be triggered to seal this association */
getL7Policer()->refreshL7Rules();
/* Must refresh host l7policies as a change in the host pool id
may determine an l7policy change for that host */
update_host.update_l7policy = true;
}
#endif
hosts_hash->walk(update_host_host_pool_l7policy, &update_host);
#ifdef NTOPNG_PRO
if(update_host.update_l7policy)
updateFlowsL7Policy();
#endif
}
/* **************************************************** */
#ifdef NTOPNG_PRO
/* **************************************************** */
static bool update_flow_l7_policy(GenericHashEntry *node, void *user_data) {
Flow *f = (Flow*)node;
f->updateFlowShapers();
f->updateProfile();
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::updateHostsL7Policy(u_int16_t host_pool_id) {
if(isView()) return;
struct update_host_pool_l7policy update_host;
update_host.update_pool_id = false;
update_host.update_l7policy = true;
hosts_hash->walk(update_host_host_pool_l7policy, &update_host);
}
/* **************************************************** */
void NetworkInterface::updateFlowsL7Policy() {
if(isView()) return;
flows_hash->walk(update_flow_l7_policy, NULL);
}
#endif
/* **************************************************** */
struct host_find_info {
char *host_to_find;
u_int16_t vlan_id;
Host *h;
};
/* **************************************************** */
struct mac_find_info {
u_int8_t mac[6];
u_int16_t vlan_id;
Mac *m;
};
/* **************************************************** */
static bool find_host_by_name(GenericHashEntry *h, void *user_data) {
struct host_find_info *info = (struct host_find_info*)user_data;
Host *host = (Host*)h;
#ifdef DEBUG
char buf[64];
ntop->getTrace()->traceEvent(TRACE_WARNING, "[%s][%s][%s]",
host->get_ip() ? host->get_ip()->print(buf, sizeof(buf)) : "",
host->get_name(), info->host_to_find);
#endif
if((info->h == NULL) && (host->get_vlan_id() == info->vlan_id)) {
if((host->get_name() == NULL) && host->get_ip()) {
char ip_buf[32], name_buf[96];
char *ipaddr = host->get_ip()->print(ip_buf, sizeof(ip_buf));
int rc = ntop->getRedis()->getAddress(ipaddr, name_buf, sizeof(name_buf),
false /* Don't resolve it if not known */);
if(rc == 0 /* found */) host->setName(name_buf);
}
if(host->get_name() && (!strcmp(host->get_name(), info->host_to_find))) {
info->h = host;
return(true); /* found */
}
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool find_mac_by_name(GenericHashEntry *h, void *user_data) {
struct mac_find_info *info = (struct mac_find_info*)user_data;
Mac *m = (Mac*)h;
if((info->m == NULL)
&& (m->get_vlan_id() == info->vlan_id)
&& (!memcmp(info->mac, m->get_mac(), 6))
) {
info->m = m;
return(true); /* found */
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
bool NetworkInterface::restoreHost(char *host_ip, u_int16_t vlan_id) {
Host *h = new Host(this, host_ip, vlan_id);
if(!h) return(false);
if(!hosts_hash->add(h)) {
//ntop->getTrace()->traceEvent(TRACE_WARNING, "Too many hosts in interface %s", ifname);
delete h;
return(false);
}
return(true);
}
/* **************************************************** */
Host* NetworkInterface::getHost(char *host_ip, u_int16_t vlan_id) {
struct in_addr a4;
struct in6_addr a6;
Host *h = NULL;
if(!host_ip) return(NULL);
/* Check if address is invalid */
if((inet_pton(AF_INET, (const char*)host_ip, &a4) == 0)
&& (inet_pton(AF_INET6, (const char*)host_ip, &a6) == 0)) {
/* Looks like a symbolic name */
struct host_find_info info;
memset(&info, 0, sizeof(info));
info.host_to_find = host_ip, info.vlan_id = vlan_id;
walker(walker_hosts, find_host_by_name, (void*)&info);
h = info.h;
} else {
IpAddress *ip = new IpAddress();
if(ip) {
ip->set(host_ip);
if(!isView())
h = hosts_hash->get(vlan_id, ip);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
h = subInterfaces[s]->get_hosts_hash()->get(vlan_id, ip);
if(h) break;
}
}
delete ip;
}
}
return(h);
}
/* **************************************************** */
#ifdef NTOPNG_PRO
static bool update_flow_profile(GenericHashEntry *h, void *user_data) {
Flow *flow = (Flow*)h;
flow->updateProfile();
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::updateFlowProfiles() {
if(isView()) return;
if(ntop->getPro()->has_valid_license()) {
FlowProfiles *newP;
if(shadow_flow_profiles) {
delete shadow_flow_profiles;
shadow_flow_profiles = NULL;
}
flow_profiles->dumpCounters();
shadow_flow_profiles = flow_profiles, newP = new FlowProfiles(id);
newP->loadProfiles(); /* and reload */
flow_profiles = newP; /* Overwrite the current profiles */
flows_hash->walk(update_flow_profile, NULL);
}
}
#endif
/* **************************************************** */
bool NetworkInterface::getHostInfo(lua_State* vm,
AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
Host *h = findHostsByIP(allowed_hosts, host_ip, vlan_id);
if(h) {
h->lua(vm, allowed_hosts, true, true, true, false, false);
return(true);
} else
return(false);
}
/* **************************************************** */
bool NetworkInterface::loadHostAlertPrefs(lua_State* vm,
AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
Host *h = findHostsByIP(allowed_hosts, host_ip, vlan_id);
if(h) {
h->loadAlertPrefs();
return(true);
}
return(false);
}
/* **************************************************** */
Host* NetworkInterface::findHostsByIP(AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
if(host_ip != NULL) {
Host *h = getHost(host_ip, vlan_id);
if(h && h->match(allowed_hosts))
return(h);
}
return(NULL);
}
/* **************************************************** */
struct flowHostRetrieveList {
Flow *flow;
/* Value */
Host *hostValue;
Mac *macValue;
u_int64_t numericValue;
char *stringValue;
};
struct flowHostRetriever {
/* Search criteria */
AddressTree *allowed_hosts;
Host *host;
Mac *mac;
char *manufacturer;
bool skipSpecialMacs, hostMacsOnly;
char *country;
int ndpi_proto;
sortField sorter;
LocationPolicy location;
u_int16_t *vlan_id;
char *osFilter;
u_int32_t *asnFilter;
int16_t *networkFilter;
u_int16_t *poolFilter;
/* Return values */
u_int32_t maxNumEntries, actNumEntries;
struct flowHostRetrieveList *elems;
/* Paginator */
Paginator *pag;
};
/* **************************************************** */
static bool flow_search_walker(GenericHashEntry *h, void *user_data) {
struct flowHostRetriever *retriever = (struct flowHostRetriever*)user_data;
Flow *f = (Flow*)h;
int ndpi_proto;
u_int16_t port;
int16_t local_network_id;
if(retriever->actNumEntries >= retriever->maxNumEntries)
return(true); /* Limit reached */
if(f && (!f->idle())) {
if(retriever->host
&& (retriever->host != f->get_cli_host())
&& (retriever->host != f->get_srv_host()))
return(false); /* false = keep on walking */
if(retriever->pag
&& retriever->pag->l7protoFilter(&ndpi_proto)
&& ndpi_proto != -1
&& (f->get_detected_protocol().protocol != ndpi_proto)
&& (f->get_detected_protocol().master_protocol != ndpi_proto))
return(false); /* false = keep on walking */
if(retriever->pag
&& retriever->pag->portFilter(&port)
&& f->get_cli_port() != port
&& f->get_srv_port() != port)
return(false); /* false = keep on walking */
if(retriever->pag
&& retriever->pag->localNetworkFilter(&local_network_id)
&& f->get_cli_host()->get_local_network_id() != local_network_id
&& f->get_srv_host()->get_local_network_id() != local_network_id)
return(false); /* false = keep on walking */
if(retriever->location == location_local_only) {
if((!f->get_cli_host()->isLocalHost())
|| (!f->get_srv_host()->isLocalHost()))
return(false); /* false = keep on walking */
} else if(retriever->location == location_remote_only) {
if((f->get_cli_host()->isLocalHost())
|| (f->get_srv_host()->isLocalHost()))
return(false); /* false = keep on walking */
}
retriever->elems[retriever->actNumEntries].flow = f;
if(f->match(retriever->allowed_hosts)) {
switch(retriever->sorter) {
case column_client:
retriever->elems[retriever->actNumEntries++].hostValue = f->get_cli_host();
break;
case column_server:
retriever->elems[retriever->actNumEntries++].hostValue = f->get_srv_host();
break;
case column_vlan:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_vlan_id();
break;
case column_proto_l4:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_protocol();
break;
case column_ndpi:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_detected_protocol().protocol;
break;
case column_duration:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_duration();
break;
case column_thpt:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_bytes_thpt();
break;
case column_bytes:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_bytes();
break;
case column_info:
if(f->getDNSQuery()) retriever->elems[retriever->actNumEntries++].stringValue = f->getDNSQuery();
else if(f->getHTTPURL()) retriever->elems[retriever->actNumEntries++].stringValue = f->getHTTPURL();
else if(f->getSSLCertificate()) retriever->elems[retriever->actNumEntries++].stringValue = f->getSSLCertificate();
else retriever->elems[retriever->actNumEntries++].stringValue = (char*)"";
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Internal error: column %d not handled", retriever->sorter);
break;
}
}
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool host_search_walker(GenericHashEntry *he, void *user_data) {
char buf[64];
struct flowHostRetriever *r = (struct flowHostRetriever*)user_data;
Host *h = (Host*)he;
if(r->actNumEntries >= r->maxNumEntries)
return(true); /* Limit reached */
if(!h || h->idle() || !h->match(r->allowed_hosts))
return(false);
if((r->location == location_local_only && !h->isLocalHost()) ||
(r->location == location_remote_only && h->isLocalHost()) ||
(r->vlan_id && *(r->vlan_id) != h->get_vlan_id()) ||
(r->asnFilter && *(r->asnFilter) != h->get_asn()) ||
(r->networkFilter && *(r->networkFilter) != h->get_local_network_id()) ||
(r->networkFilter && *(r->networkFilter) != h->get_local_network_id()) ||
(r->hostMacsOnly && h->getMac() && h->getMac()->isSpecialMac()) ||
(r->mac && (h->getMac() != r->mac)) ||
(r->poolFilter && *(r->poolFilter) != h->get_host_pool()) ||
(r->country && strlen(r->country) && (!h->get_country() || strcmp(h->get_country(), r->country))) ||
(r->osFilter && strlen(r->osFilter) && (!h->get_os() || strcmp(h->get_os(), r->osFilter))))
return(false); /* false = keep on walking */
r->elems[r->actNumEntries].hostValue = h;
switch(r->sorter) {
case column_ip:
r->elems[r->actNumEntries++].hostValue = h; /* hostValue was already set */
break;
case column_alerts:
r->elems[r->actNumEntries++].numericValue = h->getNumAlerts();
break;
case column_name:
r->elems[r->actNumEntries++].stringValue = strdup(h->get_name(buf, sizeof(buf), false));
break;
case column_country:
r->elems[r->actNumEntries++].stringValue = strdup(h->get_country() ? h->get_country() : (char*)"");
break;
case column_os:
r->elems[r->actNumEntries++].stringValue = strdup(h->get_os() ? h->get_os() : (char*)"");
break;
case column_vlan:
r->elems[r->actNumEntries++].numericValue = h->get_vlan_id();
break;
case column_since:
r->elems[r->actNumEntries++].numericValue = h->get_first_seen();
break;
case column_asn:
r->elems[r->actNumEntries++].numericValue = h->get_asn();
break;
case column_thpt:
r->elems[r->actNumEntries++].numericValue = h->getBytesThpt();
break;
case column_num_flows:
r->elems[r->actNumEntries++].numericValue = h->getNumActiveFlows();
break;
case column_traffic:
r->elems[r->actNumEntries++].numericValue = h->getNumBytes();
break;
case column_local_network_id:
r->elems[r->actNumEntries++].numericValue = h->get_local_network_id();
break;
case column_mac:
r->elems[r->actNumEntries++].numericValue = Utils::macaddr_int(h->get_mac());
break;
case column_pool_id:
r->elems[r->actNumEntries++].numericValue = h->get_host_pool();
break;
/* Criteria */
case column_uploaders: r->elems[r->actNumEntries++].numericValue = h->getNumBytesSent(); break;
case column_downloaders: r->elems[r->actNumEntries++].numericValue = h->getNumBytesRcvd(); break;
case column_unknowers: r->elems[r->actNumEntries++].numericValue = h->get_ndpi_stats()->getProtoBytes(NDPI_PROTOCOL_UNKNOWN); break;
case column_incomingflows: r->elems[r->actNumEntries++].numericValue = h->getNumIncomingFlows(); break;
case column_outgoingflows: r->elems[r->actNumEntries++].numericValue = h->getNumOutgoingFlows(); break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Internal error: column %d not handled", r->sorter);
break;
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool mac_search_walker(GenericHashEntry *he, void *user_data) {
struct flowHostRetriever *r = (struct flowHostRetriever*)user_data;
Mac *m = (Mac*)he;
if(r->actNumEntries >= r->maxNumEntries)
return(true); /* Limit reached */
if(!m
|| m->idle()
|| ((r->vlan_id && (*(r->vlan_id) != m->get_vlan_id())))
|| (r->skipSpecialMacs && m->isSpecialMac())
|| (r->hostMacsOnly && m->getNumHosts() == 0))
return(false); /* false = keep on walking */
r->elems[r->actNumEntries].macValue = m;
switch(r->sorter) {
case column_mac:
r->elems[r->actNumEntries++].numericValue = Utils::macaddr_int(m->get_mac());
break;
case column_vlan:
r->elems[r->actNumEntries++].numericValue = m->get_vlan_id();
break;
case column_since:
r->elems[r->actNumEntries++].numericValue = m->get_first_seen();
break;
case column_thpt:
r->elems[r->actNumEntries++].numericValue = m->getBytesThpt();
break;
case column_traffic:
r->elems[r->actNumEntries++].numericValue = m->getNumBytes();
break;
case column_num_hosts:
r->elems[r->actNumEntries++].numericValue = m->getNumHosts();
break;
case column_manufacturer:
r->elems[r->actNumEntries++].stringValue = m->get_manufacturer() ? (char*)m->get_manufacturer() : (char*)"zzz";
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Internal error: column %d not handled", r->sorter);
break;
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
int hostSorter(const void *_a, const void *_b) {
struct flowHostRetrieveList *a = (struct flowHostRetrieveList*)_a;
struct flowHostRetrieveList *b = (struct flowHostRetrieveList*)_b;
return(a->hostValue->get_ip()->compare(b->hostValue->get_ip()));
}
int numericSorter(const void *_a, const void *_b) {
struct flowHostRetrieveList *a = (struct flowHostRetrieveList*)_a;
struct flowHostRetrieveList *b = (struct flowHostRetrieveList*)_b;
if(a->numericValue < b->numericValue) return(-1);
else if(a->numericValue > b->numericValue) return(1);
else return(0);
}
int stringSorter(const void *_a, const void *_b) {
struct flowHostRetrieveList *a = (struct flowHostRetrieveList*)_a;
struct flowHostRetrieveList *b = (struct flowHostRetrieveList*)_b;
return(strcmp(a->stringValue, b->stringValue));
}
/* **************************************************** */
void NetworkInterface::disablePurge(bool on_flows) {
if(!isView()) {
if(on_flows)
flows_hash->disablePurge();
else {
hosts_hash->disablePurge();
macs_hash->disablePurge();
}
} else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
if(on_flows)
subInterfaces[s]->get_flows_hash()->disablePurge();
else {
subInterfaces[s]->get_hosts_hash()->disablePurge();
subInterfaces[s]->get_macs_hash()->disablePurge();
}
}
}
}
/* **************************************************** */
void NetworkInterface::enablePurge(bool on_flows) {
if(!isView()) {
if(on_flows)
flows_hash->enablePurge();
else {
hosts_hash->enablePurge();
macs_hash->enablePurge();
}
} else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
if(on_flows)
subInterfaces[s]->get_flows_hash()->enablePurge();
else {
subInterfaces[s]->get_hosts_hash()->enablePurge();
subInterfaces[s]->get_macs_hash()->enablePurge();
}
}
}
}
/* **************************************************** */
int NetworkInterface::getFlows(lua_State* vm,
AddressTree *allowed_hosts,
Host *host, int ndpi_proto,
LocationPolicy location,
char *sortColumn,
u_int32_t maxHits,
u_int32_t toSkip,
bool a2zSortOrder) {
struct flowHostRetriever retriever;
int (*sorter)(const void *_a, const void *_b);
DetailsLevel highDetails = (location == location_local_only || (maxHits != CONST_MAX_NUM_HITS)) ? details_high : details_normal;
if((maxHits > CONST_MAX_NUM_HITS) || (maxHits == 0)) maxHits = CONST_MAX_NUM_HITS;
retriever.pag = NULL;
retriever.host = host, retriever.ndpi_proto = ndpi_proto, retriever.location = location;
retriever.actNumEntries = 0, retriever.maxNumEntries = getFlowsHashSize(), retriever.allowed_hosts = allowed_hosts;
retriever.elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever.maxNumEntries);
if(retriever.elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
if(!strcmp(sortColumn, "column_client")) retriever.sorter = column_client, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_vlan")) retriever.sorter = column_vlan, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_server")) retriever.sorter = column_server, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_proto_l4")) retriever.sorter = column_proto_l4, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_ndpi")) retriever.sorter = column_ndpi, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_duration")) retriever.sorter = column_duration, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_thpt")) retriever.sorter = column_thpt, sorter = numericSorter;
else if((!strcmp(sortColumn, "column_bytes")) || (!strcmp(sortColumn, "column_") /* default */)) retriever.sorter = column_bytes, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_info")) retriever.sorter = column_info, sorter = stringSorter;
else ntop->getTrace()->traceEvent(TRACE_WARNING, "Unknown sort column %s", sortColumn), sorter = numericSorter;
/* ******************************* */
disablePurge(true);
walker(walker_flows, flow_search_walker, (void*)&retriever);
qsort(retriever.elems, retriever.actNumEntries, sizeof(struct flowHostRetrieveList), sorter);
lua_newtable(vm);
if(a2zSortOrder) {
for(int i=toSkip, num=0; i<(int)retriever.actNumEntries; i++) {
lua_newtable(vm);
retriever.elems[i].flow->lua(vm, allowed_hosts, highDetails, true);
lua_pushnumber(vm, num + 1);
lua_insert(vm, -2);
lua_settable(vm, -3);
if(++num >= (int)maxHits) break;
}
} else {
for(int i=(retriever.actNumEntries-1-toSkip), num=0; i>=0; i--) {
lua_newtable(vm);
retriever.elems[i].flow->lua(vm, allowed_hosts, highDetails, true);
lua_pushnumber(vm, num + 1);
lua_insert(vm, -2);
lua_settable(vm, -3);
if(++num >= (int)maxHits) break;
}
}
enablePurge(true);
free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
int NetworkInterface::getFlows(lua_State* vm,
AddressTree *allowed_hosts,
LocationPolicy location, Host *host,
Paginator *p) {
struct flowHostRetriever retriever;
int (*sorter)(const void *_a, const void *_b);
char sortColumn[32];
DetailsLevel highDetails;
if(p == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unable to return results with a NULL paginator");
return(-1);
}
highDetails = p->detailedResults() ? details_high : (location == location_local_only || (p && p->maxHits() != CONST_MAX_NUM_HITS)) ? details_high : details_normal;
retriever.pag = p;
retriever.host = host, retriever.location = location;
retriever.actNumEntries = 0, retriever.maxNumEntries = getFlowsHashSize(), retriever.allowed_hosts = allowed_hosts;
retriever.elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever.maxNumEntries);
if(retriever.elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
snprintf(sortColumn, sizeof(sortColumn), "%s", p->sortColumn());
if(!strcmp(sortColumn, "column_client")) retriever.sorter = column_client, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_vlan")) retriever.sorter = column_vlan, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_server")) retriever.sorter = column_server, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_proto_l4")) retriever.sorter = column_proto_l4, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_ndpi")) retriever.sorter = column_ndpi, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_duration")) retriever.sorter = column_duration, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_thpt")) retriever.sorter = column_thpt, sorter = numericSorter;
else if((!strcmp(sortColumn, "column_bytes")) || (!strcmp(sortColumn, "column_") /* default */)) retriever.sorter = column_bytes, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_info")) retriever.sorter = column_info, sorter = stringSorter;
else {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unknown sort column %s", sortColumn);
retriever.sorter = column_bytes, sorter = numericSorter;
}
/* ******************************* */
disablePurge(true);
walker(walker_flows, flow_search_walker, (void*)&retriever);
qsort(retriever.elems, retriever.actNumEntries, sizeof(struct flowHostRetrieveList), sorter);
lua_newtable(vm);
lua_push_int_table_entry(vm, "numFlows", retriever.actNumEntries);
lua_newtable(vm);
if(p->a2zSortOrder()) {
for(int i=p->toSkip(), num=0; i<(int)retriever.actNumEntries; i++) {
lua_newtable(vm);
retriever.elems[i].flow->lua(vm, allowed_hosts, highDetails, true);
lua_pushnumber(vm, num + 1);
lua_insert(vm, -2);
lua_settable(vm, -3);
if(++num >= (int)p->maxHits()) break;
}
} else {
for(int i=(retriever.actNumEntries-1-p->toSkip()), num=0; i>=0; i--) {
lua_newtable(vm);
retriever.elems[i].flow->lua(vm, allowed_hosts, highDetails, true);
lua_pushnumber(vm, num + 1);
lua_insert(vm, -2);
lua_settable(vm, -3);
if(++num >= (int)p->maxHits()) break;
}
}
lua_pushstring(vm, "flows");
lua_insert(vm, -2);
lua_settable(vm, -3);
enablePurge(true);
free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
int NetworkInterface::getLatestActivityHostsList(lua_State* vm, AddressTree *allowed_hosts) {
struct flowHostRetriever retriever;
memset(&retriever, 0, sizeof(retriever));
// there's not even the need to use the retriever or to sort results here
// we use the retriever just to leverage on the exising code.
retriever.allowed_hosts = allowed_hosts, retriever.location = location_all;
retriever.actNumEntries = 0, retriever.maxNumEntries = getHostsHashSize();
retriever.sorter = column_vlan; // just a placeholder, we don't care as we won't sort
retriever.elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever.maxNumEntries);
if(retriever.elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
disablePurge(false);
walker(walker_hosts, host_search_walker, (void*)&retriever);
lua_newtable(vm);
if(retriever.actNumEntries > 0) {
for(int i=0; i<(int)retriever.actNumEntries; i++) {
Host *h = retriever.elems[i].hostValue;
if(i < CONST_MAX_NUM_HITS)
h->lua(vm, NULL /* Already checked */,
false /* host details */,
false /* verbose */,
false /* return host */,
true /* as list element*/,
true /* exclude deserialized bytes */);
}
}
enablePurge(false);
free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
int NetworkInterface::sortHosts(struct flowHostRetriever *retriever,
AddressTree *allowed_hosts,
bool host_details,
LocationPolicy location,
char *countryFilter, char *mac_filter,
u_int16_t *vlan_id, char *osFilter,
u_int32_t *asnFilter, int16_t *networkFilter,
u_int16_t *pool_filter,
bool hostMacsOnly, char *sortColumn) {
u_int32_t maxHits;
int (*sorter)(const void *_a, const void *_b);
if(retriever == NULL)
return -1;
maxHits = getHostsHashSize();
if((maxHits > CONST_MAX_NUM_HITS) || (maxHits == 0))
maxHits = CONST_MAX_NUM_HITS;
memset(retriever, 0, sizeof(struct flowHostRetriever));
if(mac_filter) {
u_int8_t macAddr[6];
Utils::parseMac(macAddr, mac_filter);
retriever->mac = macs_hash->get(vlan_id ? *vlan_id : 0, (const u_int8_t*)macAddr);
}
retriever->allowed_hosts = allowed_hosts, retriever->location = location,
retriever->country = countryFilter, retriever->vlan_id = vlan_id,
retriever->osFilter = osFilter, retriever->asnFilter = asnFilter,
retriever->networkFilter = networkFilter, retriever->actNumEntries = 0,
retriever->poolFilter = pool_filter;
retriever->maxNumEntries = maxHits, retriever->hostMacsOnly = hostMacsOnly;
retriever->elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever->maxNumEntries);
if(retriever->elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
if((!strcmp(sortColumn, "column_ip")) || (!strcmp(sortColumn, "column_"))) retriever->sorter = column_ip, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_vlan")) retriever->sorter = column_vlan, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_alerts")) retriever->sorter = column_alerts, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_name")) retriever->sorter = column_name, sorter = stringSorter;
else if(!strcmp(sortColumn, "column_country")) retriever->sorter = column_country, sorter = stringSorter;
else if(!strcmp(sortColumn, "column_os")) retriever->sorter = column_os, sorter = stringSorter;
else if(!strcmp(sortColumn, "column_since")) retriever->sorter = column_since, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_asn")) retriever->sorter = column_asn, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_thpt")) retriever->sorter = column_thpt, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_num_flows")) retriever->sorter = column_num_flows, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_traffic")) retriever->sorter = column_traffic, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_local_network_id")) retriever->sorter = column_local_network_id, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_mac")) retriever->sorter = column_mac, sorter = numericSorter;
/* criteria (datatype sortField in ntop_typedefs.h / see also host_search_walker:NetworkInterface.cpp) */
else if(!strcmp(sortColumn, "column_uploaders")) retriever->sorter = column_uploaders, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_downloaders")) retriever->sorter = column_downloaders, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_unknowers")) retriever->sorter = column_unknowers, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_incomingflows")) retriever->sorter = column_incomingflows, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_outgoingflows")) retriever->sorter = column_outgoingflows, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_pool_id")) retriever->sorter = column_pool_id, sorter = numericSorter;
else {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unknown sort column %s", sortColumn);
retriever->sorter = column_traffic, sorter = numericSorter;
}
// make sure the caller has disabled the purge!!
walker(walker_hosts, host_search_walker, (void*)retriever);
qsort(retriever->elems, retriever->actNumEntries, sizeof(struct flowHostRetrieveList), sorter);
return(retriever->actNumEntries);
}
/* **************************************************** */
int NetworkInterface::sortMacs(struct flowHostRetriever *retriever,
u_int16_t vlan_id, bool skipSpecialMacs,
bool hostMacsOnly,
char *sortColumn) {
u_int32_t maxHits;
int (*sorter)(const void *_a, const void *_b);
if(retriever == NULL)
return -1;
maxHits = getMacsHashSize();
if((maxHits > CONST_MAX_NUM_HITS) || (maxHits == 0))
maxHits = CONST_MAX_NUM_HITS;
retriever->vlan_id = &vlan_id, retriever->skipSpecialMacs = skipSpecialMacs,
retriever->hostMacsOnly = hostMacsOnly, retriever->actNumEntries = 0,
retriever->maxNumEntries = maxHits,
retriever->elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever->maxNumEntries);
if(retriever->elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
if((!strcmp(sortColumn, "column_mac")) || (!strcmp(sortColumn, "column_"))) retriever->sorter = column_mac, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_vlan")) retriever->sorter = column_vlan, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_since")) retriever->sorter = column_since, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_thpt")) retriever->sorter = column_thpt, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_traffic")) retriever->sorter = column_traffic, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_hosts")) retriever->sorter = column_num_hosts, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_manufacturer")) retriever->sorter = column_manufacturer, sorter = stringSorter;
else ntop->getTrace()->traceEvent(TRACE_WARNING, "Unknown sort column %s", sortColumn), sorter = numericSorter;
// make sure the caller has disabled the purge!!
walker(walker_macs, mac_search_walker, (void*)retriever);
qsort(retriever->elems, retriever->actNumEntries, sizeof(struct flowHostRetrieveList), sorter);
return(retriever->actNumEntries);
}
/* **************************************************** */
int NetworkInterface::getActiveHostsList(lua_State* vm, AddressTree *allowed_hosts,
bool host_details, LocationPolicy location,
char *countryFilter, char *mac_filter,
u_int16_t *vlan_id, char *osFilter,
u_int32_t *asnFilter, int16_t *networkFilter,
u_int16_t *pool_filter,
char *sortColumn, u_int32_t maxHits,
u_int32_t toSkip, bool a2zSortOrder) {
struct flowHostRetriever retriever;
disablePurge(false);
if(sortHosts(&retriever, allowed_hosts, host_details, location,
countryFilter, mac_filter, vlan_id, osFilter,
asnFilter, networkFilter, pool_filter, true, sortColumn) < 0) {
enablePurge(false);
return -1;
}
lua_newtable(vm);
lua_push_int_table_entry(vm, "numHosts", retriever.actNumEntries);
lua_newtable(vm);
if(a2zSortOrder) {
for(int i = toSkip, num=0; i<(int)retriever.actNumEntries && num < (int)maxHits; i++, num++) {
Host *h = retriever.elems[i].hostValue;
h->lua(vm, NULL /* Already checked */, host_details, false, false, true, false);
}
} else {
for(int i = (retriever.actNumEntries-1-toSkip), num=0; i >= 0 && num < (int)maxHits; i--, num++) {
Host *h = retriever.elems[i].hostValue;
h->lua(vm, NULL /* Already checked */, host_details, false, false, true, false);
}
}
lua_pushstring(vm, "hosts");
lua_insert(vm, -2);
lua_settable(vm, -3);
enablePurge(false);
// it's up to us to clean sorted data
// make sure first to free elements in case a string sorter has been used
if(retriever.sorter == column_name
|| retriever.sorter == column_country
|| retriever.sorter == column_os) {
for(u_int i=0; i<retriever.maxNumEntries; i++)
if(retriever.elems[i].stringValue)
free(retriever.elems[i].stringValue);
}
// finally free the elements regardless of the sorted kind
if(retriever.elems) free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
int NetworkInterface::getActiveHostsGroup(lua_State* vm, AddressTree *allowed_hosts,
bool host_details, LocationPolicy location,
char *countryFilter,
u_int16_t *vlan_id, char *osFilter,
u_int32_t *asnFilter, int16_t *networkFilter,
u_int16_t *pool_filter,
bool local_macs, char *groupColumn) {
struct flowHostRetriever retriever;
Grouper *gper;
disablePurge(false);
// sort hosts according to the grouping criterion
if(sortHosts(&retriever, allowed_hosts, host_details, location,
countryFilter, NULL /* Mac */, vlan_id,
osFilter, asnFilter, networkFilter, pool_filter,
local_macs, groupColumn) < 0 ) {
enablePurge(false);
return -1;
}
// build a new grouper that will help in aggregating stats
if((gper = new(std::nothrow) Grouper(retriever.sorter)) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR,
"Unable to allocate memory for a Grouper.");
enablePurge(false);
return -1;
}
lua_newtable(vm);
for(int i=0; i<(int)retriever.actNumEntries; i++) {
Host *h = retriever.elems[i].hostValue;
if(h) {
if(gper->inGroup(h) == false) {
if(gper->getNumEntries() > 0)
gper->lua(vm);
gper->newGroup(h);
}
gper->incStats(h);
}
}
if(gper->getNumEntries() > 0)
gper->lua(vm);
delete gper;
gper = NULL;
enablePurge(false);
// it's up to us to clean sorted data
// make sure first to free elements in case a string sorter has been used
if((retriever.sorter == column_name)
|| (retriever.sorter == column_country)
|| (retriever.sorter == column_os)) {
for(u_int i=0; i<retriever.maxNumEntries; i++)
if(retriever.elems[i].stringValue)
free(retriever.elems[i].stringValue);
}
// finally free the elements regardless of the sorted kind
if(retriever.elems) free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
static bool flow_stats_walker(GenericHashEntry *h, void *user_data) {
struct active_flow_stats *stats = (struct active_flow_stats*)user_data;
Flow *flow = (Flow*)h;
stats->num_flows++,
stats->ndpi_bytes[flow->get_detected_protocol().protocol] += (u_int32_t)flow->get_bytes(),
stats->breeds_bytes[flow->get_protocol_breed()] += (u_int32_t)flow->get_bytes();
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::getFlowsStats(lua_State* vm) {
struct active_flow_stats stats;
memset(&stats, 0, sizeof(stats));
walker(walker_flows, flow_stats_walker, (void*)&stats);
lua_newtable(vm);
lua_push_int_table_entry(vm, "num_flows", stats.num_flows);
lua_newtable(vm);
for(int i=0; i<NDPI_MAX_SUPPORTED_PROTOCOLS+NDPI_MAX_NUM_CUSTOM_PROTOCOLS; i++) {
if(stats.ndpi_bytes[i] > 0)
lua_push_int_table_entry(vm,
ndpi_get_proto_name(get_ndpi_struct(), i),
stats.ndpi_bytes[i]);
}
lua_pushstring(vm, "protos");
lua_insert(vm, -2);
lua_settable(vm, -3);
lua_newtable(vm);
for(int i=0; i<NUM_BREEDS; i++) {
if(stats.breeds_bytes[i] > 0)
lua_push_int_table_entry(vm,
ndpi_get_proto_breed_name(get_ndpi_struct(),
(ndpi_protocol_breed_t)i),
stats.breeds_bytes[i]);
}
lua_pushstring(vm, "breeds");
lua_insert(vm, -2);
lua_settable(vm, -3);
}
/* **************************************************** */
void NetworkInterface::getNetworksStats(lua_State* vm) {
NetworkStats *network_stats;
u_int8_t num_local_networks = ntop->getNumLocalNetworks();
lua_newtable(vm);
for(u_int8_t network_id = 0; network_id < num_local_networks; network_id++) {
network_stats = getNetworkStats(network_id);
// do not add stats of networks that have not generated any traffic
if(!network_stats || !network_stats->trafficSeen())
continue;
lua_newtable(vm);
network_stats->lua(vm);
lua_push_int32_table_entry(vm, "network_id", network_id);
lua_pushstring(vm, ntop->getLocalNetworkName(network_id));
lua_insert(vm, -2);
lua_settable(vm, -3);
}
}
/* **************************************************** */
static bool host_activity_walker(GenericHashEntry *he, void *user_data) {
HostActivityRetriever * r = (HostActivityRetriever *)user_data;
Host *h = (Host*)he;
int i;
if(!h
|| !h->equal(&r->search)
|| (!h->get_user_activities()))
return(false); /* false = keep on walking */
r->found = true;
for(i=0; i<UserActivitiesN; i++)
r->counters[i] = *h->getActivityBytes((UserActivityID)i);
return true; /* found, stop walking */
}
/* **************************************************** */
void NetworkInterface::getLocalHostActivity(lua_State* vm, const char *host) {
HostActivityRetriever retriever(host);
int i;
disablePurge(false);
walker(walker_hosts, host_activity_walker, &retriever);
enablePurge(false);
if(retriever.found) {
lua_newtable(vm);
for(i=0; i<UserActivitiesN; i++) {
lua_newtable(vm);
lua_push_int_table_entry(vm, "up", retriever.counters[i].up);
lua_push_int_table_entry(vm, "down", retriever.counters[i].down);
lua_push_int_table_entry(vm, "background", retriever.counters[i].background);
lua_pushstring(vm, activity_names[i]);
lua_insert(vm, -2);
lua_settable(vm, -3);
}
} else
lua_pushnil(vm);
}
/* **************************************************** */
u_int NetworkInterface::purgeIdleFlows() {
if(!purge_idle_flows_hosts) return(0);
if(next_idle_flow_purge == 0) {
next_idle_flow_purge = last_pkt_rcvd + FLOW_PURGE_FREQUENCY;
return(0);
} else if(last_pkt_rcvd < next_idle_flow_purge)
return(0); /* Too early */
else {
/* Time to purge flows */
u_int n;
// ntop->getTrace()->traceEvent(TRACE_INFO, "Purging idle flows");
n = flows_hash->purgeIdle();
if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
// flush the queue
db->flush(true /* idle */);
}
next_idle_flow_purge = last_pkt_rcvd + FLOW_PURGE_FREQUENCY;
return(n);
}
}
/* **************************************************** */
u_int64_t NetworkInterface::getNumPackets() {
u_int64_t tot = ethStats.getNumPackets();
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumPackets();
return(tot);
};
/* **************************************************** */
u_int64_t NetworkInterface::getNumBytes() {
u_int64_t tot = ethStats.getNumBytes();
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumBytes();
return(tot);
}
/* **************************************************** */
u_int32_t NetworkInterface::getNumPacketDrops() {
u_int32_t tot = getNumDroppedPackets();
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumDroppedPackets();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::getNumFlows() {
u_int tot = flows_hash ? flows_hash->getNumEntries() : 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumFlows();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::getNumHosts() {
u_int tot = hosts_hash ? hosts_hash->getNumEntries() : 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumHosts();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::getNumHTTPHosts() {
u_int tot = hosts_hash ? hosts_hash->getNumHTTPEntries() : 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumHTTPHosts();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::getNumMacs() {
u_int tot = macs_hash ? macs_hash->getNumEntries() : 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumMacs();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::purgeIdleHostsMacs() {
if(!purge_idle_flows_hosts) return(0);
if(next_idle_host_purge == 0) {
next_idle_host_purge = last_pkt_rcvd + HOST_PURGE_FREQUENCY;
return(0);
} else if(last_pkt_rcvd < next_idle_host_purge)
return(0); /* Too early */
else {
/* Time to purge hosts */
u_int n;
// ntop->getTrace()->traceEvent(TRACE_INFO, "Purging idle hosts");
n = hosts_hash->purgeIdle() + macs_hash->purgeIdle();
next_idle_host_purge = last_pkt_rcvd + HOST_PURGE_FREQUENCY;
return(n);
}
}
/* *************************************** */
void NetworkInterface::getnDPIProtocols(lua_State *vm) {
int i;
lua_newtable(vm);
for(i=0; i<(int)ndpi_struct->ndpi_num_supported_protocols; i++) {
char buf[8];
snprintf(buf, sizeof(buf), "%d", i);
lua_push_str_table_entry(vm, ndpi_struct->proto_defaults[i].protoName, buf);
}
}
/* **************************************************** */
void NetworkInterface::getnDPIProtocols(lua_State *vm, ndpi_protocol_category_t filter) {
int i;
lua_newtable(vm);
for(i=0; i<(int)ndpi_struct->ndpi_num_supported_protocols; i++) {
char buf[8];
if (ndpi_struct->proto_defaults[i].protoCategory == filter) {
snprintf(buf, sizeof(buf), "%d", i);
lua_push_str_table_entry(vm, ndpi_struct->proto_defaults[i].protoName, buf);
}
}
}
/* **************************************************** */
#define NUM_TCP_STATES 4
/*
0 = RST
1 = SYN
2 = Established
3 = FIN
*/
static bool num_flows_state_walker(GenericHashEntry *node, void *user_data) {
Flow *flow = (Flow*)node;
u_int32_t *num_flows = (u_int32_t*)user_data;
switch(flow->getFlowState()) {
case flow_state_syn:
num_flows[1]++;
break;
case flow_state_established:
num_flows[2]++;
break;
case flow_state_rst:
num_flows[0]++;
break;
case flow_state_fin:
num_flows[3]++;
break;
default:
/* UDP... */
break;
}
return(false /* keep walking */);
}
/* *************************************** */
static bool num_flows_walker(GenericHashEntry *node, void *user_data) {
Flow *flow = (Flow*)node;
u_int32_t *num_flows = (u_int32_t*)user_data;
num_flows[flow->get_detected_protocol().protocol]++;
return(false /* keep walking */);
}
/* *************************************** */
void NetworkInterface::getFlowsStatus(lua_State *vm) {
u_int32_t num_flows[NUM_TCP_STATES] = { 0 };
walker(walker_flows, num_flows_state_walker, num_flows);
lua_push_int_table_entry(vm, "RST", num_flows[0]);
lua_push_int_table_entry(vm, "SYN", num_flows[1]);
lua_push_int_table_entry(vm, "Established", num_flows[2]);
lua_push_int_table_entry(vm, "FIN", num_flows[3]);
}
/* *************************************** */
void NetworkInterface::getnDPIFlowsCount(lua_State *vm) {
u_int32_t *num_flows;
num_flows = (u_int32_t*)calloc(ndpi_struct->ndpi_num_supported_protocols, sizeof(u_int32_t));
if(num_flows) {
walker(walker_flows, num_flows_walker, num_flows);
for(int i=0; i<(int)ndpi_struct->ndpi_num_supported_protocols; i++) {
if(num_flows[i] > 0)
lua_push_int_table_entry(vm, ndpi_struct->proto_defaults[i].protoName, num_flows[i]);
}
free(num_flows);
}
}
/* *************************************** */
void NetworkInterface::sumStats(TcpFlowStats *_tcpFlowStats,
EthStats *_ethStats,
LocalTrafficStats *_localStats,
nDPIStats *_ndpiStats,
PacketStats *_pktStats,
TcpPacketStats *_tcpPacketStats) {
tcpFlowStats.sum(_tcpFlowStats), ethStats.sum(_ethStats), localStats.sum(_localStats),
ndpiStats.sum(_ndpiStats), pktStats.sum(_pktStats), tcpPacketStats.sum(_tcpPacketStats);
}
/* *************************************** */
void NetworkInterface::lua(lua_State *vm) {
TcpFlowStats _tcpFlowStats;
EthStats _ethStats;
LocalTrafficStats _localStats;
nDPIStats _ndpiStats;
PacketStats _pktStats;
TcpPacketStats _tcpPacketStats;
lua_newtable(vm);
lua_push_str_table_entry(vm, "name", ifname);
lua_push_int_table_entry(vm, "scalingFactor", scalingFactor);
lua_push_int_table_entry(vm, "id", id);
lua_push_bool_table_entry(vm, "isView", isView()); /* View interface */
lua_push_int_table_entry(vm, "seen.last", getTimeLastPktRcvd());
lua_push_bool_table_entry(vm, "sprobe", get_sprobe_interface());
lua_push_bool_table_entry(vm, "inline", get_inline_interface());
lua_push_bool_table_entry(vm, "vlan", get_has_vlan_packets());
if(remoteIfname) lua_push_str_table_entry(vm, "remote.name", remoteIfname);
if(remoteIfIPaddr) lua_push_str_table_entry(vm, "remote.if_addr", remoteIfIPaddr);
if(remoteProbeIPaddr) lua_push_str_table_entry(vm, "probe.ip", remoteProbeIPaddr);
if(remoteProbePublicIPaddr) lua_push_str_table_entry(vm, "probe.public_ip", remoteProbePublicIPaddr);
lua_newtable(vm);
lua_push_int_table_entry(vm, "packets", getNumPackets());
lua_push_int_table_entry(vm, "bytes", getNumBytes());
lua_push_int_table_entry(vm, "flows", getNumFlows());
lua_push_int_table_entry(vm, "hosts", getNumHosts());
lua_push_int_table_entry(vm, "http_hosts", getNumHTTPHosts());
lua_push_int_table_entry(vm, "drops", getNumPacketDrops());
lua_push_int_table_entry(vm, "devices", numL2Devices);
/* even if the counter is global, we put it here on every interface
as we may decide to make an elasticsearch thread per interface.
*/
if(ntop->getPrefs()->do_dump_flows_on_es()) {
ntop->getElasticSearch()->lua(vm, false /* Overall */);
} else if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
if(db) db->lua(vm, false /* Overall */);
}
lua_pushstring(vm, "stats");
lua_insert(vm, -2);
lua_settable(vm, -3);
lua_newtable(vm);
lua_push_int_table_entry(vm, "packets", getNumPackets() - getCheckPointNumPackets());
lua_push_int_table_entry(vm, "bytes", getNumBytes() - getCheckPointNumBytes());
lua_push_int_table_entry(vm, "drops", getNumPacketDrops() - getCheckPointNumPacketDrops());
if(ntop->getPrefs()->do_dump_flows_on_es()) {
ntop->getElasticSearch()->lua(vm, true /* Since last checkpoint */);
} else if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
if(db) db->lua(vm, true /* Since last checkpoint */);
}
lua_pushstring(vm, "stats_since_reset");
lua_insert(vm, -2);
lua_settable(vm, -3);
lua_push_int_table_entry(vm, "remote_pps", last_remote_pps);
lua_push_int_table_entry(vm, "remote_bps", last_remote_bps);
lua_push_str_table_entry(vm, "type", (char*)get_type());
lua_push_int_table_entry(vm, "speed", ifSpeed);
lua_push_int_table_entry(vm, "mtu", ifMTU);
lua_push_int_table_entry(vm, "alertLevel", alertLevel);
lua_push_str_table_entry(vm, "ip_addresses", (char*)getLocalIPAddresses());
sumStats(&_tcpFlowStats, &_ethStats, &_localStats,
&_ndpiStats, &_pktStats, &_tcpPacketStats);
for(u_int8_t s = 0; s<numSubInterfaces; s++)
subInterfaces[s]->sumStats(&_tcpFlowStats, &_ethStats,
&_localStats, &_ndpiStats, &_pktStats, &_tcpPacketStats);
_tcpFlowStats.lua(vm, "tcpFlowStats");
_ethStats.lua(vm);
_localStats.lua(vm);
_ndpiStats.lua(this, vm);
_pktStats.lua(vm, "pktSizeDistribution");
_tcpPacketStats.lua(vm, "tcpPacketStats");
if(!isView()) {
if(pkt_dumper) pkt_dumper->lua(vm);
#ifdef NTOPNG_PRO
if(flow_profiles) flow_profiles->lua(vm);
#endif
}
}
/* **************************************************** */
void NetworkInterface::runHousekeepingTasks() {
/* NOTE NOTE NOTE
This task runs asynchronously with respect to ntopng
so if you need to allocate memory you must LOCK
Example HTTPStats::updateHTTPHostRequest() is called
by both this function and the main thread
*/
periodicStatsUpdate();
}
/* **************************************************** */
Mac* NetworkInterface::getMac(u_int8_t _mac[6], u_int16_t vlanId,
bool createIfNotPresent) {
Mac *ret = NULL;
if(_mac == NULL) return(NULL);
if(!isView())
ret = macs_hash->get(vlanId, _mac);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
if((ret = subInterfaces[s]->get_macs_hash()->get(vlanId, _mac)) != NULL)
break;
}
}
if((ret == NULL) && createIfNotPresent) {
try {
if((ret = new Mac(this, _mac, vlanId)) != NULL)
macs_hash->add(ret);
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
return(NULL);
}
}
return(ret);
}
/* **************************************************** */
Flow* NetworkInterface::findFlowByKey(u_int32_t key,
AddressTree *allowed_hosts) {
Flow *f;
if(!isView())
f = (Flow*)(flows_hash->findByKey(key));
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
f = (Flow*)subInterfaces[s]->get_flows_hash()->findByKey(key);
if(f) break;
}
}
if(f && (!f->match(allowed_hosts))) f = NULL;
return(f);
}
/* **************************************************** */
struct search_host_info {
lua_State *vm;
char *host_name_or_ip;
u_int num_matches;
AddressTree *allowed_hosts;
};
/* **************************************************** */
static bool hosts_search_walker(GenericHashEntry *h, void *user_data) {
Host *host = (Host*)h;
struct search_host_info *info = (struct search_host_info*)user_data;
if(host->addIfMatching(info->vm, info->allowed_hosts, info->host_name_or_ip))
info->num_matches++;
/* Stop after CONST_MAX_NUM_FIND_HITS matches */
return((info->num_matches > CONST_MAX_NUM_FIND_HITS) ? true /* stop */ : false /* keep walking */);
}
/* **************************************************** */
bool NetworkInterface::findHostsByName(lua_State* vm,
AddressTree *allowed_hosts,
char *key) {
struct search_host_info info;
info.vm = vm, info.host_name_or_ip = key, info.num_matches = 0, info.allowed_hosts = allowed_hosts;
lua_newtable(vm);
walker(walker_hosts, hosts_search_walker, (void*)&info);
return(info.num_matches > 0);
}
/* **************************************************** */
bool NetworkInterface::validInterface(char *name) {
if(name &&
(strstr(name, "PPP") /* Avoid to use the PPP interface */
|| strstr(name, "dialup") /* Avoid to use the dialup interface */
|| strstr(name, "ICSHARE") /* Avoid to use the internet sharing interface */
|| strstr(name, "NdisWan"))) { /* Avoid to use the internet sharing interface */
return(false);
}
return(true);
}
/* **************************************************** */
u_int NetworkInterface::printAvailableInterfaces(bool printHelp, int idx,
char *ifname, u_int ifname_len) {
char ebuf[256];
int numInterfaces = 0;
pcap_if_t *devpointer;
if(printHelp && help_printed)
return(0);
ebuf[0] = '\0';
if(pcap_findalldevs(&devpointer, ebuf) < 0) {
;
} else {
if(ifname == NULL) {
if(printHelp)
printf("Available interfaces (-i <interface index>):\n");
else if(!help_printed)
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"Available interfaces (-i <interface index>):");
}
for(int i = 0; devpointer != NULL; i++) {
if(validInterface(devpointer->description)) {
numInterfaces++;
if(ifname == NULL) {
if(printHelp) {
#ifdef WIN32
printf(" %d. %s\n"
"\t%s\n", numInterfaces,
devpointer->description ? devpointer->description : "",
devpointer->name);
#else
printf(" %d. %s\n", numInterfaces, devpointer->name);
#endif
} else if(!help_printed)
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%d. %s (%s)\n",
numInterfaces, devpointer->name,
devpointer->description ? devpointer->description : devpointer->name);
} else if(numInterfaces == idx) {
snprintf(ifname, ifname_len, "%s", devpointer->name);
break;
}
}
devpointer = devpointer->next;
} /* for */
} /* else */
if(numInterfaces == 0) {
#ifdef WIN32
ntop->getTrace()->traceEvent(TRACE_WARNING, "No interfaces available! This application cannot work");
ntop->getTrace()->traceEvent(TRACE_WARNING, "Make sure that winpcap is installed properly,");
ntop->getTrace()->traceEvent(TRACE_WARNING, "that you have administrative rights,");
ntop->getTrace()->traceEvent(TRACE_WARNING, "and that you have network interfaces installed.");
#else
ntop->getTrace()->traceEvent(TRACE_WARNING, "No interfaces available: are you superuser?");
#endif
}
help_printed = true;
return(numInterfaces);
}
/* **************************************************** */
bool NetworkInterface::isNumber(const char *str) {
while(*str) {
if(!isdigit(*str))
return(false);
str++;
}
return(true);
}
/* **************************************************** */
struct correlator_host_info {
lua_State* vm;
Host *h;
activity_bitmap x;
};
static bool correlator_walker(GenericHashEntry *node, void *user_data) {
Host *h = (Host*)node;
struct correlator_host_info *info = (struct correlator_host_info*)user_data;
if(h
// && h->isLocalHost() /* Consider only local hosts */
&& h->get_ip()
&& (h != info->h)) {
char buf[32], *name = h->get_ip()->print(buf, sizeof(buf));
activity_bitmap y;
double pearson;
h->getActivityStats()->extractPoints(&y);
pearson = Utils::pearsonValueCorrelation(&(info->x), &y);
/* ntop->getTrace()->traceEvent(TRACE_WARNING, "%s: %f", name, pearson); */
lua_push_float_table_entry(info->vm, name, (float)pearson);
}
return(false); /* false = keep on walking */
}
static bool similarity_walker(GenericHashEntry *node, void *user_data) {
Host *h = (Host*)node;
struct correlator_host_info *info = (struct correlator_host_info*)user_data;
if(h
// && h->isLocalHost() /* Consider only local hosts */
&& h->get_ip()
&& (h != info->h)) {
char buf[32], name[64];
if(h->get_vlan_id() == 0) {
sprintf(name, "%s",h->get_ip()->print(buf, sizeof(buf)));
} else {
sprintf(name, "%s@%d",h->get_ip()->print(buf, sizeof(buf)),h->get_vlan_id());
}
activity_bitmap y;
double jaccard;
h->getActivityStats()->extractPoints(&y);
jaccard = Utils::JaccardSimilarity(&(info->x), &y);
/* ntop->getTrace()->traceEvent(TRACE_WARNING, "%s: %f", name, pearson); */
lua_push_float_table_entry(info->vm, name, (float)jaccard);
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
bool NetworkInterface::correlateHostActivity(lua_State* vm,
AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
Host *h = getHost(host_ip, vlan_id);
if(h) {
struct correlator_host_info info;
memset(&info, 0, sizeof(info));
info.vm = vm, info.h = h;
h->getActivityStats()->extractPoints(&info.x);
walker(walker_hosts, correlator_walker, &info);
return(true);
} else
return(false);
}
/* **************************************************** */
bool NetworkInterface::similarHostActivity(lua_State* vm,
AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
Host *h = getHost(host_ip, vlan_id);
if(h) {
struct correlator_host_info info;
memset(&info, 0, sizeof(info));
info.vm = vm, info.h = h;
h->getActivityStats()->extractPoints(&info.x);
walker(walker_hosts, similarity_walker, &info);
return(true);
} else
return(false);
}
/* **************************************************** */
struct user_flows {
lua_State* vm;
char *username;
};
static bool userfinder_walker(GenericHashEntry *node, void *user_data) {
Flow *f = (Flow*)node;
struct user_flows *info = (struct user_flows*)user_data;
char *user = f->get_username(true);
if(user == NULL)
user = f->get_username(false);
if(user && (strcmp(user, info->username) == 0)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::findUserFlows(lua_State *vm, char *username) {
struct user_flows u;
u.vm = vm, u.username = username;
walker(walker_flows, userfinder_walker, &u);
}
/* **************************************************** */
struct proc_name_flows {
lua_State* vm;
char *proc_name;
};
static bool proc_name_finder_walker(GenericHashEntry *node, void *user_data) {
Flow *f = (Flow*)node;
struct proc_name_flows *info = (struct proc_name_flows*)user_data;
char *name = f->get_proc_name(true);
if(name && (strcmp(name, info->proc_name) == 0)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
} else {
name = f->get_proc_name(false);
if(name && (strcmp(name, info->proc_name) == 0)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
}
}
return(false); /* false = keep on walking */
}
void NetworkInterface::findProcNameFlows(lua_State *vm, char *proc_name) {
struct proc_name_flows u;
u.vm = vm, u.proc_name = proc_name;
walker(walker_flows, proc_name_finder_walker, &u);
}
/* **************************************************** */
struct pid_flows {
lua_State* vm;
u_int32_t pid;
};
static bool pidfinder_walker(GenericHashEntry *node, void *pid_data) {
Flow *f = (Flow*)node;
struct pid_flows *info = (struct pid_flows*)pid_data;
if((f->getPid(true) == info->pid) || (f->getPid(false) == info->pid)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
}
return(false); /* false = keep on walking */
}
/* **************************************** */
void NetworkInterface::findPidFlows(lua_State *vm, u_int32_t pid) {
struct pid_flows u;
u.vm = vm, u.pid = pid;
walker(walker_flows, pidfinder_walker, &u);
}
/* **************************************** */
static bool father_pidfinder_walker(GenericHashEntry *node, void *father_pid_data) {
Flow *f = (Flow*)node;
struct pid_flows *info = (struct pid_flows*)father_pid_data;
if((f->getFatherPid(true) == info->pid) || (f->getFatherPid(false) == info->pid)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
}
return(false); /* false = keep on walking */
}
/* **************************************** */
void NetworkInterface::findFatherPidFlows(lua_State *vm, u_int32_t father_pid) {
struct pid_flows u;
u.vm = vm, u.pid = father_pid;
walker(walker_flows, father_pidfinder_walker, &u);
}
/* **************************************** */
struct virtual_host_valk_info {
lua_State *vm;
char *key;
u_int32_t num;
};
static bool virtual_http_hosts_walker(GenericHashEntry *node, void *data) {
Host *h = (Host*)node;
struct virtual_host_valk_info *info = (struct virtual_host_valk_info*)data;
HTTPstats *s = h->getHTTPstats();
if(s)
info->num += s->luaVirtualHosts(info->vm, info->key, h);
return(false); /* false = keep on walking */
}
/* **************************************** */
void NetworkInterface::listHTTPHosts(lua_State *vm, char *key) {
struct virtual_host_valk_info info;
lua_newtable(vm);
info.vm = vm, info.key = key, info.num = 0;
walker(walker_hosts, virtual_http_hosts_walker, &info);
}
/* **************************************** */
bool NetworkInterface::isInterfaceUp(char *name) {
#ifdef WIN32
return(true);
#else
struct ifreq ifr;
int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if(strlen(name) >= sizeof(ifr.ifr_name))
return(false);
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, name);
if(ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
closesocket(sock);
return(false);
}
closesocket(sock);
return(!!(ifr.ifr_flags & IFF_UP));
#endif
}
/* **************************************** */
void NetworkInterface::addAllAvailableInterfaces() {
char ebuf[256] = { '\0' };
pcap_if_t *devpointer;
if(pcap_findalldevs(&devpointer, ebuf) < 0) {
;
} else {
for(int i = 0; devpointer != 0; i++) {
if(validInterface(devpointer->description)
&& isInterfaceUp(devpointer->name)) {
ntop->getPrefs()->add_network_interface(devpointer->name,
devpointer->description);
} else
ntop->getTrace()->traceEvent(TRACE_INFO, "Interface [%s][%s] not valid or down: discarded",
devpointer->name, devpointer->description);
devpointer = devpointer->next;
} /* for */
pcap_freealldevs(devpointer);
}
}
/* **************************************** */
#ifdef NTOPNG_PRO
void NetworkInterface::refreshL7Rules() {
if(ntop->getPro()->has_valid_license() && policer)
policer->refreshL7Rules();
}
#endif
/* **************************************** */
#ifdef NTOPNG_PRO
void NetworkInterface::refreshShapers() {
if(ntop->getPro()->has_valid_license() && policer)
policer->refreshShapers();
}
#endif
/* **************************************** */
void NetworkInterface::addInterfaceAddress(char *addr) {
if(ip_addresses.size() == 0)
ip_addresses = addr;
else {
string s = addr;
ip_addresses = ip_addresses + "," + s;
}
}
/* **************************************** */
void NetworkInterface::allocateNetworkStats() {
u_int8_t numNetworks = ntop->getNumLocalNetworks();
try {
networkStats = new NetworkStats[numNetworks];
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
networkStats = NULL;
}
}
/* **************************************** */
NetworkStats* NetworkInterface::getNetworkStats(u_int8_t networkId) {
if((networkStats == NULL) || (networkId >= ntop->getNumLocalNetworks()))
return(NULL);
else
return(&networkStats[networkId]);
}
/* **************************************** */
void NetworkInterface::updateSecondTraffic(time_t when) {
u_int64_t bytes = ethStats.getNumBytes();
u_int16_t sec = when % 60;
if(sec == 0) {
/* Beginning of a new minute */
memcpy(lastMinuteTraffic, currentMinuteTraffic, sizeof(currentMinuteTraffic));
resetSecondTraffic();
}
currentMinuteTraffic[sec] = max_val(0, bytes-lastSecTraffic);
lastSecTraffic = bytes;
};
/* **************************************** */
void NetworkInterface::checkPointCounters(bool drops_only) {
if(!drops_only) {
checkpointPktCount = getNumPackets(),
checkpointBytesCount = getNumBytes();
}
checkpointPktDropCount = getNumPacketDrops();
if(ntop->getPrefs()->do_dump_flows_on_es()) {
ntop->getElasticSearch()->checkPointCounters(drops_only);
} else if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
if(db) db->checkPointCounters(drops_only);
}
}
/* **************************************************** */
u_int64_t NetworkInterface::getCheckPointNumPackets() {
u_int64_t tot = checkpointPktCount;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getCheckPointNumPackets();
return(tot);
};
/* **************************************************** */
u_int64_t NetworkInterface::getCheckPointNumBytes() {
u_int64_t tot = checkpointBytesCount;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getCheckPointNumBytes();
return(tot);
}
/* **************************************************** */
u_int32_t NetworkInterface::getCheckPointNumPacketDrops() {
u_int32_t tot = checkpointPktDropCount;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getCheckPointNumPacketDrops();
return(tot);
};
/* **************************************** */
void NetworkInterface::setRemoteStats(char *name, char *address, u_int32_t speedMbit,
char *remoteProbeAddress, char *remoteProbePublicAddress,
u_int64_t remBytes, u_int64_t remPkts,
u_int32_t remTime, u_int32_t last_pps, u_int32_t last_bps) {
if(name) setRemoteIfname(name);
if(address) setRemoteIfIPaddr(address);
if(remoteProbeAddress) setRemoteProbeAddr(remoteProbeAddress);
if(remoteProbePublicAddress) setRemoteProbePublicAddr(remoteProbePublicAddress);
ifSpeed = speedMbit, last_pkt_rcvd_remote = remTime, last_remote_pps = last_pps, last_remote_bps = last_bps;
if((zmq_initial_pkts == 0) /* ntopng has been restarted */
|| (remBytes < zmq_initial_bytes) /* nProbe has been restarted */
) {
/* Start over */
zmq_initial_bytes = remBytes, zmq_initial_pkts = remPkts;
} else {
remBytes -= zmq_initial_bytes, remPkts -= zmq_initial_pkts;
ntop->getTrace()->traceEvent(TRACE_INFO, "[%s][bytes=%u/%u (%d)][pkts=%u/%u (%d)]",
ifname, remBytes, ethStats.getNumBytes(), remBytes-ethStats.getNumBytes(),
remPkts, ethStats.getNumPackets(), remPkts-ethStats.getNumPackets());
/*
* Don't override ethStats here, these stats are properly updated
* inside NetworkInterface::processFlow for ZMQ interfaces.
* Overriding values here may cause glitches and non-strictly-increasing counters
* yielding negative rates.
ethStats.setNumBytes(remBytes), ethStats.setNumPackets(remPkts);
*
*/
}
}
/* **************************************** */
void NetworkInterface::processInterfaceStats(sFlowInterfaceStats *stats) {
if(interfaceStats == NULL)
interfaceStats = new InterfaceStatsHash(NUM_IFACE_STATS_HASH);
if(interfaceStats) {
char a[64];
ntop->getTrace()->traceEvent(TRACE_INFO, "[%s][ifIndex=%u]",
Utils::intoaV4(stats->deviceIP, a, sizeof(a)),
stats->ifIndex);
interfaceStats->set(stats->deviceIP, stats->ifIndex, stats);
}
}
/* **************************************** */
ndpi_protocol_category_t NetworkInterface::get_ndpi_proto_category(u_int protoid) {
ndpi_protocol proto;
proto.protocol = NDPI_PROTOCOL_UNKNOWN;
proto.master_protocol = protoid;
return get_ndpi_proto_category(proto);
}
/* **************************************** */
static int lua_flow_get_ndpi_category(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushstring(vm, ndpi_category_str(f->get_detected_protocol_category()));
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_ndpi_proto(lua_State* vm) {
Flow *f;
char buf[32];
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushstring(vm, f->get_detected_protocol_name(buf, sizeof(buf)));
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_ndpi_proto_id(lua_State* vm) {
Flow *f;
ndpi_protocol p;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR); else p = f->get_detected_protocol();
lua_pushnumber(vm, (p.protocol != NDPI_PROTOCOL_UNKNOWN) ? p.protocol : p.master_protocol);
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_first_seen(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushnumber(vm, f->get_first_seen());
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_last_seen(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushnumber(vm, f->get_last_seen());
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_server_name(lua_State* vm) {
Flow *f;
char buf[64];
const char *srv;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
srv = f->getFlowServerInfo();
if(!srv && f->get_srv_host())
srv = f->get_srv_host()->get_name(buf, sizeof(buf), false);
if(!srv) srv = "";
lua_pushstring(vm, srv);
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_http_url(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushstring(vm, f->getHTTPURL());
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_http_content_type(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushstring(vm, f->getHTTPContentType());
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_dump(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
f->lua(vm, NULL, details_high, false);
return(CONST_LUA_OK);
}
/* **************************************** */
/* -1 on error */
static int lua_flow_get_profile_id(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
UserActivityID uaid;
lua_pushnumber(vm, f->getActivityId(&uaid) ? uaid : -1);
return(CONST_LUA_OK);
}
/* ****************************************** */
/* -1 on error */
static int lua_flow_get_activity_filter_id(lua_State* vm) {
Flow * f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
ActivityFilterID fid;
lua_pushnumber(vm, f->getActivityFilterId(&fid) ? fid : -1);
return(CONST_LUA_OK);
}
/* ****************************************** */
/*
* lua params:
* activityID - ID of the activity to apply for filtered bytes
* filterID - ID of the filter to apply to the flow for activity recording
* *parametes - parameters to pass to the filter - See below
*
* SMA/WMA filter params:
* edge - moving average edge to trigger activity
* minsamples - minimum number of samples for activity detection
* WMA filter params:
* timescale - division scale for each second difference from previous packet. 0 to disable
* aggrsecs - max packet seconds difference to aggregate. 0 to disable
* SMA filter params:
* timebound - expected time tick in milliseconds between activity packets. 0 to disable
* sustain - time, in milliseconds, between packets to be considered activity. 0 to disable
*
* CommandSequence filter params:
* mustwait - if true, activity trigger requires server to wait after command request
* minbytes - minimum number of bytes to trigger activity
* maxinterval - maximum milliseconds difference between interactions
* mincommands - minimum number of commands seen in the flow to trigger activity
* minflips - minimum number of server interactions to trigger activity
*
* Web filter params:
* numsamples - number of packets to process for detection
* minbytes - minimum number of bytes to trigger activity
* maxinterval - maximum milliseconds difference between packets
* serverdominant - if true, server bytes must be more then client bytes
* forceWebProfile - if true, force 'web' profile for unknown and 'other' flow profiles
*
* Ratio filter params:
* numsamples - number of packets to process for detection
* minbytes - minimum number of bytes to trigger activity
* clisrv_ratio - minimum (positive ? client/server : server/client) bytes to trigger activity
*
* Interflow filter params:
* minflows - minimum number of concurrent flows. -1 to disable [1]
* minpkts - minimum number of cumulative packets in concurrent flows to trigger activity
* minduration - minimum (max duration of cumulative packets) in concurrent flows. -1 to disable [1]
* sslonly - if true, only SSL traffic can trigger activity
* NOTE: At least one of [1] must be satisfied to trigger activity
*/
static int lua_flow_set_activity_filter(lua_State* vm) {
UserActivityID activityID;
ActivityFilterID filterID;
Flow *f;
activity_filter_config config = {};
u_int8_t params = 0;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, params+1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
activityID = (UserActivityID)lua_tonumber(vm, ++params);
if(activityID >= UserActivitiesN) return(CONST_LUA_ERROR);
if(lua_type(vm, params+1) == LUA_TNUMBER)
filterID = (ActivityFilterID)lua_tonumber(vm, ++params);
else
return(CONST_LUA_ERROR);
// filter specific parameters
switch(filterID) {
case activity_filter_all:
if(lua_type(vm, params+1) == LUA_TBOOLEAN) {
config.all.pass = lua_toboolean(vm, ++params);
}
switch (params) {
case 2+0: config.all.pass = true;
}
break;
case activity_filter_web:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.web.numsamples = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.web.minbytes = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.web.maxinterval = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TBOOLEAN) {
config.web.forceWebProfile = lua_toboolean(vm, ++params);
if(lua_type(vm, params+1) == LUA_TBOOLEAN)
config.web.serverdominant = lua_toboolean(vm, ++params);
}
}
}
}
// defaults
switch (params) {
case 2+0: config.web.numsamples = 4;
case 2+1: config.web.minbytes = 0;
case 2+2: config.web.maxinterval = 2000;
case 2+3: config.web.forceWebProfile = true;
case 2+4: config.web.serverdominant = true;
}
break;
case activity_filter_ratio:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.ratio.numsamples = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.ratio.minbytes = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER)
config.ratio.clisrv_ratio = lua_tonumber(vm, ++params);
}
}
// defaults
switch (params) {
case 2+0: config.ratio.numsamples = 4;
case 2+1: config.ratio.minbytes = 0;
case 2+2: config.ratio.clisrv_ratio = -1.f;
}
break;
case activity_filter_interflow:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.interflow.minflows = min((int)lua_tonumber(vm, ++params), INTER_FLOW_ACTIVITY_SLOTS);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.interflow.minpkts = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.interflow.minduration = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TBOOLEAN)
config.interflow.sslonly = lua_toboolean(vm, ++params);
}
}
}
// defaults
switch (params) {
case 2+0: config.interflow.minflows = INTER_FLOW_ACTIVITY_SLOTS;
case 2+1: config.interflow.minpkts = 200;
case 2+2: config.interflow.minduration = -1;
case 2+3: config.interflow.sslonly = false;
}
break;
case activity_filter_metrics_test:
break;
case activity_filter_sma:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.sma.edge = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.sma.minsamples = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.sma.timebound = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER)
config.sma.sustain = lua_tonumber(vm, ++params);
}
}
}
// defaults
switch (params) {
case 2+0: config.sma.edge = 0;
case 2+1: config.sma.minsamples = ACTIVITY_FILTER_WMA_SAMPLES;
case 2+2: config.sma.timebound = 2000;
case 2+3: config.sma.sustain = 1000;
}
break;
case activity_filter_wma:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.wma.edge = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.wma.minsamples = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.wma.timescale = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER)
config.wma.aggrsecs = lua_tonumber(vm, ++params);
}
}
}
// defaults
switch (params) {
case 2+0: config.wma.edge = 0;
case 2+1: config.wma.minsamples = ACTIVITY_FILTER_WMA_SAMPLES;
case 2+2: config.wma.timescale = 1.f;
case 2+3: config.wma.aggrsecs = 0;
}
break;
case activity_filter_command_sequence:
if(lua_type(vm, params+1) == LUA_TBOOLEAN) {
config.command_sequence.mustwait = lua_toboolean(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.command_sequence.minbytes = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.command_sequence.maxinterval = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.command_sequence.mincommands = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER)
config.command_sequence.minflips = lua_tonumber(vm, ++params);
}
}
}
}
switch (params) {
case 2+0: config.command_sequence.mustwait = false;
case 2+1: config.command_sequence.minbytes = 0;
case 2+2: config.command_sequence.maxinterval = 3000;
case 2+3: config.command_sequence.mincommands = 1;
case 2+4: config.command_sequence.minflips = 1;
}
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Invalid activity filter (%d)", filterID);
return (CONST_LUA_ERROR);
}
ntop->getTrace()->traceEvent(TRACE_DEBUG, "Flow %p setActivityFilter: filter=%d activity=%d", f, filterID, activityID);
f->setActivityFilter(filterID, &config);
f->setActivityId(activityID);
return(CONST_LUA_OK);
}
/* ****************************************** */
static const luaL_Reg flow_reg[] = {
{ "getNdpiCategory", lua_flow_get_ndpi_category },
{ "getNdpiProto", lua_flow_get_ndpi_proto },
{ "getNdpiProtoId", lua_flow_get_ndpi_proto_id },
{ "getFirstSeen", lua_flow_get_first_seen },
{ "getLastSeen", lua_flow_get_last_seen },
{ "getServerName", lua_flow_get_server_name },
{ "getHTTPUrl", lua_flow_get_http_url },
{ "getHTTPContentType",lua_flow_get_http_content_type },
{ "dump", lua_flow_dump },
{ "setActivityFilter", lua_flow_set_activity_filter },
{ "getProfileId", lua_flow_get_profile_id },
{ "getActivityFilterId", lua_flow_get_activity_filter_id },
{ NULL, NULL }
};
ntop_class_reg ntop_lua_reg[] = {
{ "flow", flow_reg },
{NULL, NULL}
};
lua_State* NetworkInterface::initLuaInterpreter(const char *lua_file) {
static const luaL_Reg _meta[] = { { NULL, NULL } };
int i;
char script_path[256];
lua_State *L;
L = luaL_newstate();
if(!L) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "Unable to initialize lua interpreter");
return(NULL);
}
snprintf(script_path, sizeof(script_path), "%s/%s",
ntop->getPrefs()->get_callbacks_dir(),
lua_file);
/* ******************************************** */
luaL_openlibs(L); /* Load base libraries */
for(i=0; ntop_lua_reg[i].class_name != NULL; i++) {
int lib_id, meta_id;
/* newclass = {} */
lua_createtable(L, 0, 0);
lib_id = lua_gettop(L);
/* metatable = {} */
luaL_newmetatable(L, ntop_lua_reg[i].class_name);
meta_id = lua_gettop(L);
luaL_register(L, NULL, _meta);
/* metatable.__index = class_methods */
lua_newtable(L), luaL_register(L, NULL, ntop_lua_reg[i].class_methods);
lua_setfield(L, meta_id, "__index");
/* class.__metatable = metatable */
lua_setmetatable(L, lib_id);
/* _G["Foo"] = newclass */
lua_setglobal(L, ntop_lua_reg[i].class_name);
}
lua_register(L, "print", ntop_lua_cli_print);
// Activity profiles - see ntop_typedefs.h
lua_newtable(L);
for(int i=0; i<UserActivitiesN; i++)
lua_push_int_table_entry(L, activity_names[i], i);
lua_setglobal(L, CONST_USERACTIVITY_PROFILES);
// Activity filters
lua_newtable(L);
lua_push_int_table_entry(L, "All", activity_filter_all);
lua_push_int_table_entry(L, "SMA", activity_filter_sma);
lua_push_int_table_entry(L, "WMA", activity_filter_wma);
lua_push_int_table_entry(L, "CommandSequence", activity_filter_command_sequence);
lua_push_int_table_entry(L, "Web", activity_filter_web);
lua_push_int_table_entry(L, "Ratio", activity_filter_ratio);
lua_push_int_table_entry(L, "Interflow", activity_filter_interflow);
lua_push_int_table_entry(L, "Metrics", activity_filter_metrics_test);
lua_setglobal(L, CONST_USERACTIVITY_FILTERS);
if(luaL_loadfile(L, script_path) || lua_pcall(L, 0, 0, 0)) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Cannot run lua file %s: %s",
script_path, lua_tostring(L, -1));
lua_close(L);
L = NULL;
} else {
ntop->getTrace()->traceEvent(TRACE_INFO, "Successfully interpreted %s", script_path);
lua_pushlightuserdata(L, NULL);
lua_setglobal(L, CONST_USERACTIVITY_FLOW);
}
return(L);
}
/* **************************************** */
void NetworkInterface::termLuaInterpreter() {
if(L_flow_create_delete_ndpi) { lua_close(L_flow_create_delete_ndpi); L_flow_create_delete_ndpi = NULL; }
if(L_flow_update) { lua_close(L_flow_update); L_flow_update = NULL; }
}
/* **************************************** */
int NetworkInterface::luaEvalFlow(Flow *f, const LuaCallback cb) {
int rc;
lua_State *L;
const char *luaFunction;
return(0); // FIX
if(reloadLuaInterpreter) {
if(L_flow_create_delete_ndpi || L_flow_update) termLuaInterpreter();
L_flow_create_delete_ndpi = initLuaInterpreter(CONST_FLOWACTIVITY_SCRIPT);
L_flow_update = initLuaInterpreter(CONST_FLOWACTIVITY_SCRIPT);
reloadLuaInterpreter = false;
}
switch(cb) {
case callback_flow_create:
L = L_flow_create_delete_ndpi, luaFunction = CONST_LUA_FLOW_CREATE;
break;
case callback_flow_delete:
L = L_flow_create_delete_ndpi, luaFunction = CONST_LUA_FLOW_DELETE;
break;
case callback_flow_update:
L = L_flow_update, luaFunction = CONST_LUA_FLOW_UPDATE;
break;
case callback_flow_proto_callback:
L = L_flow_create_delete_ndpi, luaFunction = CONST_LUA_FLOW_NDPI_DETECT;
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Invalid lua callback (%d)", cb);
return(-1);
}
if(L == NULL)
return(-2);
lua_settop(L, 0); /* Reset stack */
lua_pushlightuserdata(L, f);
lua_setglobal(L, CONST_USERACTIVITY_FLOW);
lua_getglobal(L, luaFunction); /* function to be called */
if((rc = lua_pcall(L, 0 /* 0 parameters */, 0 /* no return values */, 0)) != 0) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Error while executing %s [rc=%d][%s]", luaFunction, rc, lua_tostring(L, -1));
}
return(rc);
}
/* **************************************** */
int NetworkInterface::getActiveMacList(lua_State* vm, u_int16_t vlan_id,
bool skipSpecialMacs,
bool hostMacsOnly,
char *sortColumn, u_int32_t maxHits,
u_int32_t toSkip, bool a2zSortOrder) {
struct flowHostRetriever retriever;
bool show_details = true;
disablePurge(false);
if(sortMacs(&retriever, vlan_id, skipSpecialMacs, hostMacsOnly, sortColumn) < 0) {
enablePurge(false);
return -1;
}
lua_newtable(vm);
lua_push_int_table_entry(vm, "numMacs", retriever.actNumEntries);
lua_newtable(vm);
if(a2zSortOrder) {
for(int i = toSkip, num=0; i<(int)retriever.actNumEntries && num < (int)maxHits; i++, num++) {
Mac *m = retriever.elems[i].macValue;
m->lua(vm, show_details, false);
lua_rawseti(vm, -2, num + 1); /* Must use integer keys to preserve and iterate inorder with ipairs */
}
} else {
for(int i = (retriever.actNumEntries-1-toSkip), num=0; i >= 0 && num < (int)maxHits; i--, num++) {
Mac *m = retriever.elems[i].macValue;
m->lua(vm, show_details, false);
lua_rawseti(vm, -2, num + 1);
}
}
lua_pushstring(vm, "macs");
lua_insert(vm, -2);
lua_settable(vm, -3);
enablePurge(false);
// finally free the elements regardless of the sorted kind
if(retriever.elems) free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************** */
bool NetworkInterface::getMacInfo(lua_State* vm, char *mac, u_int16_t vlan_id) {
struct mac_find_info info;
memset(&info, 0, sizeof(info));
Utils::parseMac(info.mac, mac), info.vlan_id = vlan_id;
walker(walker_macs, find_mac_by_name, (void*)&info);
if(info.m) {
info.m->lua(vm, true, false);
return(true);
} else
return(false);
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_3266_1 |
crossvul-cpp_data_bad_3266_1 | /*
*
* (C) 2013-17 - ntop.org
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include "ntop_includes.h"
#ifdef __APPLE__
#include <uuid/uuid.h>
#endif
/* UserActivityStats.cpp */
extern const char* activity_names[];
/* Lua.cpp */
extern int ntop_lua_cli_print(lua_State* vm);
extern int ntop_lua_check(lua_State* vm, const char* func, int pos, int expected_type);
static bool help_printed = false;
/* **************************************************** */
/* Method used for collateral activities */
NetworkInterface::NetworkInterface() { init(); }
/* **************************************************** */
NetworkInterface::NetworkInterface(const char *name,
const char *custom_interface_type) {
NDPI_PROTOCOL_BITMASK all;
char _ifname[64];
bool isViewInterface = (strncmp(name, "view:", 5) == 0) ? 1 : 0; /* We need to do it as isView() is not yet initialized */
customIftype = custom_interface_type, flowHashingMode = flowhashing_none;
init();
#ifdef WIN32
if(name == NULL) name = "1"; /* First available interface */
#endif
scalingFactor = 1, remoteIfname = remoteIfIPaddr = remoteProbeIPaddr = remoteProbePublicIPaddr = NULL;
if(strcmp(name, "-") == 0) name = "stdin";
if(strcmp(name, "-") == 0) name = "stdin";
if(ntop->getRedis())
id = Utils::ifname2id(name);
else
id = -1;
purge_idle_flows_hosts = true;
if(name == NULL) {
char pcap_error_buffer[PCAP_ERRBUF_SIZE];
if(!help_printed)
ntop->getTrace()->traceEvent(TRACE_WARNING, "No capture interface specified");
printAvailableInterfaces(false, 0, NULL, 0);
name = pcap_lookupdev(pcap_error_buffer);
if(name == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR,
"Unable to locate default interface (%s)\n",
pcap_error_buffer);
exit(0);
}
} else {
if(isNumber(name)) {
/* We need to convert this numeric index into an interface name */
int id = atoi(name);
_ifname[0] = '\0';
printAvailableInterfaces(false, id, _ifname, sizeof(_ifname));
if(_ifname[0] == '\0') {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unable to locate interface Id %d", id);
printAvailableInterfaces(false, 0, NULL, 0);
exit(0);
}
name = _ifname;
}
}
pkt_dumper_tap = NULL, lastSecUpdate = 0;
ifname = strdup(name);
if(id >= 0) {
u_int32_t num_hashes;
ndpi_port_range d_port[MAX_DEFAULT_PORTS];
u_int16_t no_master[2] = { NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO };
num_hashes = max_val(4096, ntop->getPrefs()->get_max_num_flows()/4);
flows_hash = new FlowHash(this, num_hashes, ntop->getPrefs()->get_max_num_flows());
num_hashes = max_val(4096, ntop->getPrefs()->get_max_num_hosts()/4);
hosts_hash = new HostHash(this, num_hashes, ntop->getPrefs()->get_max_num_hosts());
macs_hash = new MacHash(this, 4, ntop->getPrefs()->get_max_num_hosts());
// init global detection structure
ndpi_struct = ndpi_init_detection_module();
if(ndpi_struct == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "Global structure initialization failed");
exit(-1);
}
if(ntop->getCustomnDPIProtos() != NULL)
ndpi_load_protocols_file(ndpi_struct, ntop->getCustomnDPIProtos());
ndpi_struct->http_dont_dissect_response = 1;
memset(d_port, 0, sizeof(d_port));
ndpi_set_proto_defaults(ndpi_struct, NDPI_PROTOCOL_UNRATED, NTOPNG_NDPI_OS_PROTO_ID,
no_master, no_master,
(char*)"Operating System",
NDPI_PROTOCOL_CATEGORY_SYSTEM,
d_port, d_port);
// enable all protocols
NDPI_BITMASK_SET_ALL(all);
ndpi_set_protocol_detection_bitmask2(ndpi_struct, &all);
last_pkt_rcvd = last_pkt_rcvd_remote = 0, pollLoopCreated = false, bridge_interface = false;
next_idle_flow_purge = next_idle_host_purge = 0;
cpu_affinity = -1 /* no affinity */, has_vlan_packets = false, pkt_dumper = NULL;
if(ntop->getPrefs()->are_taps_enabled())
pkt_dumper_tap = new PacketDumperTuntap(this);
running = false, sprobe_interface = false, inline_interface = false, db = NULL;
if((!isViewInterface) && (ntop->getPrefs()->do_dump_flows_on_mysql())) {
#ifdef NTOPNG_PRO
if(ntop->getPrefs()->is_enterprise_edition()) db = new BatchedMySQLDB(this);
#endif
if(db == NULL)
db = new MySQLDB(this);
if(!db) throw "Not enough memory";
}
checkIdle();
ifSpeed = Utils::getMaxIfSpeed(name);
ifMTU = Utils::getIfMTU(name), mtuWarningShown = false;
} else {
flows_hash = NULL, hosts_hash = NULL;
ndpi_struct = NULL, db = NULL, ifSpeed = 0;
pkt_dumper = NULL, pkt_dumper_tap = NULL;
}
networkStats = NULL;
#ifdef NTOPNG_PRO
policer = NULL; /* possibly instantiated by subclass PacketBridge */
flow_profiles = ntop->getPro()->has_valid_license() ? new FlowProfiles(id) : NULL;
if(flow_profiles) flow_profiles->loadProfiles();
shadow_flow_profiles = NULL;
#endif
loadDumpPrefs();
loadScalingFactorPrefs();
if(((statsManager = new StatsManager(id, STATS_MANAGER_STORE_NAME)) == NULL)
|| ((alertsManager = new AlertsManager(id, ALERTS_MANAGER_STORE_NAME)) == NULL))
throw "Not enough memory";
if((host_pools = new HostPools(this)) == NULL)
throw "Not enough memory";
alertLevel = alertsManager->getNumAlerts(true);
#ifdef linux
/*
A bit aggressive but as people usually
ignore warnings let's be proactive
*/
if(ifname
&& (!isViewInterface)
&& (!strstr(ifname, ":"))
&& (!strstr(ifname, ".pcap"))
&& strncmp(ifname, "lo", 2)
) {
char buf[64];
snprintf(buf, sizeof(buf), "ethtool -K %s gro off gso off tso off", ifname);
system(buf);
ntop->getTrace()->traceEvent(TRACE_NORMAL, "Executing %s", buf);
}
#endif
}
/* **************************************************** */
void NetworkInterface::init() {
ifname = remoteIfname = remoteIfIPaddr = remoteProbeIPaddr = NULL,
remoteProbePublicIPaddr = NULL, flows_hash = NULL, hosts_hash = NULL,
ndpi_struct = NULL, zmq_initial_bytes = 0, zmq_initial_pkts = 0,
sprobe_interface = inline_interface = false, has_vlan_packets = false,
last_pkt_rcvd = last_pkt_rcvd_remote = 0,
next_idle_flow_purge = next_idle_host_purge = 0,
running = false, numSubInterfaces = 0,
numVirtualInterfaces = 0, flowHashing = NULL,
pcap_datalink_type = 0, mtuWarningShown = false, lastSecUpdate = 0,
purge_idle_flows_hosts = true, id = (u_int8_t)-1,
last_remote_pps = 0, last_remote_bps = 0,
sprobe_interface = false, has_vlan_packets = false,
pcap_datalink_type = 0, cpu_affinity = -1 /* no affinity */,
inline_interface = false, running = false, interfaceStats = NULL,
tooManyFlowsAlertTriggered = tooManyHostsAlertTriggered = false,
pkt_dumper = NULL, numL2Devices = 0,
checkpointPktCount = checkpointBytesCount = checkpointPktDropCount = 0,
pollLoopCreated = false, bridge_interface = false;
if(ntop && ntop->getPrefs() && ntop->getPrefs()->are_taps_enabled())
pkt_dumper_tap = new PacketDumperTuntap(this);
else
pkt_dumper_tap = NULL;
memset(subInterfaces, 0, sizeof(subInterfaces));
ip_addresses = "", networkStats = NULL,
pcap_datalink_type = 0, cpu_affinity = -1,
pkt_dumper = NULL;
memset(lastMinuteTraffic, 0, sizeof(lastMinuteTraffic));
resetSecondTraffic();
reloadLuaInterpreter = true, L_flow_create_delete_ndpi = L_flow_update = NULL;
db = NULL;
#ifdef NTOPNG_PRO
policer = NULL;
#endif
statsManager = NULL, alertsManager = NULL, ifSpeed = 0;
host_pools = NULL;
checkIdle();
dump_all_traffic = dump_to_disk = dump_unknown_traffic
= dump_security_packets = dump_to_tap = false;
dump_sampling_rate = CONST_DUMP_SAMPLING_RATE;
dump_max_pkts_file = CONST_MAX_NUM_PACKETS_PER_DUMP;
dump_max_duration = CONST_MAX_DUMP_DURATION;
dump_max_files = CONST_MAX_DUMP;
ifMTU = CONST_DEFAULT_MAX_PACKET_SIZE, mtuWarningShown = false;
#ifdef NTOPNG_PRO
flow_profiles = shadow_flow_profiles = NULL;
#endif
}
/* **************************************************** */
#ifdef NTOPNG_PRO
void NetworkInterface::initL7Policer() {
/* Instantiate the policer */
policer = new L7Policer(this);
}
#endif
/* **************************************************** */
void NetworkInterface::checkAggregationMode() {
if(!customIftype) {
char rsp[32];
if(!strcmp(get_type(), CONST_INTERFACE_TYPE_ZMQ)) {
if(ntop->getRedis()->get((char*)CONST_RUNTIME_PREFS_IFACE_FLOW_COLLECTION, rsp, sizeof(rsp)) == 0) {
if(!strcmp(rsp, "probe_ip")) flowHashingMode = flowhashing_probe_ip;
else if(!strcmp(rsp, "ingress_iface_idx")) flowHashingMode = flowhashing_ingress_iface_idx;
}
} else {
if((ntop->getRedis()->get((char*)CONST_RUNTIME_PREFS_IFACE_VLAN_CREATION, rsp, sizeof(rsp)) == 0)
&& (!strncmp(rsp, "1", 1)))
flowHashingMode = flowhashing_vlan;
}
}
}
/* **************************************************** */
void NetworkInterface::loadDumpPrefs() {
if(ntop->getRedis() != NULL) {
updateDumpAllTrafficPolicy();
updateDumpTrafficDiskPolicy();
updateDumpTrafficTapPolicy();
updateDumpTrafficSamplingRate();
updateDumpTrafficMaxPktsPerFile();
updateDumpTrafficMaxSecPerFile();
updateDumpTrafficMaxFiles();
}
}
/* **************************************************** */
void NetworkInterface::loadScalingFactorPrefs() {
if(ntop->getRedis() != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), CONST_IFACE_SCALING_FACTOR_PREFS, id);
if((ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0) && (rsp[0] != '\0'))
scalingFactor = atol(rsp);
if(scalingFactor == 0) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "INTERNAL ERROR: scalingFactor can't be 0!");
scalingFactor = 1;
}
}
}
/* **************************************************** */
bool NetworkInterface::updateDumpTrafficTapPolicy(void) {
bool retval = false;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_tap", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = !strncmp(rsp, "true", 5);
else
retval = false;
}
dump_to_tap = retval;
return retval;
}
/* **************************************************** */
bool NetworkInterface::updateDumpAllTrafficPolicy(void) {
bool retval = false;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_all_traffic", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = !strncmp(rsp, "true", 5);
}
dump_all_traffic = retval;
return retval;
}
/* **************************************************** */
bool NetworkInterface::updateDumpTrafficDiskPolicy(void) {
bool retval = false, retval_u = false, retval_s = false;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_disk", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = !strncmp(rsp, "true", 5);
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_unknown_disk", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval_u = !strncmp(rsp, "true", 5);
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_security_disk", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval_s = !strncmp(rsp, "true", 5);
}
dump_to_disk = retval;
dump_unknown_traffic = retval_u;
dump_security_packets = retval_s;
return retval;
}
/* **************************************************** */
int NetworkInterface::updateDumpTrafficSamplingRate(void) {
int retval = 1;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_sampling_rate", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = atoi(rsp);
}
dump_sampling_rate = retval;
return retval;
}
/* **************************************************** */
int NetworkInterface::updateDumpTrafficMaxPktsPerFile(void) {
int retval = 0;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_max_pkts_file", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = atoi(rsp);
}
retval = retval > 0 ? retval : CONST_MAX_NUM_PACKETS_PER_DUMP;
dump_max_pkts_file = retval;
return retval;
}
/* **************************************************** */
int NetworkInterface::updateDumpTrafficMaxSecPerFile(void) {
int retval = 0;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_max_sec_file", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = atoi(rsp);
}
retval = retval > 0 ? retval : CONST_MAX_DUMP_DURATION;
dump_max_duration = retval;
return retval;
}
/* **************************************************** */
int NetworkInterface::updateDumpTrafficMaxFiles(void) {
int retval = 0;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s.dump_max_files", ifname);
if(ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0)
retval = atoi(rsp);
}
retval = retval > 0 ? retval : CONST_MAX_DUMP;
dump_max_files = retval;
return retval;
}
/* **************************************************** */
bool NetworkInterface::checkIdle() {
is_idle = false;
if(ifname != NULL) {
char rkey[128], rsp[16];
snprintf(rkey, sizeof(rkey), "ntopng.prefs.%s_not_idle", ifname);
if((ntop->getRedis()->get(rkey, rsp, sizeof(rsp)) == 0) && (rsp[0] != '\0')) {
int val = atoi(rsp);
if(val == 0) is_idle = true;
}
}
return(is_idle);
}
/* **************************************************** */
void NetworkInterface::deleteDataStructures() {
if(flows_hash) { delete(flows_hash); flows_hash = NULL; }
if(hosts_hash) { delete(hosts_hash); hosts_hash = NULL; }
if(macs_hash) { delete(macs_hash); macs_hash = NULL; }
if(ndpi_struct) {
ndpi_exit_detection_module(ndpi_struct);
ndpi_struct = NULL;
}
if(ifname) {
//ntop->getTrace()->traceEvent(TRACE_NORMAL, "Interface %s shutdown", ifname);
free(ifname);
ifname = NULL;
}
}
/* **************************************************** */
NetworkInterface::~NetworkInterface() {
if(getNumPackets() > 0) {
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"Flushing host contacts for interface %s",
get_name());
cleanup();
}
if(host_pools) delete host_pools; /* note: this requires ndpi_struct */
deleteDataStructures();
if(remoteIfname) free(remoteIfname);
if(remoteIfIPaddr) free(remoteIfIPaddr);
if(remoteProbeIPaddr) free(remoteProbeIPaddr);
if(remoteProbePublicIPaddr) free(remoteProbePublicIPaddr);
if(db) delete db;
if(statsManager) delete statsManager;
if(alertsManager) delete alertsManager;
if(networkStats) delete []networkStats;
if(pkt_dumper) delete pkt_dumper;
if(pkt_dumper_tap) delete pkt_dumper_tap;
if(interfaceStats) delete interfaceStats;
if(flowHashing) {
FlowHashing *current, *tmp;
HASH_ITER(hh, flowHashing, current, tmp) {
/* Interfaces are deleted by the main termination function */
HASH_DEL(flowHashing, current);
free(current);
}
}
#ifdef NTOPNG_PRO
if(policer) delete(policer);
if(flow_profiles) delete(flow_profiles);
if(shadow_flow_profiles) delete(shadow_flow_profiles);
#endif
termLuaInterpreter();
}
/* **************************************************** */
int NetworkInterface::dumpFlow(time_t when, bool idle_flow, Flow *f) {
if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
return(dumpDBFlow(when, idle_flow, f));
} else if(ntop->getPrefs()->do_dump_flows_on_es())
return(dumpEsFlow(when, f));
else {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Internal error");
return(-1);
}
}
/* **************************************************** */
int NetworkInterface::dumpEsFlow(time_t when, Flow *f) {
char *json = f->serialize(true);
int rc;
if(json) {
ntop->getTrace()->traceEvent(TRACE_INFO, "[ES] %s", json);
rc = ntop->getElasticSearch()->sendToES(json);
free(json);
} else
rc = -1;
return(rc);
}
/* **************************************************** */
int NetworkInterface::dumpDBFlow(time_t when, bool idle_flow, Flow *f) {
char *json = f->serialize(false);
int rc;
if(json) {
rc = db->dumpFlow(when, idle_flow, f, json);
free(json);
} else
rc = -1;
return(rc);
}
/* **************************************************** */
static bool local_hosts_2_redis_walker(GenericHashEntry *h, void *user_data) {
Host *host = (Host*)h;
if(host && (host->isLocalHost() || host->isSystemHost()))
host->serialize2redis();
return(false); /* false = keep on walking */
}
/* **************************************************** */
int NetworkInterface::dumpLocalHosts2redis(bool disable_purge) {
int rc;
if(disable_purge) disablePurge(false /* on hosts */);
rc = walker(walker_hosts, local_hosts_2_redis_walker, NULL) ? 0 : -1;
if(disable_purge) enablePurge(false /* on hosts */);
return rc;
}
/* **************************************************** */
u_int32_t NetworkInterface::getHostsHashSize() {
if(!isView())
return(hosts_hash->getNumEntries());
else {
u_int32_t tot = 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++)
tot += subInterfaces[s]->get_hosts_hash()->getNumEntries();
return(tot);
}
}
/* **************************************************** */
u_int32_t NetworkInterface::getFlowsHashSize() {
if(!isView())
return(flows_hash->getNumEntries());
else {
u_int32_t tot = 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++)
tot += subInterfaces[s]->get_flows_hash()->getNumEntries();
return(tot);
}
}
/* **************************************************** */
u_int32_t NetworkInterface::getMacsHashSize() {
if(!isView())
return(macs_hash->getNumEntries());
else {
u_int32_t tot = 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++)
tot += subInterfaces[s]->get_macs_hash()->getNumEntries();
return(tot);
}
}
/* **************************************************** */
bool NetworkInterface::walker(WalkerType wtype,
bool (*walker)(GenericHashEntry *h, void *user_data),
void *user_data) {
bool ret = false;
switch(wtype) {
case walker_hosts:
if(!isView())
ret = hosts_hash->walk(walker, user_data);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++)
ret |= subInterfaces[s]->get_hosts_hash()->walk(walker, user_data);
}
break;
case walker_flows:
if(!isView())
ret = flows_hash->walk(walker, user_data);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++)
ret |= subInterfaces[s]->get_flows_hash()->walk(walker, user_data);
}
break;
case walker_macs:
if(!isView())
ret = macs_hash->walk(walker, user_data);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++)
ret |= subInterfaces[s]->get_macs_hash()->walk(walker, user_data);
}
break;
}
return(ret);
}
/* **************************************************** */
Flow* NetworkInterface::getFlow(u_int8_t *src_eth, u_int8_t *dst_eth,
u_int16_t vlan_id,
u_int32_t deviceIP, u_int16_t inIndex, u_int16_t outIndex,
IpAddress *src_ip, IpAddress *dst_ip,
u_int16_t src_port, u_int16_t dst_port,
u_int8_t l4_proto,
bool *src2dst_direction,
time_t first_seen, time_t last_seen,
bool *new_flow) {
Flow *ret;
if(vlan_id != 0) setSeenVlanTaggedPackets();
ret = flows_hash->find(src_ip, dst_ip, src_port, dst_port,
vlan_id, l4_proto, src2dst_direction);
if(ret == NULL) {
*new_flow = true;
try {
ret = new Flow(this, vlan_id, l4_proto,
src_eth, src_ip, src_port,
dst_eth, dst_ip, dst_port,
first_seen, last_seen);
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
triggerTooManyFlowsAlert();
return(NULL);
}
if(flows_hash->add(ret)) {
*src2dst_direction = true;
if(inIndex && ret->get_cli_host()) {
Host *host = (Host*)ret->get_cli_host();
if(host->isLocalHost() || host->isSystemHost())
ret->get_cli_host()->setDeviceIfIdx(deviceIP, inIndex);
}
/*
We have decided to set only ingress traffic to make sure we do not mix truth with invalid data
if(outIndex && ret->get_srv_host()) ret->get_srv_host()->setDeviceIfIdx(deviceIP, outIndex);
*/
return(ret);
} else {
delete ret;
// ntop->getTrace()->traceEvent(TRACE_WARNING, "Too many flows");
return(NULL);
}
} else {
*new_flow = false;
return(ret);
}
}
/* **************************************************** */
void NetworkInterface::triggerTooManyFlowsAlert() {
if(!tooManyFlowsAlertTriggered) {
char alert_msg[512];
snprintf(alert_msg, sizeof(alert_msg),
"Interface <A HREF='%s/lua/if_stats.lua?ifid=%d'>%s</A> has too many flows. Please extend the --max-num-flows/-X command line option",
ntop->getPrefs()->get_http_prefix(),
id, get_name());
alertsManager->engageInterfaceAlert(this,
(char*)"app_misconfiguration",
alert_app_misconfiguration, alert_level_error, alert_msg);
tooManyFlowsAlertTriggered = true;
}
}
/* **************************************************** */
void NetworkInterface::triggerTooManyHostsAlert() {
if(!tooManyHostsAlertTriggered) {
char alert_msg[512];
snprintf(alert_msg, sizeof(alert_msg),
"Interface <A HREF='%s/lua/if_stats.lua?ifid=%d'>%s</A> has too many hosts. Please extend the --max-num-hosts/-x command line option",
ntop->getPrefs()->get_http_prefix(),
id, get_name());
alertsManager->releaseInterfaceAlert(this,
(char*)"app_misconfiguration",
alert_app_misconfiguration, alert_level_error, alert_msg);
tooManyHostsAlertTriggered = true;
}
}
/* **************************************************** */
NetworkInterface* NetworkInterface::getSubInterface(u_int32_t criteria) {
FlowHashing *h = NULL;
HASH_FIND_INT(flowHashing, &criteria, h);
if(h == NULL) {
/* Interface not found */
if(numVirtualInterfaces < MAX_NUM_VIRTUAL_INTERFACES) {
if((h = (FlowHashing*)malloc(sizeof(FlowHashing))) != NULL) {
char buf[64], buf1[48];
const char *vIface_type;
h->criteria = criteria;
switch(flowHashingMode) {
case flowhashing_vlan:
vIface_type = CONST_INTERFACE_TYPE_VLAN;
snprintf(buf, sizeof(buf), "%s [vlanId: %u]", ifname, criteria);
break;
case flowhashing_probe_ip:
vIface_type = CONST_INTERFACE_TYPE_FLOW;
snprintf(buf, sizeof(buf), "%s [probeIP: %s]", ifname,
Utils::intoaV4(criteria, buf1, sizeof(buf1)));
break;
case flowhashing_ingress_iface_idx:
vIface_type = CONST_INTERFACE_TYPE_FLOW;
snprintf(buf, sizeof(buf), "%s [ifIdx: %u]", ifname, criteria);
break;
default:
free(h);
return(NULL);
break;
}
if((h->iface = new NetworkInterface(buf, vIface_type)) != NULL) {
HASH_ADD_INT(flowHashing, criteria, h);
ntop->registerInterface(h->iface);
numVirtualInterfaces++;
}
} else
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
}
}
if(h) return(h->iface);
return(NULL);
}
/* **************************************************** */
void NetworkInterface::processFlow(ZMQ_Flow *zflow) {
bool src2dst_direction, new_flow;
Flow *flow;
ndpi_protocol p;
time_t now = time(NULL);
if(flowHashingMode != flowhashing_none) {
NetworkInterface *vIface;
switch(flowHashingMode) {
case flowhashing_probe_ip:
vIface = getSubInterface((u_int32_t)zflow->deviceIP);
break;
case flowhashing_ingress_iface_idx:
vIface = getSubInterface((u_int32_t)zflow->inIndex);
break;
default:
vIface = NULL;
break;
}
if(vIface) {
vIface->setTimeLastPktRcvd(getTimeLastPktRcvd());
vIface->processFlow(zflow);
return;
}
}
if(last_pkt_rcvd_remote > 0) {
int drift = now - last_pkt_rcvd_remote;
if(drift >= 0)
zflow->last_switched += drift, zflow->first_switched += drift;
else {
u_int32_t d = (u_int32_t)-drift;
if(d < zflow->last_switched) zflow->last_switched += drift;
if(d < zflow->first_switched) zflow->first_switched += drift;
}
#ifdef DEBUG
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"[first=%u][last=%u][duration: %u][drift: %d][now: %u][remote: %u]",
zflow->first_switched, zflow->last_switched,
zflow->last_switched-zflow->first_switched, drift,
now, last_pkt_rcvd_remote);
#endif
} else {
/* Old nProbe */
if((time_t)zflow->last_switched > (time_t)last_pkt_rcvd_remote)
last_pkt_rcvd_remote = zflow->last_switched;
#ifdef DEBUG
ntop->getTrace()->traceEvent(TRACE_NORMAL, "[first=%u][last=%u][duration: %u]",
zflow->first_switched, zflow->last_switched,
zflow->last_switched- zflow->first_switched);
#endif
}
/* Updating Flow */
flow = getFlow((u_int8_t*)zflow->src_mac, (u_int8_t*)zflow->dst_mac, zflow->vlan_id,
zflow->deviceIP, zflow->inIndex, zflow->outIndex,
&zflow->src_ip, &zflow->dst_ip,
zflow->src_port, zflow->dst_port,
zflow->l4_proto, &src2dst_direction,
zflow->first_switched,
zflow->last_switched, &new_flow);
incStats(now, zflow->src_ip.isIPv4() ? ETHERTYPE_IP : ETHERTYPE_IPV6,
flow ? flow->get_detected_protocol().protocol : NDPI_PROTOCOL_UNKNOWN,
zflow->pkt_sampling_rate*(zflow->in_bytes + zflow->out_bytes),
zflow->pkt_sampling_rate*(zflow->in_pkts + zflow->out_pkts),
24 /* 8 Preamble + 4 CRC + 12 IFG */ + 14 /* Ethernet header */);
if(flow == NULL)
return;
if(zflow->l4_proto == IPPROTO_TCP) {
struct timeval when;
when.tv_sec = (long)now, when.tv_usec = 0;
flow->updateTcpFlags((const struct bpf_timeval*)&when,
zflow->tcp_flags, src2dst_direction);
flow->incTcpBadStats(true,
zflow->tcp.ooo_in_pkts, zflow->tcp.retr_in_pkts, zflow->tcp.lost_in_pkts);
flow->incTcpBadStats(false,
zflow->tcp.ooo_out_pkts, zflow->tcp.retr_out_pkts, zflow->tcp.lost_out_pkts);
}
flow->addFlowStats(src2dst_direction,
zflow->pkt_sampling_rate*zflow->in_pkts,
zflow->pkt_sampling_rate*zflow->in_bytes, 0,
zflow->pkt_sampling_rate*zflow->out_pkts,
zflow->pkt_sampling_rate*zflow->out_bytes, 0,
zflow->last_switched);
p.protocol = zflow->l7_proto, p.master_protocol = NDPI_PROTOCOL_UNKNOWN;
flow->setDetectedProtocol(p, true);
flow->setJSONInfo(json_object_to_json_string(zflow->additional_fields));
flow->updateActivities();
flow->updateInterfaceLocalStats(src2dst_direction,
zflow->pkt_sampling_rate*(zflow->in_pkts+zflow->out_pkts),
zflow->pkt_sampling_rate*(zflow->in_bytes+zflow->out_bytes));
if(zflow->src_process.pid || zflow->dst_process.pid) {
if(zflow->src_process.pid) flow->handle_process(&zflow->src_process, src2dst_direction ? true : false);
if(zflow->dst_process.pid) flow->handle_process(&zflow->dst_process, src2dst_direction ? false : true);
if(zflow->l7_proto == NDPI_PROTOCOL_UNKNOWN)
flow->guessProtocol();
}
if(zflow->dns_query) flow->setDNSQuery(zflow->dns_query);
if(zflow->http_url) flow->setHTTPURL(zflow->http_url);
if(zflow->http_site) flow->setServerName(zflow->http_site);
if(zflow->ssl_server_name) flow->setServerName(zflow->ssl_server_name);
if(zflow->bittorrent_hash) flow->setBTHash(zflow->bittorrent_hash);
/* purge is actually performed at most one time every FLOW_PURGE_FREQUENCY */
// purgeIdle(zflow->last_switched);
}
/* **************************************************** */
void NetworkInterface::dumpPacketDisk(const struct pcap_pkthdr *h, const u_char *packet,
dump_reason reason) {
if(pkt_dumper == NULL)
pkt_dumper = new PacketDumper(this);
if(pkt_dumper)
pkt_dumper->dumpPacket(h, packet, reason, getDumpTrafficSamplingRate(),
getDumpTrafficMaxPktsPerFile(),
getDumpTrafficMaxSecPerFile());
}
/* **************************************************** */
void NetworkInterface::dumpPacketTap(const struct pcap_pkthdr *h, const u_char *packet,
dump_reason reason) {
if(pkt_dumper_tap)
pkt_dumper_tap->writeTap((unsigned char *)packet, h->len, reason,
getDumpTrafficSamplingRate());
}
/* **************************************************** */
bool NetworkInterface::processPacket(const struct bpf_timeval *when,
const u_int64_t time,
struct ndpi_ethhdr *eth,
u_int16_t vlan_id,
struct ndpi_iphdr *iph,
struct ndpi_ipv6hdr *ip6,
u_int16_t ipsize,
u_int32_t rawsize,
const struct pcap_pkthdr *h,
const u_char *packet,
u_int16_t *ndpiProtocol,
Host **srcHost, Host **dstHost,
Flow **hostFlow) {
bool src2dst_direction;
u_int8_t l4_proto;
Flow *flow;
u_int8_t *eth_src = eth->h_source, *eth_dst = eth->h_dest;
IpAddress src_ip, dst_ip;
u_int16_t src_port = 0, dst_port = 0, payload_len = 0;
struct ndpi_tcphdr *tcph = NULL;
struct ndpi_udphdr *udph = NULL;
u_int16_t l4_packet_len;
u_int8_t *l4, tcp_flags = 0, *payload = NULL;
u_int8_t *ip;
bool is_fragment = false, new_flow;
bool pass_verdict = true;
/* VLAN disaggregation */
if((flowHashingMode == flowhashing_vlan) && (vlan_id > 0)) {
NetworkInterface *vIface;
if((vIface = getSubInterface((u_int32_t)vlan_id)) != NULL) {
vIface->setTimeLastPktRcvd(getTimeLastPktRcvd());
return(vIface->processPacket(when, time, eth, vlan_id,
iph, ip6, ipsize, rawsize,
h, packet, ndpiProtocol,
srcHost, dstHost, hostFlow));
}
}
decode_ip:
if(iph != NULL) {
/* IPv4 */
if(ipsize < 20) {
incStats(when->tv_sec, ETHERTYPE_IP, NDPI_PROTOCOL_UNKNOWN,
rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
if((iph->ihl * 4) > ipsize || ipsize < ntohs(iph->tot_len)
|| (iph->frag_off & htons(0x1FFF /* IP_OFFSET */)) != 0) {
is_fragment = true;
}
l4_packet_len = ntohs(iph->tot_len) - (iph->ihl * 4);
l4_proto = iph->protocol;
l4 = ((u_int8_t *) iph + iph->ihl * 4);
ip = (u_int8_t*)iph;
} else {
/* IPv6 */
u_int ipv6_shift = sizeof(const struct ndpi_ipv6hdr);
if(ipsize < sizeof(const struct ndpi_ipv6hdr)) {
incStats(when->tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize,
1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
l4_packet_len = ntohs(ip6->ip6_ctlun.ip6_un1.ip6_un1_plen);
l4_proto = ip6->ip6_ctlun.ip6_un1.ip6_un1_nxt;
if(l4_proto == 0x3C /* IPv6 destination option */) {
u_int8_t *options = (u_int8_t*)ip6 + ipv6_shift;
l4_proto = options[0];
ipv6_shift = 8 * (options[1] + 1);
if(ipsize < ipv6_shift) {
incStats(when->tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
}
l4 = (u_int8_t*)ip6 + ipv6_shift;
ip = (u_int8_t*)ip6;
}
if(l4_proto == IPPROTO_TCP) {
if(l4_packet_len >= sizeof(struct ndpi_tcphdr)) {
u_int tcp_len;
/* TCP */
tcph = (struct ndpi_tcphdr *)l4;
src_port = tcph->source, dst_port = tcph->dest;
tcp_flags = l4[13];
tcp_len = min_val(4*tcph->doff, l4_packet_len);
payload = &l4[tcp_len];
payload_len = max_val(0, l4_packet_len-4*tcph->doff);
// TODO: check if payload should be set to NULL when payload_len == 0
} else {
/* Packet too short: this is a faked packet */
ntop->getTrace()->traceEvent(TRACE_INFO, "Invalid TCP packet received [%u bytes long]", l4_packet_len);
incStats(when->tv_sec, iph ? ETHERTYPE_IP : ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
} else if(l4_proto == IPPROTO_UDP) {
if(l4_packet_len >= sizeof(struct ndpi_udphdr)) {
/* UDP */
udph = (struct ndpi_udphdr *)l4;
src_port = udph->source, dst_port = udph->dest;
payload = &l4[sizeof(struct ndpi_udphdr)];
payload_len = max_val(0, l4_packet_len-sizeof(struct ndpi_udphdr));
} else {
/* Packet too short: this is a faked packet */
ntop->getTrace()->traceEvent(TRACE_INFO, "Invalid UDP packet received [%u bytes long]", l4_packet_len);
incStats(when->tv_sec, iph ? ETHERTYPE_IP : ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
} else if(l4_proto == IPPROTO_GRE) {
struct grev1_header gre;
int offset = sizeof(struct grev1_header);
memcpy(&gre, l4, sizeof(struct grev1_header));
gre.flags_and_version = ntohs(gre.flags_and_version);
gre.proto = ntohs(gre.proto);
if(gre.flags_and_version & (GRE_HEADER_CHECKSUM | GRE_HEADER_ROUTING)) offset += 4;
if(gre.flags_and_version & GRE_HEADER_KEY) offset += 4;
if(gre.flags_and_version & GRE_HEADER_SEQ_NUM) offset += 4;
if(gre.proto == ETHERTYPE_IP) {
iph = (struct ndpi_iphdr*)(l4 + offset), ip6 = NULL;
goto decode_ip;
} else if(gre.proto == ETHERTYPE_IPV6) {
iph = (struct ndpi_iphdr*)(l4 + offset), ip6 = NULL;
goto decode_ip;
} else {
/* Unknown encapsulation */
}
} else {
/* non TCP/UDP protocols */
}
if(iph != NULL)
src_ip.set(iph->saddr), dst_ip.set(iph->daddr);
else
src_ip.set(&ip6->ip6_src), dst_ip.set(&ip6->ip6_dst);
#if defined(WIN32) && defined(DEMO_WIN32)
if(this->ethStats.getNumPackets() > MAX_NUM_PACKETS) {
static bool showMsg = false;
if(!showMsg) {
ntop->getTrace()->traceEvent(TRACE_NORMAL, "-----------------------------------------------------------");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "WARNING: this demo application is a limited ntopng version able to");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "capture up to %d packets. If you are interested", MAX_NUM_PACKETS);
ntop->getTrace()->traceEvent(TRACE_NORMAL, "in the full version please have a look at the ntop");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "home page http://www.ntop.org/.");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "-----------------------------------------------------------");
ntop->getTrace()->traceEvent(TRACE_NORMAL, "");
showMsg = true;
}
return(pass_verdict);
}
#endif
/* Updating Flow */
flow = getFlow(eth_src, eth_dst, vlan_id, 0, 0, 0, &src_ip, &dst_ip, src_port, dst_port,
l4_proto, &src2dst_direction, last_pkt_rcvd, last_pkt_rcvd, &new_flow);
if(flow == NULL) {
incStats(when->tv_sec, iph ? ETHERTYPE_IP : ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN,
rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
} else {
*srcHost = src2dst_direction ? flow->get_cli_host() : flow->get_srv_host();
*dstHost = src2dst_direction ? flow->get_srv_host() : flow->get_cli_host();
*hostFlow = flow;
switch(l4_proto) {
case IPPROTO_TCP:
flow->updateTcpFlags(when, tcp_flags, src2dst_direction);
flow->updateTcpSeqNum(when, ntohl(tcph->seq), ntohl(tcph->ack_seq), ntohs(tcph->window),
tcp_flags, l4_packet_len - (4 * tcph->doff),
src2dst_direction);
break;
case IPPROTO_ICMP:
case IPPROTO_ICMPV6:
if(l4_packet_len > 2) {
u_int8_t icmp_type = l4[0];
u_int8_t icmp_code = l4[1];
if((flow->get_cli_host()->isLocalHost()) && (flow->get_srv_host()->isLocalHost())) {
/* Set correct direction in localhost ping */
if((icmp_type == 8) || /* ICMP Echo [RFC792] */
(icmp_type == 128)) /* ICMPV6 Echo Request [RFC4443] */
src2dst_direction = true;
else if((icmp_type == 0) || /* ICMP Echo Reply [RFC792] */
(icmp_type == 129)) /* ICMPV6 Echo Reply [RFC4443] */
src2dst_direction = false;
}
flow->setICMP(icmp_type, icmp_code);
}
break;
}
#ifdef __OpenBSD__
struct timeval tv_ts;
tv_ts.tv_sec = h->ts.tv_sec;
tv_ts.tv_usec = h->ts.tv_usec;
flow->incStats(src2dst_direction, rawsize, payload, payload_len, l4_proto, &tv_ts);
#else
flow->incStats(src2dst_direction, rawsize, payload, payload_len, l4_proto, &h->ts);
#endif
}
/* Protocol Detection */
flow->updateActivities();
flow->updateInterfaceLocalStats(src2dst_direction, 1, rawsize);
if(!flow->isDetectionCompleted()) {
if(isSampledTraffic())
flow->guessProtocol();
else {
if(!is_fragment) {
struct ndpi_flow_struct *ndpi_flow = flow->get_ndpi_flow();
struct ndpi_id_struct *cli = (struct ndpi_id_struct*)flow->get_cli_id();
struct ndpi_id_struct *srv = (struct ndpi_id_struct*)flow->get_srv_id();
if(flow->get_packets() >= NDPI_MIN_NUM_PACKETS)
flow->setDetectedProtocol(ndpi_detection_giveup(ndpi_struct, ndpi_flow), false);
else
flow->setDetectedProtocol(ndpi_detection_process_packet(ndpi_struct, ndpi_flow,
ip, ipsize, (u_int32_t)time,
cli, srv), false);
} else {
// FIX - only handle unfragmented packets
// ntop->getTrace()->traceEvent(TRACE_WARNING, "IP fragments are not handled yet!");
}
}
}
if(flow->isDetectionCompleted()
&& (!isSampledTraffic())
&& flow->get_cli_host()
&& flow->get_srv_host()) {
struct ndpi_flow_struct *ndpi_flow;
switch(ndpi_get_lower_proto(flow->get_detected_protocol())) {
case NDPI_PROTOCOL_DHCP:
if(payload_len > 240) {
for(int i = 240; i<payload_len; ) {
u_int8_t id = payload[i], len = payload[i+1];
if(len == 0) break;
if(id == 12 /* Host Name */) {
char name[64], buf[24], *client_mac, key[64];
int j;
j = ndpi_min(len, sizeof(name)-1);
strncpy((char*)name, (char*)&payload[i+2], j);
name[j] = '\0';
client_mac = Utils::formatMac(&payload[28], buf, sizeof(buf)),
ntop->getTrace()->traceEvent(TRACE_INFO, "[DHCP] %s = '%s'", client_mac, name);
snprintf(key, sizeof(key), DHCP_CACHE, get_id());
ntop->getRedis()->hashSet(key, client_mac, name);
break;
} else if(id == 0xFF)
break; /* End of options */
i += len + 2;
}
}
break;
case NDPI_PROTOCOL_BITTORRENT:
if((flow->getBitTorrentHash() == NULL)
&& (l4_proto == IPPROTO_UDP)
&& (flow->get_packets() < 8))
flow->dissectBittorrent((char*)payload, payload_len);
break;
case NDPI_PROTOCOL_HTTP:
if(payload_len > 0)
flow->dissectHTTP(src2dst_direction, (char*)payload, payload_len);
break;
case NDPI_PROTOCOL_DNS:
ndpi_flow = flow->get_ndpi_flow();
/*
DNS-over-TCP flows may carry zero-payload TCP segments
e.g., during three-way-handshake, or when acknowledging.
Make sure only non-zero-payload segments are processed.
*/
if((payload_len > 0) && payload) {
/*
DNS-over-TCP has a 2-bytes field with DNS payload length
at the beginning. See RFC1035 section 4.2.2. TCP usage.
*/
u_int8_t dns_offset = l4_proto == IPPROTO_TCP && payload_len > 1 ? 2 : 0;
struct ndpi_dns_packet_header *header = (struct ndpi_dns_packet_header*)(payload + dns_offset);
u_int16_t dns_flags = ntohs(header->flags);
bool is_query = ((dns_flags & 0x8000) == 0x8000) ? false : true;
if(flow->get_cli_host() && flow->get_srv_host()) {
Host *client = src2dst_direction ? flow->get_cli_host() : flow->get_srv_host();
Host *server = src2dst_direction ? flow->get_srv_host() : flow->get_cli_host();
/*
Inside the DNS packet it is possible to have multiple queries
and mix query types. In general this is not a practice followed
by applications.
*/
if(is_query) {
u_int16_t query_type = ndpi_flow ? ndpi_flow->protos.dns.query_type : 0;
client->incNumDNSQueriesSent(query_type), server->incNumDNSQueriesRcvd(query_type);
} else {
u_int8_t ret_code = (dns_flags & 0x000F);
client->incNumDNSResponsesSent(ret_code), server->incNumDNSResponsesRcvd(ret_code);
}
}
}
if(ndpi_flow) {
struct ndpi_id_struct *cli = (struct ndpi_id_struct*)flow->get_cli_id();
struct ndpi_id_struct *srv = (struct ndpi_id_struct*)flow->get_srv_id();
memset(&ndpi_flow->detected_protocol_stack,
0, sizeof(ndpi_flow->detected_protocol_stack));
ndpi_detection_process_packet(ndpi_struct, ndpi_flow,
ip, ipsize, (u_int32_t)time,
src2dst_direction ? cli : srv,
src2dst_direction ? srv : cli);
/*
We reset the nDPI flow so that it can decode new packets
of the same flow (e.g. the DNS response)
*/
ndpi_flow->detected_protocol_stack[0] = NDPI_PROTOCOL_UNKNOWN;
}
break;
default:
if(flow->isSSLProto())
flow->dissectSSL(payload, payload_len, when, src2dst_direction);
}
flow->processDetectedProtocol();
#ifdef NTOPNG_PRO
if(is_bridge_interface()) {
pass_verdict = flow->isPassVerdict();
if(pass_verdict) {
u_int8_t shaper_ingress, shaper_engress;
char buf[64];
flow->getFlowShapers(src2dst_direction, &shaper_ingress, &shaper_engress);
ntop->getTrace()->traceEvent(TRACE_DEBUG, "[%s] %u / %u ",
flow->get_detected_protocol_name(buf, sizeof(buf)),
shaper_ingress, shaper_engress);
pass_verdict = passShaperPacket(shaper_ingress, shaper_engress, (struct pcap_pkthdr*)h);
}
}
#endif
bool dump_if_unknown = dump_unknown_traffic
&& (!flow->isDetectionCompleted() ||
flow->get_detected_protocol().protocol == NDPI_PROTOCOL_UNKNOWN);
if(dump_if_unknown
|| dump_all_traffic
|| dump_security_packets
|| flow->dumpFlowTraffic()) {
if(dump_to_disk) dumpPacketDisk(h, packet, dump_if_unknown ? UNKNOWN : GUI);
if(dump_to_tap) dumpPacketTap(h, packet, GUI);
}
}
incStats(when->tv_sec, iph ? ETHERTYPE_IP : ETHERTYPE_IPV6,
flow->get_detected_protocol().protocol,
rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
// Detect user activities
if((!isSampledTraffic())
&& (ntop->getPrefs()->is_flow_activity_enabled())) {
Host *cli = flow->get_cli_host();
Host *srv = flow->get_srv_host();
if((cli->isLocalHost() || srv->isLocalHost())
&& (!flow->isSSLProto() || flow->isSSLData())) {
UserActivityID activity;
u_int64_t up = 0, down = 0, backgr = 0, bytes = payload_len;
if(flow->getActivityId(&activity)) {
#ifdef __OpenBSD__
struct timeval* tv_when;
tv_when->tv_sec = when->tv_sec;
tv_when->tv_usec = when->tv_usec;
if(flow->invokeActivityFilter(tv_when, src2dst_direction, payload_len)) {
#else
if(flow->invokeActivityFilter(when, src2dst_direction, payload_len)) {
#endif
if(src2dst_direction)
up = bytes;
else
down = bytes;
} else {
backgr = bytes;
}
if(cli->isLocalHost())
cli->incActivityBytes(activity, up, down, backgr);
if(srv->isLocalHost())
srv->incActivityBytes(activity, down, up, backgr);
}
}
}
return(pass_verdict);
}
/* **************************************************** */
void NetworkInterface::purgeIdle(time_t when) {
if(purge_idle_flows_hosts) {
u_int n;
last_pkt_rcvd = when;
if((n = purgeIdleFlows()) > 0)
ntop->getTrace()->traceEvent(TRACE_INFO, "Purged %u/%u idle flows on %s",
n, getNumFlows(), ifname);
if((n = purgeIdleHostsMacs()) > 0)
ntop->getTrace()->traceEvent(TRACE_INFO, "Purged %u/%u idle hosts/macs on %s",
n, getNumHosts()+getNumMacs(), ifname);
}
if(pkt_dumper) pkt_dumper->idle(when);
updateSecondTraffic(when);
}
/* **************************************************** */
bool NetworkInterface::dissectPacket(const struct pcap_pkthdr *h,
const u_char *packet,
u_int16_t *ndpiProtocol,
Host **srcHost, Host **dstHost,
Flow **flow) {
struct ndpi_ethhdr *ethernet, dummy_ethernet;
u_int64_t time;
u_int16_t eth_type, ip_offset, vlan_id = 0, eth_offset = 0;
u_int32_t null_type;
int pcap_datalink_type = get_datalink();
bool pass_verdict = true;
u_int32_t rawsize = h->len * scalingFactor;
if(h->len > ifMTU) {
if(!mtuWarningShown) {
ntop->getTrace()->traceEvent(TRACE_NORMAL, "Invalid packet received [len: %u][max-len: %u].", h->len, ifMTU);
ntop->getTrace()->traceEvent(TRACE_WARNING, "If you have TSO/GRO enabled, please disable it");
#ifdef linux
ntop->getTrace()->traceEvent(TRACE_WARNING, "Use sudo ethtool -K %s gro off gso off tso off", ifname);
#endif
mtuWarningShown = true;
}
}
setTimeLastPktRcvd(h->ts.tv_sec);
time = ((uint64_t) h->ts.tv_sec) * 1000 + h->ts.tv_usec / 1000;
datalink_check:
if(pcap_datalink_type == DLT_NULL) {
memcpy(&null_type, &packet[eth_offset], sizeof(u_int32_t));
switch(null_type) {
case BSD_AF_INET:
eth_type = ETHERTYPE_IP;
break;
case BSD_AF_INET6_BSD:
case BSD_AF_INET6_FREEBSD:
case BSD_AF_INET6_DARWIN:
eth_type = ETHERTYPE_IPV6;
break;
default:
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict); /* Any other non IP protocol */
}
memset(&dummy_ethernet, 0, sizeof(dummy_ethernet));
ethernet = (struct ndpi_ethhdr *)&dummy_ethernet;
ip_offset = 4 + eth_offset;
} else if(pcap_datalink_type == DLT_EN10MB) {
ethernet = (struct ndpi_ethhdr *)&packet[eth_offset];
ip_offset = sizeof(struct ndpi_ethhdr) + eth_offset;
eth_type = ntohs(ethernet->h_proto);
} else if(pcap_datalink_type == 113 /* Linux Cooked Capture */) {
memset(&dummy_ethernet, 0, sizeof(dummy_ethernet));
ethernet = (struct ndpi_ethhdr *)&dummy_ethernet;
eth_type = (packet[eth_offset+14] << 8) + packet[eth_offset+15];
ip_offset = 16 + eth_offset;
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
#ifdef DLT_RAW
} else if(pcap_datalink_type == DLT_RAW /* Linux TUN/TAP device in TUN mode; Raw IP capture */) {
switch((packet[eth_offset] & 0xf0) >> 4) {
case 4:
eth_type = ETHERTYPE_IP;
break;
case 6:
eth_type = ETHERTYPE_IPV6;
break;
default:
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict); /* Unknown IP protocol version */
}
memset(&dummy_ethernet, 0, sizeof(dummy_ethernet));
ethernet = (struct ndpi_ethhdr *)&dummy_ethernet;
ip_offset = eth_offset;
#endif /* DLT_RAW */
} else if(pcap_datalink_type == DLT_IPV4) {
eth_type = ETHERTYPE_IP;
memset(&dummy_ethernet, 0, sizeof(dummy_ethernet));
ethernet = (struct ndpi_ethhdr *)&dummy_ethernet;
ip_offset = 0;
} else {
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
while(true) {
if(eth_type == 0x8100 /* VLAN */) {
Ether80211q *qType = (Ether80211q*)&packet[ip_offset];
vlan_id = ntohs(qType->vlanId) & 0xFFF;
eth_type = (packet[ip_offset+2] << 8) + packet[ip_offset+3];
ip_offset += 4;
} else if(eth_type == 0x8847 /* MPLS */) {
u_int8_t bos; /* bottom_of_stack */
bos = (((u_int8_t)packet[ip_offset+2]) & 0x1), ip_offset += 4;
if(bos) {
eth_type = ETHERTYPE_IP;
break;
}
} else
break;
}
decode_packet_eth:
switch(eth_type) {
case ETHERTYPE_PPOE:
eth_type = ETHERTYPE_IP;
ip_offset += 8;
goto decode_packet_eth;
break;
case ETHERTYPE_IP:
if(h->caplen >= ip_offset) {
u_int16_t frag_off;
struct ndpi_iphdr *iph = (struct ndpi_iphdr *) &packet[ip_offset];
struct ndpi_ipv6hdr *ip6 = NULL;
if(iph->version != 4) {
/* This is not IPv4 */
incStats(h->ts.tv_sec, ETHERTYPE_IP, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
} else
frag_off = ntohs(iph->frag_off);
if(ntop->getGlobals()->decode_tunnels() && (iph->protocol == IPPROTO_UDP)
&& ((frag_off & 0x3FFF /* IP_MF | IP_OFFSET */ ) == 0)) {
u_short ip_len = ((u_short)iph->ihl * 4);
struct ndpi_udphdr *udp = (struct ndpi_udphdr *)&packet[ip_offset+ip_len];
u_int16_t sport = ntohs(udp->source), dport = ntohs(udp->dest);
if((sport == GTP_U_V1_PORT) || (dport == GTP_U_V1_PORT)) {
/* Check if it's GTPv1 */
u_int offset = (u_int)(ip_offset+ip_len+sizeof(struct ndpi_udphdr));
u_int8_t flags = packet[offset];
u_int8_t message_type = packet[offset+1];
if((((flags & 0xE0) >> 5) == 1 /* GTPv1 */) && (message_type == 0xFF /* T-PDU */)) {
ip_offset = ip_offset+ip_len+sizeof(struct ndpi_udphdr)+8 /* GTPv1 header len */;
if(flags & 0x04) ip_offset += 1; /* next_ext_header is present */
if(flags & 0x02) ip_offset += 4; /* sequence_number is present (it also includes next_ext_header and pdu_number) */
if(flags & 0x01) ip_offset += 1; /* pdu_number is present */
iph = (struct ndpi_iphdr *) &packet[ip_offset];
if(iph->version != 4) {
/* FIX - Add IPv6 support */
incStats(h->ts.tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
}
} else if((sport == TZSP_PORT) || (dport == TZSP_PORT)) {
/* https://en.wikipedia.org/wiki/TZSP */
u_int offset = ip_offset+ip_len+sizeof(struct ndpi_udphdr);
u_int8_t version = packet[offset];
u_int8_t type = packet[offset+1];
u_int16_t encapsulates = ntohs(*((u_int16_t*)&packet[offset+2]));
if((version == 1) && (type == 0) && (encapsulates == 1)) {
u_int8_t stop = 0;
offset += 4;
while((!stop) && (offset < h->caplen)) {
u_int8_t tag_type = packet[offset];
u_int8_t tag_len;
switch(tag_type) {
case 0: /* PADDING Tag */
tag_len = 1;
break;
case 1: /* END Tag */
tag_len = 1, stop = 1;
break;
default:
tag_len = packet[offset+1];
break;
}
offset += tag_len;
if(offset >= h->caplen) {
incStats(h->ts.tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
} else {
eth_offset = offset;
goto datalink_check;
}
}
}
}
if((sport == CAPWAP_DATA_PORT) || (dport == CAPWAP_DATA_PORT)) {
/*
Control And Provisioning of Wireless Access Points
https://www.rfc-editor.org/rfc/rfc5415.txt
CAPWAP Header - variable length (5 MSB of byte 2 of header)
IEEE 802.11 Data Flags - 24 bytes
Logical-Link Control - 8 bytes
Total = CAPWAP_header_length + 24 + 8
*/
u_short eth_type;
ip_offset = ip_offset+ip_len+sizeof(struct ndpi_udphdr);
u_int8_t capwap_header_len = ((*(u_int8_t*)&packet[ip_offset+1])>>3)*4;
ip_offset = ip_offset+capwap_header_len+24+8;
if(ip_offset >= h->len) {
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
eth_type = ntohs(*(u_int16_t*)&packet[ip_offset-2]);
switch(eth_type) {
case ETHERTYPE_IP:
iph = (struct ndpi_iphdr *) &packet[ip_offset];
break;
case ETHERTYPE_IPV6:
iph = NULL;
ip6 = (struct ndpi_ipv6hdr*)&packet[ip_offset];
break;
default:
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
}
}
if((vlan_id == 0) && ntop->getPrefs()->do_simulate_vlans())
vlan_id = (ip6 ? ip6->ip6_src.u6_addr.u6_addr8[15] : iph->saddr) & 0xFF;
try {
pass_verdict = processPacket(&h->ts, time, ethernet, vlan_id, iph,
ip6, h->caplen - ip_offset, rawsize,
h, packet, ndpiProtocol, srcHost, dstHost, flow);
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
}
}
break;
case ETHERTYPE_IPV6:
if(h->caplen >= ip_offset) {
struct ndpi_iphdr *iph = NULL;
struct ndpi_ipv6hdr *ip6 = (struct ndpi_ipv6hdr*)&packet[ip_offset];
if((ntohl(ip6->ip6_ctlun.ip6_un1.ip6_un1_flow) & 0xF0000000) != 0x60000000) {
/* This is not IPv6 */
incStats(h->ts.tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
} else {
u_int ipv6_shift = sizeof(const struct ndpi_ipv6hdr);
u_int8_t l4_proto = ip6->ip6_ctlun.ip6_un1.ip6_un1_nxt;
if(l4_proto == 0x3C /* IPv6 destination option */) {
u_int8_t *options = (u_int8_t*)ip6 + ipv6_shift;
l4_proto = options[0];
ipv6_shift = 8 * (options[1] + 1);
}
if(ntop->getGlobals()->decode_tunnels() && (l4_proto == IPPROTO_UDP)) {
ip_offset += ipv6_shift;
if(ip_offset >= h->len) {
incStats(h->ts.tv_sec, ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
struct ndpi_udphdr *udp = (struct ndpi_udphdr *)&packet[ip_offset];
u_int16_t sport = udp->source, dport = udp->dest;
if((sport == CAPWAP_DATA_PORT) || (dport == CAPWAP_DATA_PORT)) {
/*
Control And Provisioning of Wireless Access Points
https://www.rfc-editor.org/rfc/rfc5415.txt
CAPWAP Header - variable length (5 MSB of byte 2 of header)
IEEE 802.11 Data Flags - 24 bytes
Logical-Link Control - 8 bytes
Total = CAPWAP_header_length + 24 + 8
*/
u_short eth_type;
ip_offset = ip_offset+sizeof(struct ndpi_udphdr);
u_int8_t capwap_header_len = ((*(u_int8_t*)&packet[ip_offset+1])>>3)*4;
ip_offset = ip_offset+capwap_header_len+24+8;
if(ip_offset >= h->len) {
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
eth_type = ntohs(*(u_int16_t*)&packet[ip_offset-2]);
switch(eth_type) {
case ETHERTYPE_IP:
iph = (struct ndpi_iphdr *) &packet[ip_offset];
ip6 = NULL;
break;
case ETHERTYPE_IPV6:
ip6 = (struct ndpi_ipv6hdr*)&packet[ip_offset];
break;
default:
incStats(h->ts.tv_sec, 0, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
return(pass_verdict);
}
}
}
if((vlan_id == 0) && ntop->getPrefs()->do_simulate_vlans())
vlan_id = (ip6 ? ip6->ip6_src.u6_addr.u6_addr8[15] : iph->saddr) & 0xFF;
try {
pass_verdict = processPacket(&h->ts, time, ethernet, vlan_id,
iph, ip6, h->len - ip_offset, rawsize,
h, packet, ndpiProtocol, srcHost, dstHost, flow);
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
}
}
}
break;
default: /* No IPv4 nor IPv6 */
Mac *srcMac = getMac(ethernet->h_source, vlan_id, true);
Mac *dstMac = getMac(ethernet->h_dest, vlan_id, true);
if(srcMac) srcMac->incSentStats(rawsize);
if(dstMac) dstMac->incRcvdStats(rawsize);
incStats(h->ts.tv_sec, eth_type, NDPI_PROTOCOL_UNKNOWN, rawsize,
1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
break;
}
purgeIdle(last_pkt_rcvd);
return(pass_verdict);
}
/* **************************************************** */
void NetworkInterface::startPacketPolling() {
if((cpu_affinity != -1) && (ntop->getNumCPUs() > 1)) {
if(Utils::setThreadAffinity(pollLoop, cpu_affinity))
ntop->getTrace()->traceEvent(TRACE_WARNING, "Could not set affinity of interface %s to core %d",
get_name(), cpu_affinity);
else
ntop->getTrace()->traceEvent(TRACE_NORMAL, "Setting affinity of interface %s to core %d",
get_name(), cpu_affinity);
}
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"Started packet polling on interface %s [id: %u]...",
get_name(), get_id());
running = true;
}
/* **************************************************** */
void NetworkInterface::shutdown() {
running = false;
}
/* **************************************************** */
void NetworkInterface::cleanup() {
next_idle_flow_purge = next_idle_host_purge = 0;
cpu_affinity = -1, has_vlan_packets = false;
running = false, sprobe_interface = false, inline_interface = false;
getStats()->cleanup();
flows_hash->cleanup();
hosts_hash->cleanup();
macs_hash->cleanup();
ntop->getTrace()->traceEvent(TRACE_NORMAL, "Cleanup interface %s", get_name());
}
/* **************************************************** */
void NetworkInterface::findFlowHosts(u_int16_t vlanId,
u_int8_t src_mac[6], IpAddress *_src_ip, Host **src,
u_int8_t dst_mac[6], IpAddress *_dst_ip, Host **dst) {
if(!isView())
(*src) = hosts_hash->get(vlanId, _src_ip);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
if(((*src) = subInterfaces[s]->get_hosts_hash()->get(vlanId, _src_ip)) != NULL)
break;
}
}
if((*src) == NULL) {
if(!hosts_hash->hasEmptyRoom()) {
*src = *dst = NULL;
triggerTooManyHostsAlert();
return;
}
(*src) = new Host(this, src_mac, vlanId, _src_ip);
if(!hosts_hash->add(*src)) {
//ntop->getTrace()->traceEvent(TRACE_WARNING, "Too many hosts in interface %s", ifname);
delete *src;
*src = *dst = NULL;
triggerTooManyHostsAlert();
return;
}
}
/* ***************************** */
(*dst) = hosts_hash->get(vlanId, _dst_ip);
if((*dst) == NULL) {
if(!hosts_hash->hasEmptyRoom()) {
*dst = NULL;
triggerTooManyHostsAlert();
return;
}
(*dst) = new Host(this, dst_mac, vlanId, _dst_ip);
if(!hosts_hash->add(*dst)) {
// ntop->getTrace()->traceEvent(TRACE_WARNING, "Too many hosts in interface %s", ifname);
delete *dst;
*dst = NULL;
triggerTooManyHostsAlert();
return;
}
}
}
/* **************************************************** */
struct ndpiStatsRetrieverData {
nDPIStats *stats;
Host *host;
};
static bool flow_sum_protos(GenericHashEntry *flow, void *user_data) {
ndpiStatsRetrieverData *retriever = (ndpiStatsRetrieverData*)user_data;
nDPIStats *stats = retriever->stats;
Flow *f = (Flow*)flow;
if(retriever->host
&& (retriever->host != f->get_cli_host())
&& (retriever->host != f->get_srv_host()))
return(false); /* false = keep on walking */
f->sumStats(stats);
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::getnDPIStats(nDPIStats *stats, AddressTree *allowed_hosts,
const char *host_ip, u_int16_t vlan_id) {
ndpiStatsRetrieverData retriever;
Host *h = NULL;
if (host_ip)
h = findHostsByIP(allowed_hosts, (char *)host_ip, vlan_id);
retriever.stats = stats;
retriever.host = h;
walker(walker_flows, flow_sum_protos, (void*)&retriever);
}
/* **************************************************** */
static bool flow_update_hosts_stats(GenericHashEntry *node, void *user_data) {
Flow *flow = (Flow*)node;
struct timeval *tv = (struct timeval*)user_data;
flow->update_hosts_stats(tv, false);
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool update_hosts_stats(GenericHashEntry *node, void *user_data) {
Host *host = (Host*)node;
struct timeval *tv = (struct timeval*)user_data;
host->updateStats(tv);
/*
ntop->getTrace()->traceEvent(TRACE_WARNING, "Updated: %s [%d]",
((StringHost*)node)->host_key(),
host->getThptTrend());
*/
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool update_macs_stats(GenericHashEntry *node, void *user_data) {
Mac *mac = (Mac*)node;
struct timeval *tv = (struct timeval*)user_data;
mac->updateStats(tv);
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::periodicStatsUpdate() {
struct timeval tv;
if(isView()) return;
gettimeofday(&tv, NULL);
flows_hash->walk(flow_update_hosts_stats, (void*)&tv);
hosts_hash->walk(update_hosts_stats, (void*)&tv);
macs_hash->walk(update_macs_stats, (void*)&tv);
if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
static_cast<MySQLDB*>(db)->updateStats(&tv);
db->flush(false /* not idle, periodic activities */);
}
#ifdef NTOPNG_PRO
if(host_pools)
host_pools->updateStats(&tv);
#endif
}
/* **************************************************** */
struct update_host_pool_l7policy {
bool update_pool_id;
bool update_l7policy;
};
static bool update_host_host_pool_l7policy(GenericHashEntry *node, void *user_data) {
Host *h = (Host*)node;
update_host_pool_l7policy *up = (update_host_pool_l7policy*)user_data;
#ifdef HOST_POOLS_DEBUG
char buf[128];
u_int16_t cur_pool_id = h->get_host_pool();
#endif
if(up->update_pool_id)
h->updateHostPool();
if(up->update_l7policy)
h->updateHostL7Policy();
#ifdef HOST_POOLS_DEBUG
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"Going to refresh pool for %s "
"[refresh pool id: %i] "
"[refresh l7policy: %i] "
"[host pool id before refresh: %i] "
"[host pool id after refresh: %i] ",
h->get_ip()->print(buf, sizeof(buf)),
up->update_pool_id ? 1 : 0,
up->update_l7policy ? 1 : 0,
cur_pool_id,
h->get_host_pool());
#endif
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::refreshHostPools() {
if(isView()) return;
struct update_host_pool_l7policy update_host;
update_host.update_pool_id = true;
update_host.update_l7policy = false;
#ifdef NTOPNG_PRO
if(is_bridge_interface() && getL7Policer()) {
/* Every pool is associated with a set of L7 rules
so a refresh must be triggered to seal this association */
getL7Policer()->refreshL7Rules();
/* Must refresh host l7policies as a change in the host pool id
may determine an l7policy change for that host */
update_host.update_l7policy = true;
}
#endif
hosts_hash->walk(update_host_host_pool_l7policy, &update_host);
#ifdef NTOPNG_PRO
if(update_host.update_l7policy)
updateFlowsL7Policy();
#endif
}
/* **************************************************** */
#ifdef NTOPNG_PRO
/* **************************************************** */
static bool update_flow_l7_policy(GenericHashEntry *node, void *user_data) {
Flow *f = (Flow*)node;
f->updateFlowShapers();
f->updateProfile();
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::updateHostsL7Policy(u_int16_t host_pool_id) {
if(isView()) return;
struct update_host_pool_l7policy update_host;
update_host.update_pool_id = false;
update_host.update_l7policy = true;
hosts_hash->walk(update_host_host_pool_l7policy, &update_host);
}
/* **************************************************** */
void NetworkInterface::updateFlowsL7Policy() {
if(isView()) return;
flows_hash->walk(update_flow_l7_policy, NULL);
}
#endif
/* **************************************************** */
struct host_find_info {
char *host_to_find;
u_int16_t vlan_id;
Host *h;
};
/* **************************************************** */
struct mac_find_info {
u_int8_t mac[6];
u_int16_t vlan_id;
Mac *m;
};
/* **************************************************** */
static bool find_host_by_name(GenericHashEntry *h, void *user_data) {
struct host_find_info *info = (struct host_find_info*)user_data;
Host *host = (Host*)h;
#ifdef DEBUG
char buf[64];
ntop->getTrace()->traceEvent(TRACE_WARNING, "[%s][%s][%s]",
host->get_ip() ? host->get_ip()->print(buf, sizeof(buf)) : "",
host->get_name(), info->host_to_find);
#endif
if((info->h == NULL) && (host->get_vlan_id() == info->vlan_id)) {
if((host->get_name() == NULL) && host->get_ip()) {
char ip_buf[32], name_buf[96];
char *ipaddr = host->get_ip()->print(ip_buf, sizeof(ip_buf));
int rc = ntop->getRedis()->getAddress(ipaddr, name_buf, sizeof(name_buf),
false /* Don't resolve it if not known */);
if(rc == 0 /* found */) host->setName(name_buf);
}
if(host->get_name() && (!strcmp(host->get_name(), info->host_to_find))) {
info->h = host;
return(true); /* found */
}
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool find_mac_by_name(GenericHashEntry *h, void *user_data) {
struct mac_find_info *info = (struct mac_find_info*)user_data;
Mac *m = (Mac*)h;
if((info->m == NULL)
&& (m->get_vlan_id() == info->vlan_id)
&& (!memcmp(info->mac, m->get_mac(), 6))
) {
info->m = m;
return(true); /* found */
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
bool NetworkInterface::restoreHost(char *host_ip, u_int16_t vlan_id) {
Host *h = new Host(this, host_ip, vlan_id);
if(!h) return(false);
if(!hosts_hash->add(h)) {
//ntop->getTrace()->traceEvent(TRACE_WARNING, "Too many hosts in interface %s", ifname);
delete h;
return(false);
}
return(true);
}
/* **************************************************** */
Host* NetworkInterface::getHost(char *host_ip, u_int16_t vlan_id) {
struct in_addr a4;
struct in6_addr a6;
Host *h = NULL;
/* Check if address is invalid */
if((inet_pton(AF_INET, (const char*)host_ip, &a4) == 0)
&& (inet_pton(AF_INET6, (const char*)host_ip, &a6) == 0)) {
/* Looks like a symbolic name */
struct host_find_info info;
memset(&info, 0, sizeof(info));
info.host_to_find = host_ip, info.vlan_id = vlan_id;
walker(walker_hosts, find_host_by_name, (void*)&info);
h = info.h;
} else {
IpAddress *ip = new IpAddress();
if(ip) {
ip->set(host_ip);
if(!isView())
h = hosts_hash->get(vlan_id, ip);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
h = subInterfaces[s]->get_hosts_hash()->get(vlan_id, ip);
if(h) break;
}
}
delete ip;
}
}
return(h);
}
/* **************************************************** */
#ifdef NTOPNG_PRO
static bool update_flow_profile(GenericHashEntry *h, void *user_data) {
Flow *flow = (Flow*)h;
flow->updateProfile();
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::updateFlowProfiles() {
if(isView()) return;
if(ntop->getPro()->has_valid_license()) {
FlowProfiles *newP;
if(shadow_flow_profiles) {
delete shadow_flow_profiles;
shadow_flow_profiles = NULL;
}
flow_profiles->dumpCounters();
shadow_flow_profiles = flow_profiles, newP = new FlowProfiles(id);
newP->loadProfiles(); /* and reload */
flow_profiles = newP; /* Overwrite the current profiles */
flows_hash->walk(update_flow_profile, NULL);
}
}
#endif
/* **************************************************** */
bool NetworkInterface::getHostInfo(lua_State* vm,
AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
Host *h = findHostsByIP(allowed_hosts, host_ip, vlan_id);
if(h) {
h->lua(vm, allowed_hosts, true, true, true, false, false);
return(true);
} else
return(false);
}
/* **************************************************** */
bool NetworkInterface::loadHostAlertPrefs(lua_State* vm,
AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
Host *h = findHostsByIP(allowed_hosts, host_ip, vlan_id);
if(h) {
h->loadAlertPrefs();
return(true);
}
return(false);
}
/* **************************************************** */
Host* NetworkInterface::findHostsByIP(AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
if(host_ip != NULL) {
Host *h = getHost(host_ip, vlan_id);
if(h && h->match(allowed_hosts))
return(h);
}
return(NULL);
}
/* **************************************************** */
struct flowHostRetrieveList {
Flow *flow;
/* Value */
Host *hostValue;
Mac *macValue;
u_int64_t numericValue;
char *stringValue;
};
struct flowHostRetriever {
/* Search criteria */
AddressTree *allowed_hosts;
Host *host;
Mac *mac;
char *manufacturer;
bool skipSpecialMacs, hostMacsOnly;
char *country;
int ndpi_proto;
sortField sorter;
LocationPolicy location;
u_int16_t *vlan_id;
char *osFilter;
u_int32_t *asnFilter;
int16_t *networkFilter;
u_int16_t *poolFilter;
/* Return values */
u_int32_t maxNumEntries, actNumEntries;
struct flowHostRetrieveList *elems;
/* Paginator */
Paginator *pag;
};
/* **************************************************** */
static bool flow_search_walker(GenericHashEntry *h, void *user_data) {
struct flowHostRetriever *retriever = (struct flowHostRetriever*)user_data;
Flow *f = (Flow*)h;
int ndpi_proto;
u_int16_t port;
int16_t local_network_id;
if(retriever->actNumEntries >= retriever->maxNumEntries)
return(true); /* Limit reached */
if(f && (!f->idle())) {
if(retriever->host
&& (retriever->host != f->get_cli_host())
&& (retriever->host != f->get_srv_host()))
return(false); /* false = keep on walking */
if(retriever->pag
&& retriever->pag->l7protoFilter(&ndpi_proto)
&& ndpi_proto != -1
&& (f->get_detected_protocol().protocol != ndpi_proto)
&& (f->get_detected_protocol().master_protocol != ndpi_proto))
return(false); /* false = keep on walking */
if(retriever->pag
&& retriever->pag->portFilter(&port)
&& f->get_cli_port() != port
&& f->get_srv_port() != port)
return(false); /* false = keep on walking */
if(retriever->pag
&& retriever->pag->localNetworkFilter(&local_network_id)
&& f->get_cli_host()->get_local_network_id() != local_network_id
&& f->get_srv_host()->get_local_network_id() != local_network_id)
return(false); /* false = keep on walking */
if(retriever->location == location_local_only) {
if((!f->get_cli_host()->isLocalHost())
|| (!f->get_srv_host()->isLocalHost()))
return(false); /* false = keep on walking */
} else if(retriever->location == location_remote_only) {
if((f->get_cli_host()->isLocalHost())
|| (f->get_srv_host()->isLocalHost()))
return(false); /* false = keep on walking */
}
retriever->elems[retriever->actNumEntries].flow = f;
if(f->match(retriever->allowed_hosts)) {
switch(retriever->sorter) {
case column_client:
retriever->elems[retriever->actNumEntries++].hostValue = f->get_cli_host();
break;
case column_server:
retriever->elems[retriever->actNumEntries++].hostValue = f->get_srv_host();
break;
case column_vlan:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_vlan_id();
break;
case column_proto_l4:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_protocol();
break;
case column_ndpi:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_detected_protocol().protocol;
break;
case column_duration:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_duration();
break;
case column_thpt:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_bytes_thpt();
break;
case column_bytes:
retriever->elems[retriever->actNumEntries++].numericValue = f->get_bytes();
break;
case column_info:
if(f->getDNSQuery()) retriever->elems[retriever->actNumEntries++].stringValue = f->getDNSQuery();
else if(f->getHTTPURL()) retriever->elems[retriever->actNumEntries++].stringValue = f->getHTTPURL();
else if(f->getSSLCertificate()) retriever->elems[retriever->actNumEntries++].stringValue = f->getSSLCertificate();
else retriever->elems[retriever->actNumEntries++].stringValue = (char*)"";
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Internal error: column %d not handled", retriever->sorter);
break;
}
}
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool host_search_walker(GenericHashEntry *he, void *user_data) {
char buf[64];
struct flowHostRetriever *r = (struct flowHostRetriever*)user_data;
Host *h = (Host*)he;
if(r->actNumEntries >= r->maxNumEntries)
return(true); /* Limit reached */
if(!h || h->idle() || !h->match(r->allowed_hosts))
return(false);
if((r->location == location_local_only && !h->isLocalHost()) ||
(r->location == location_remote_only && h->isLocalHost()) ||
(r->vlan_id && *(r->vlan_id) != h->get_vlan_id()) ||
(r->asnFilter && *(r->asnFilter) != h->get_asn()) ||
(r->networkFilter && *(r->networkFilter) != h->get_local_network_id()) ||
(r->networkFilter && *(r->networkFilter) != h->get_local_network_id()) ||
(r->hostMacsOnly && h->getMac() && h->getMac()->isSpecialMac()) ||
(r->mac && (h->getMac() != r->mac)) ||
(r->poolFilter && *(r->poolFilter) != h->get_host_pool()) ||
(r->country && strlen(r->country) && (!h->get_country() || strcmp(h->get_country(), r->country))) ||
(r->osFilter && strlen(r->osFilter) && (!h->get_os() || strcmp(h->get_os(), r->osFilter))))
return(false); /* false = keep on walking */
r->elems[r->actNumEntries].hostValue = h;
switch(r->sorter) {
case column_ip:
r->elems[r->actNumEntries++].hostValue = h; /* hostValue was already set */
break;
case column_alerts:
r->elems[r->actNumEntries++].numericValue = h->getNumAlerts();
break;
case column_name:
r->elems[r->actNumEntries++].stringValue = strdup(h->get_name(buf, sizeof(buf), false));
break;
case column_country:
r->elems[r->actNumEntries++].stringValue = strdup(h->get_country() ? h->get_country() : (char*)"");
break;
case column_os:
r->elems[r->actNumEntries++].stringValue = strdup(h->get_os() ? h->get_os() : (char*)"");
break;
case column_vlan:
r->elems[r->actNumEntries++].numericValue = h->get_vlan_id();
break;
case column_since:
r->elems[r->actNumEntries++].numericValue = h->get_first_seen();
break;
case column_asn:
r->elems[r->actNumEntries++].numericValue = h->get_asn();
break;
case column_thpt:
r->elems[r->actNumEntries++].numericValue = h->getBytesThpt();
break;
case column_num_flows:
r->elems[r->actNumEntries++].numericValue = h->getNumActiveFlows();
break;
case column_traffic:
r->elems[r->actNumEntries++].numericValue = h->getNumBytes();
break;
case column_local_network_id:
r->elems[r->actNumEntries++].numericValue = h->get_local_network_id();
break;
case column_mac:
r->elems[r->actNumEntries++].numericValue = Utils::macaddr_int(h->get_mac());
break;
case column_pool_id:
r->elems[r->actNumEntries++].numericValue = h->get_host_pool();
break;
/* Criteria */
case column_uploaders: r->elems[r->actNumEntries++].numericValue = h->getNumBytesSent(); break;
case column_downloaders: r->elems[r->actNumEntries++].numericValue = h->getNumBytesRcvd(); break;
case column_unknowers: r->elems[r->actNumEntries++].numericValue = h->get_ndpi_stats()->getProtoBytes(NDPI_PROTOCOL_UNKNOWN); break;
case column_incomingflows: r->elems[r->actNumEntries++].numericValue = h->getNumIncomingFlows(); break;
case column_outgoingflows: r->elems[r->actNumEntries++].numericValue = h->getNumOutgoingFlows(); break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Internal error: column %d not handled", r->sorter);
break;
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
static bool mac_search_walker(GenericHashEntry *he, void *user_data) {
struct flowHostRetriever *r = (struct flowHostRetriever*)user_data;
Mac *m = (Mac*)he;
if(r->actNumEntries >= r->maxNumEntries)
return(true); /* Limit reached */
if(!m
|| m->idle()
|| ((r->vlan_id && (*(r->vlan_id) != m->get_vlan_id())))
|| (r->skipSpecialMacs && m->isSpecialMac())
|| (r->hostMacsOnly && m->getNumHosts() == 0))
return(false); /* false = keep on walking */
r->elems[r->actNumEntries].macValue = m;
switch(r->sorter) {
case column_mac:
r->elems[r->actNumEntries++].numericValue = Utils::macaddr_int(m->get_mac());
break;
case column_vlan:
r->elems[r->actNumEntries++].numericValue = m->get_vlan_id();
break;
case column_since:
r->elems[r->actNumEntries++].numericValue = m->get_first_seen();
break;
case column_thpt:
r->elems[r->actNumEntries++].numericValue = m->getBytesThpt();
break;
case column_traffic:
r->elems[r->actNumEntries++].numericValue = m->getNumBytes();
break;
case column_num_hosts:
r->elems[r->actNumEntries++].numericValue = m->getNumHosts();
break;
case column_manufacturer:
r->elems[r->actNumEntries++].stringValue = m->get_manufacturer() ? (char*)m->get_manufacturer() : (char*)"zzz";
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Internal error: column %d not handled", r->sorter);
break;
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
int hostSorter(const void *_a, const void *_b) {
struct flowHostRetrieveList *a = (struct flowHostRetrieveList*)_a;
struct flowHostRetrieveList *b = (struct flowHostRetrieveList*)_b;
return(a->hostValue->get_ip()->compare(b->hostValue->get_ip()));
}
int numericSorter(const void *_a, const void *_b) {
struct flowHostRetrieveList *a = (struct flowHostRetrieveList*)_a;
struct flowHostRetrieveList *b = (struct flowHostRetrieveList*)_b;
if(a->numericValue < b->numericValue) return(-1);
else if(a->numericValue > b->numericValue) return(1);
else return(0);
}
int stringSorter(const void *_a, const void *_b) {
struct flowHostRetrieveList *a = (struct flowHostRetrieveList*)_a;
struct flowHostRetrieveList *b = (struct flowHostRetrieveList*)_b;
return(strcmp(a->stringValue, b->stringValue));
}
/* **************************************************** */
void NetworkInterface::disablePurge(bool on_flows) {
if(!isView()) {
if(on_flows)
flows_hash->disablePurge();
else {
hosts_hash->disablePurge();
macs_hash->disablePurge();
}
} else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
if(on_flows)
subInterfaces[s]->get_flows_hash()->disablePurge();
else {
subInterfaces[s]->get_hosts_hash()->disablePurge();
subInterfaces[s]->get_macs_hash()->disablePurge();
}
}
}
}
/* **************************************************** */
void NetworkInterface::enablePurge(bool on_flows) {
if(!isView()) {
if(on_flows)
flows_hash->enablePurge();
else {
hosts_hash->enablePurge();
macs_hash->enablePurge();
}
} else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
if(on_flows)
subInterfaces[s]->get_flows_hash()->enablePurge();
else {
subInterfaces[s]->get_hosts_hash()->enablePurge();
subInterfaces[s]->get_macs_hash()->enablePurge();
}
}
}
}
/* **************************************************** */
int NetworkInterface::getFlows(lua_State* vm,
AddressTree *allowed_hosts,
Host *host, int ndpi_proto,
LocationPolicy location,
char *sortColumn,
u_int32_t maxHits,
u_int32_t toSkip,
bool a2zSortOrder) {
struct flowHostRetriever retriever;
int (*sorter)(const void *_a, const void *_b);
DetailsLevel highDetails = (location == location_local_only || (maxHits != CONST_MAX_NUM_HITS)) ? details_high : details_normal;
if((maxHits > CONST_MAX_NUM_HITS) || (maxHits == 0)) maxHits = CONST_MAX_NUM_HITS;
retriever.pag = NULL;
retriever.host = host, retriever.ndpi_proto = ndpi_proto, retriever.location = location;
retriever.actNumEntries = 0, retriever.maxNumEntries = getFlowsHashSize(), retriever.allowed_hosts = allowed_hosts;
retriever.elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever.maxNumEntries);
if(retriever.elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
if(!strcmp(sortColumn, "column_client")) retriever.sorter = column_client, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_vlan")) retriever.sorter = column_vlan, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_server")) retriever.sorter = column_server, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_proto_l4")) retriever.sorter = column_proto_l4, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_ndpi")) retriever.sorter = column_ndpi, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_duration")) retriever.sorter = column_duration, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_thpt")) retriever.sorter = column_thpt, sorter = numericSorter;
else if((!strcmp(sortColumn, "column_bytes")) || (!strcmp(sortColumn, "column_") /* default */)) retriever.sorter = column_bytes, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_info")) retriever.sorter = column_info, sorter = stringSorter;
else ntop->getTrace()->traceEvent(TRACE_WARNING, "Unknown sort column %s", sortColumn), sorter = numericSorter;
/* ******************************* */
disablePurge(true);
walker(walker_flows, flow_search_walker, (void*)&retriever);
qsort(retriever.elems, retriever.actNumEntries, sizeof(struct flowHostRetrieveList), sorter);
lua_newtable(vm);
if(a2zSortOrder) {
for(int i=toSkip, num=0; i<(int)retriever.actNumEntries; i++) {
lua_newtable(vm);
retriever.elems[i].flow->lua(vm, allowed_hosts, highDetails, true);
lua_pushnumber(vm, num + 1);
lua_insert(vm, -2);
lua_settable(vm, -3);
if(++num >= (int)maxHits) break;
}
} else {
for(int i=(retriever.actNumEntries-1-toSkip), num=0; i>=0; i--) {
lua_newtable(vm);
retriever.elems[i].flow->lua(vm, allowed_hosts, highDetails, true);
lua_pushnumber(vm, num + 1);
lua_insert(vm, -2);
lua_settable(vm, -3);
if(++num >= (int)maxHits) break;
}
}
enablePurge(true);
free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
int NetworkInterface::getFlows(lua_State* vm,
AddressTree *allowed_hosts,
LocationPolicy location, Host *host,
Paginator *p) {
struct flowHostRetriever retriever;
int (*sorter)(const void *_a, const void *_b);
char sortColumn[32];
DetailsLevel highDetails;
if(p == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unable to return results with a NULL paginator");
return(-1);
}
highDetails = p->detailedResults() ? details_high : (location == location_local_only || (p && p->maxHits() != CONST_MAX_NUM_HITS)) ? details_high : details_normal;
retriever.pag = p;
retriever.host = host, retriever.location = location;
retriever.actNumEntries = 0, retriever.maxNumEntries = getFlowsHashSize(), retriever.allowed_hosts = allowed_hosts;
retriever.elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever.maxNumEntries);
if(retriever.elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
snprintf(sortColumn, sizeof(sortColumn), "%s", p->sortColumn());
if(!strcmp(sortColumn, "column_client")) retriever.sorter = column_client, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_vlan")) retriever.sorter = column_vlan, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_server")) retriever.sorter = column_server, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_proto_l4")) retriever.sorter = column_proto_l4, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_ndpi")) retriever.sorter = column_ndpi, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_duration")) retriever.sorter = column_duration, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_thpt")) retriever.sorter = column_thpt, sorter = numericSorter;
else if((!strcmp(sortColumn, "column_bytes")) || (!strcmp(sortColumn, "column_") /* default */)) retriever.sorter = column_bytes, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_info")) retriever.sorter = column_info, sorter = stringSorter;
else {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unknown sort column %s", sortColumn);
retriever.sorter = column_bytes, sorter = numericSorter;
}
/* ******************************* */
disablePurge(true);
walker(walker_flows, flow_search_walker, (void*)&retriever);
qsort(retriever.elems, retriever.actNumEntries, sizeof(struct flowHostRetrieveList), sorter);
lua_newtable(vm);
lua_push_int_table_entry(vm, "numFlows", retriever.actNumEntries);
lua_newtable(vm);
if(p->a2zSortOrder()) {
for(int i=p->toSkip(), num=0; i<(int)retriever.actNumEntries; i++) {
lua_newtable(vm);
retriever.elems[i].flow->lua(vm, allowed_hosts, highDetails, true);
lua_pushnumber(vm, num + 1);
lua_insert(vm, -2);
lua_settable(vm, -3);
if(++num >= (int)p->maxHits()) break;
}
} else {
for(int i=(retriever.actNumEntries-1-p->toSkip()), num=0; i>=0; i--) {
lua_newtable(vm);
retriever.elems[i].flow->lua(vm, allowed_hosts, highDetails, true);
lua_pushnumber(vm, num + 1);
lua_insert(vm, -2);
lua_settable(vm, -3);
if(++num >= (int)p->maxHits()) break;
}
}
lua_pushstring(vm, "flows");
lua_insert(vm, -2);
lua_settable(vm, -3);
enablePurge(true);
free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
int NetworkInterface::getLatestActivityHostsList(lua_State* vm, AddressTree *allowed_hosts) {
struct flowHostRetriever retriever;
memset(&retriever, 0, sizeof(retriever));
// there's not even the need to use the retriever or to sort results here
// we use the retriever just to leverage on the exising code.
retriever.allowed_hosts = allowed_hosts, retriever.location = location_all;
retriever.actNumEntries = 0, retriever.maxNumEntries = getHostsHashSize();
retriever.sorter = column_vlan; // just a placeholder, we don't care as we won't sort
retriever.elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever.maxNumEntries);
if(retriever.elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
disablePurge(false);
walker(walker_hosts, host_search_walker, (void*)&retriever);
lua_newtable(vm);
if(retriever.actNumEntries > 0) {
for(int i=0; i<(int)retriever.actNumEntries; i++) {
Host *h = retriever.elems[i].hostValue;
if(i < CONST_MAX_NUM_HITS)
h->lua(vm, NULL /* Already checked */,
false /* host details */,
false /* verbose */,
false /* return host */,
true /* as list element*/,
true /* exclude deserialized bytes */);
}
}
enablePurge(false);
free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
int NetworkInterface::sortHosts(struct flowHostRetriever *retriever,
AddressTree *allowed_hosts,
bool host_details,
LocationPolicy location,
char *countryFilter, char *mac_filter,
u_int16_t *vlan_id, char *osFilter,
u_int32_t *asnFilter, int16_t *networkFilter,
u_int16_t *pool_filter,
bool hostMacsOnly, char *sortColumn) {
u_int32_t maxHits;
int (*sorter)(const void *_a, const void *_b);
if(retriever == NULL)
return -1;
maxHits = getHostsHashSize();
if((maxHits > CONST_MAX_NUM_HITS) || (maxHits == 0))
maxHits = CONST_MAX_NUM_HITS;
memset(retriever, 0, sizeof(struct flowHostRetriever));
if(mac_filter) {
u_int8_t macAddr[6];
Utils::parseMac(macAddr, mac_filter);
retriever->mac = macs_hash->get(vlan_id ? *vlan_id : 0, (const u_int8_t*)macAddr);
}
retriever->allowed_hosts = allowed_hosts, retriever->location = location,
retriever->country = countryFilter, retriever->vlan_id = vlan_id,
retriever->osFilter = osFilter, retriever->asnFilter = asnFilter,
retriever->networkFilter = networkFilter, retriever->actNumEntries = 0,
retriever->poolFilter = pool_filter;
retriever->maxNumEntries = maxHits, retriever->hostMacsOnly = hostMacsOnly;
retriever->elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever->maxNumEntries);
if(retriever->elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
if((!strcmp(sortColumn, "column_ip")) || (!strcmp(sortColumn, "column_"))) retriever->sorter = column_ip, sorter = hostSorter;
else if(!strcmp(sortColumn, "column_vlan")) retriever->sorter = column_vlan, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_alerts")) retriever->sorter = column_alerts, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_name")) retriever->sorter = column_name, sorter = stringSorter;
else if(!strcmp(sortColumn, "column_country")) retriever->sorter = column_country, sorter = stringSorter;
else if(!strcmp(sortColumn, "column_os")) retriever->sorter = column_os, sorter = stringSorter;
else if(!strcmp(sortColumn, "column_since")) retriever->sorter = column_since, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_asn")) retriever->sorter = column_asn, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_thpt")) retriever->sorter = column_thpt, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_num_flows")) retriever->sorter = column_num_flows, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_traffic")) retriever->sorter = column_traffic, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_local_network_id")) retriever->sorter = column_local_network_id, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_mac")) retriever->sorter = column_mac, sorter = numericSorter;
/* criteria (datatype sortField in ntop_typedefs.h / see also host_search_walker:NetworkInterface.cpp) */
else if(!strcmp(sortColumn, "column_uploaders")) retriever->sorter = column_uploaders, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_downloaders")) retriever->sorter = column_downloaders, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_unknowers")) retriever->sorter = column_unknowers, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_incomingflows")) retriever->sorter = column_incomingflows, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_outgoingflows")) retriever->sorter = column_outgoingflows, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_pool_id")) retriever->sorter = column_pool_id, sorter = numericSorter;
else {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Unknown sort column %s", sortColumn);
retriever->sorter = column_traffic, sorter = numericSorter;
}
// make sure the caller has disabled the purge!!
walker(walker_hosts, host_search_walker, (void*)retriever);
qsort(retriever->elems, retriever->actNumEntries, sizeof(struct flowHostRetrieveList), sorter);
return(retriever->actNumEntries);
}
/* **************************************************** */
int NetworkInterface::sortMacs(struct flowHostRetriever *retriever,
u_int16_t vlan_id, bool skipSpecialMacs,
bool hostMacsOnly,
char *sortColumn) {
u_int32_t maxHits;
int (*sorter)(const void *_a, const void *_b);
if(retriever == NULL)
return -1;
maxHits = getMacsHashSize();
if((maxHits > CONST_MAX_NUM_HITS) || (maxHits == 0))
maxHits = CONST_MAX_NUM_HITS;
retriever->vlan_id = &vlan_id, retriever->skipSpecialMacs = skipSpecialMacs,
retriever->hostMacsOnly = hostMacsOnly, retriever->actNumEntries = 0,
retriever->maxNumEntries = maxHits,
retriever->elems = (struct flowHostRetrieveList*)calloc(sizeof(struct flowHostRetrieveList), retriever->maxNumEntries);
if(retriever->elems == NULL) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Out of memory :-(");
return(-1);
}
if((!strcmp(sortColumn, "column_mac")) || (!strcmp(sortColumn, "column_"))) retriever->sorter = column_mac, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_vlan")) retriever->sorter = column_vlan, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_since")) retriever->sorter = column_since, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_thpt")) retriever->sorter = column_thpt, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_traffic")) retriever->sorter = column_traffic, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_hosts")) retriever->sorter = column_num_hosts, sorter = numericSorter;
else if(!strcmp(sortColumn, "column_manufacturer")) retriever->sorter = column_manufacturer, sorter = stringSorter;
else ntop->getTrace()->traceEvent(TRACE_WARNING, "Unknown sort column %s", sortColumn), sorter = numericSorter;
// make sure the caller has disabled the purge!!
walker(walker_macs, mac_search_walker, (void*)retriever);
qsort(retriever->elems, retriever->actNumEntries, sizeof(struct flowHostRetrieveList), sorter);
return(retriever->actNumEntries);
}
/* **************************************************** */
int NetworkInterface::getActiveHostsList(lua_State* vm, AddressTree *allowed_hosts,
bool host_details, LocationPolicy location,
char *countryFilter, char *mac_filter,
u_int16_t *vlan_id, char *osFilter,
u_int32_t *asnFilter, int16_t *networkFilter,
u_int16_t *pool_filter,
char *sortColumn, u_int32_t maxHits,
u_int32_t toSkip, bool a2zSortOrder) {
struct flowHostRetriever retriever;
disablePurge(false);
if(sortHosts(&retriever, allowed_hosts, host_details, location,
countryFilter, mac_filter, vlan_id, osFilter,
asnFilter, networkFilter, pool_filter, true, sortColumn) < 0) {
enablePurge(false);
return -1;
}
lua_newtable(vm);
lua_push_int_table_entry(vm, "numHosts", retriever.actNumEntries);
lua_newtable(vm);
if(a2zSortOrder) {
for(int i = toSkip, num=0; i<(int)retriever.actNumEntries && num < (int)maxHits; i++, num++) {
Host *h = retriever.elems[i].hostValue;
h->lua(vm, NULL /* Already checked */, host_details, false, false, true, false);
}
} else {
for(int i = (retriever.actNumEntries-1-toSkip), num=0; i >= 0 && num < (int)maxHits; i--, num++) {
Host *h = retriever.elems[i].hostValue;
h->lua(vm, NULL /* Already checked */, host_details, false, false, true, false);
}
}
lua_pushstring(vm, "hosts");
lua_insert(vm, -2);
lua_settable(vm, -3);
enablePurge(false);
// it's up to us to clean sorted data
// make sure first to free elements in case a string sorter has been used
if(retriever.sorter == column_name
|| retriever.sorter == column_country
|| retriever.sorter == column_os) {
for(u_int i=0; i<retriever.maxNumEntries; i++)
if(retriever.elems[i].stringValue)
free(retriever.elems[i].stringValue);
}
// finally free the elements regardless of the sorted kind
if(retriever.elems) free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
int NetworkInterface::getActiveHostsGroup(lua_State* vm, AddressTree *allowed_hosts,
bool host_details, LocationPolicy location,
char *countryFilter,
u_int16_t *vlan_id, char *osFilter,
u_int32_t *asnFilter, int16_t *networkFilter,
u_int16_t *pool_filter,
bool local_macs, char *groupColumn) {
struct flowHostRetriever retriever;
Grouper *gper;
disablePurge(false);
// sort hosts according to the grouping criterion
if(sortHosts(&retriever, allowed_hosts, host_details, location,
countryFilter, NULL /* Mac */, vlan_id,
osFilter, asnFilter, networkFilter, pool_filter,
local_macs, groupColumn) < 0 ) {
enablePurge(false);
return -1;
}
// build a new grouper that will help in aggregating stats
if((gper = new(std::nothrow) Grouper(retriever.sorter)) == NULL) {
ntop->getTrace()->traceEvent(TRACE_ERROR,
"Unable to allocate memory for a Grouper.");
enablePurge(false);
return -1;
}
lua_newtable(vm);
for(int i=0; i<(int)retriever.actNumEntries; i++) {
Host *h = retriever.elems[i].hostValue;
if(h) {
if(gper->inGroup(h) == false) {
if(gper->getNumEntries() > 0)
gper->lua(vm);
gper->newGroup(h);
}
gper->incStats(h);
}
}
if(gper->getNumEntries() > 0)
gper->lua(vm);
delete gper;
gper = NULL;
enablePurge(false);
// it's up to us to clean sorted data
// make sure first to free elements in case a string sorter has been used
if((retriever.sorter == column_name)
|| (retriever.sorter == column_country)
|| (retriever.sorter == column_os)) {
for(u_int i=0; i<retriever.maxNumEntries; i++)
if(retriever.elems[i].stringValue)
free(retriever.elems[i].stringValue);
}
// finally free the elements regardless of the sorted kind
if(retriever.elems) free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************************** */
static bool flow_stats_walker(GenericHashEntry *h, void *user_data) {
struct active_flow_stats *stats = (struct active_flow_stats*)user_data;
Flow *flow = (Flow*)h;
stats->num_flows++,
stats->ndpi_bytes[flow->get_detected_protocol().protocol] += (u_int32_t)flow->get_bytes(),
stats->breeds_bytes[flow->get_protocol_breed()] += (u_int32_t)flow->get_bytes();
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::getFlowsStats(lua_State* vm) {
struct active_flow_stats stats;
memset(&stats, 0, sizeof(stats));
walker(walker_flows, flow_stats_walker, (void*)&stats);
lua_newtable(vm);
lua_push_int_table_entry(vm, "num_flows", stats.num_flows);
lua_newtable(vm);
for(int i=0; i<NDPI_MAX_SUPPORTED_PROTOCOLS+NDPI_MAX_NUM_CUSTOM_PROTOCOLS; i++) {
if(stats.ndpi_bytes[i] > 0)
lua_push_int_table_entry(vm,
ndpi_get_proto_name(get_ndpi_struct(), i),
stats.ndpi_bytes[i]);
}
lua_pushstring(vm, "protos");
lua_insert(vm, -2);
lua_settable(vm, -3);
lua_newtable(vm);
for(int i=0; i<NUM_BREEDS; i++) {
if(stats.breeds_bytes[i] > 0)
lua_push_int_table_entry(vm,
ndpi_get_proto_breed_name(get_ndpi_struct(),
(ndpi_protocol_breed_t)i),
stats.breeds_bytes[i]);
}
lua_pushstring(vm, "breeds");
lua_insert(vm, -2);
lua_settable(vm, -3);
}
/* **************************************************** */
void NetworkInterface::getNetworksStats(lua_State* vm) {
NetworkStats *network_stats;
u_int8_t num_local_networks = ntop->getNumLocalNetworks();
lua_newtable(vm);
for(u_int8_t network_id = 0; network_id < num_local_networks; network_id++) {
network_stats = getNetworkStats(network_id);
// do not add stats of networks that have not generated any traffic
if(!network_stats || !network_stats->trafficSeen())
continue;
lua_newtable(vm);
network_stats->lua(vm);
lua_push_int32_table_entry(vm, "network_id", network_id);
lua_pushstring(vm, ntop->getLocalNetworkName(network_id));
lua_insert(vm, -2);
lua_settable(vm, -3);
}
}
/* **************************************************** */
static bool host_activity_walker(GenericHashEntry *he, void *user_data) {
HostActivityRetriever * r = (HostActivityRetriever *)user_data;
Host *h = (Host*)he;
int i;
if(!h
|| !h->equal(&r->search)
|| (!h->get_user_activities()))
return(false); /* false = keep on walking */
r->found = true;
for(i=0; i<UserActivitiesN; i++)
r->counters[i] = *h->getActivityBytes((UserActivityID)i);
return true; /* found, stop walking */
}
/* **************************************************** */
void NetworkInterface::getLocalHostActivity(lua_State* vm, const char *host) {
HostActivityRetriever retriever(host);
int i;
disablePurge(false);
walker(walker_hosts, host_activity_walker, &retriever);
enablePurge(false);
if(retriever.found) {
lua_newtable(vm);
for(i=0; i<UserActivitiesN; i++) {
lua_newtable(vm);
lua_push_int_table_entry(vm, "up", retriever.counters[i].up);
lua_push_int_table_entry(vm, "down", retriever.counters[i].down);
lua_push_int_table_entry(vm, "background", retriever.counters[i].background);
lua_pushstring(vm, activity_names[i]);
lua_insert(vm, -2);
lua_settable(vm, -3);
}
} else
lua_pushnil(vm);
}
/* **************************************************** */
u_int NetworkInterface::purgeIdleFlows() {
if(!purge_idle_flows_hosts) return(0);
if(next_idle_flow_purge == 0) {
next_idle_flow_purge = last_pkt_rcvd + FLOW_PURGE_FREQUENCY;
return(0);
} else if(last_pkt_rcvd < next_idle_flow_purge)
return(0); /* Too early */
else {
/* Time to purge flows */
u_int n;
// ntop->getTrace()->traceEvent(TRACE_INFO, "Purging idle flows");
n = flows_hash->purgeIdle();
if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
// flush the queue
db->flush(true /* idle */);
}
next_idle_flow_purge = last_pkt_rcvd + FLOW_PURGE_FREQUENCY;
return(n);
}
}
/* **************************************************** */
u_int64_t NetworkInterface::getNumPackets() {
u_int64_t tot = ethStats.getNumPackets();
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumPackets();
return(tot);
};
/* **************************************************** */
u_int64_t NetworkInterface::getNumBytes() {
u_int64_t tot = ethStats.getNumBytes();
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumBytes();
return(tot);
}
/* **************************************************** */
u_int32_t NetworkInterface::getNumPacketDrops() {
u_int32_t tot = getNumDroppedPackets();
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumDroppedPackets();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::getNumFlows() {
u_int tot = flows_hash ? flows_hash->getNumEntries() : 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumFlows();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::getNumHosts() {
u_int tot = hosts_hash ? hosts_hash->getNumEntries() : 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumHosts();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::getNumHTTPHosts() {
u_int tot = hosts_hash ? hosts_hash->getNumHTTPEntries() : 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumHTTPHosts();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::getNumMacs() {
u_int tot = macs_hash ? macs_hash->getNumEntries() : 0;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getNumMacs();
return(tot);
};
/* **************************************************** */
u_int NetworkInterface::purgeIdleHostsMacs() {
if(!purge_idle_flows_hosts) return(0);
if(next_idle_host_purge == 0) {
next_idle_host_purge = last_pkt_rcvd + HOST_PURGE_FREQUENCY;
return(0);
} else if(last_pkt_rcvd < next_idle_host_purge)
return(0); /* Too early */
else {
/* Time to purge hosts */
u_int n;
// ntop->getTrace()->traceEvent(TRACE_INFO, "Purging idle hosts");
n = hosts_hash->purgeIdle() + macs_hash->purgeIdle();
next_idle_host_purge = last_pkt_rcvd + HOST_PURGE_FREQUENCY;
return(n);
}
}
/* *************************************** */
void NetworkInterface::getnDPIProtocols(lua_State *vm) {
int i;
lua_newtable(vm);
for(i=0; i<(int)ndpi_struct->ndpi_num_supported_protocols; i++) {
char buf[8];
snprintf(buf, sizeof(buf), "%d", i);
lua_push_str_table_entry(vm, ndpi_struct->proto_defaults[i].protoName, buf);
}
}
/* **************************************************** */
void NetworkInterface::getnDPIProtocols(lua_State *vm, ndpi_protocol_category_t filter) {
int i;
lua_newtable(vm);
for(i=0; i<(int)ndpi_struct->ndpi_num_supported_protocols; i++) {
char buf[8];
if (ndpi_struct->proto_defaults[i].protoCategory == filter) {
snprintf(buf, sizeof(buf), "%d", i);
lua_push_str_table_entry(vm, ndpi_struct->proto_defaults[i].protoName, buf);
}
}
}
/* **************************************************** */
#define NUM_TCP_STATES 4
/*
0 = RST
1 = SYN
2 = Established
3 = FIN
*/
static bool num_flows_state_walker(GenericHashEntry *node, void *user_data) {
Flow *flow = (Flow*)node;
u_int32_t *num_flows = (u_int32_t*)user_data;
switch(flow->getFlowState()) {
case flow_state_syn:
num_flows[1]++;
break;
case flow_state_established:
num_flows[2]++;
break;
case flow_state_rst:
num_flows[0]++;
break;
case flow_state_fin:
num_flows[3]++;
break;
default:
/* UDP... */
break;
}
return(false /* keep walking */);
}
/* *************************************** */
static bool num_flows_walker(GenericHashEntry *node, void *user_data) {
Flow *flow = (Flow*)node;
u_int32_t *num_flows = (u_int32_t*)user_data;
num_flows[flow->get_detected_protocol().protocol]++;
return(false /* keep walking */);
}
/* *************************************** */
void NetworkInterface::getFlowsStatus(lua_State *vm) {
u_int32_t num_flows[NUM_TCP_STATES] = { 0 };
walker(walker_flows, num_flows_state_walker, num_flows);
lua_push_int_table_entry(vm, "RST", num_flows[0]);
lua_push_int_table_entry(vm, "SYN", num_flows[1]);
lua_push_int_table_entry(vm, "Established", num_flows[2]);
lua_push_int_table_entry(vm, "FIN", num_flows[3]);
}
/* *************************************** */
void NetworkInterface::getnDPIFlowsCount(lua_State *vm) {
u_int32_t *num_flows;
num_flows = (u_int32_t*)calloc(ndpi_struct->ndpi_num_supported_protocols, sizeof(u_int32_t));
if(num_flows) {
walker(walker_flows, num_flows_walker, num_flows);
for(int i=0; i<(int)ndpi_struct->ndpi_num_supported_protocols; i++) {
if(num_flows[i] > 0)
lua_push_int_table_entry(vm, ndpi_struct->proto_defaults[i].protoName, num_flows[i]);
}
free(num_flows);
}
}
/* *************************************** */
void NetworkInterface::sumStats(TcpFlowStats *_tcpFlowStats,
EthStats *_ethStats,
LocalTrafficStats *_localStats,
nDPIStats *_ndpiStats,
PacketStats *_pktStats,
TcpPacketStats *_tcpPacketStats) {
tcpFlowStats.sum(_tcpFlowStats), ethStats.sum(_ethStats), localStats.sum(_localStats),
ndpiStats.sum(_ndpiStats), pktStats.sum(_pktStats), tcpPacketStats.sum(_tcpPacketStats);
}
/* *************************************** */
void NetworkInterface::lua(lua_State *vm) {
TcpFlowStats _tcpFlowStats;
EthStats _ethStats;
LocalTrafficStats _localStats;
nDPIStats _ndpiStats;
PacketStats _pktStats;
TcpPacketStats _tcpPacketStats;
lua_newtable(vm);
lua_push_str_table_entry(vm, "name", ifname);
lua_push_int_table_entry(vm, "scalingFactor", scalingFactor);
lua_push_int_table_entry(vm, "id", id);
lua_push_bool_table_entry(vm, "isView", isView()); /* View interface */
lua_push_int_table_entry(vm, "seen.last", getTimeLastPktRcvd());
lua_push_bool_table_entry(vm, "sprobe", get_sprobe_interface());
lua_push_bool_table_entry(vm, "inline", get_inline_interface());
lua_push_bool_table_entry(vm, "vlan", get_has_vlan_packets());
if(remoteIfname) lua_push_str_table_entry(vm, "remote.name", remoteIfname);
if(remoteIfIPaddr) lua_push_str_table_entry(vm, "remote.if_addr", remoteIfIPaddr);
if(remoteProbeIPaddr) lua_push_str_table_entry(vm, "probe.ip", remoteProbeIPaddr);
if(remoteProbePublicIPaddr) lua_push_str_table_entry(vm, "probe.public_ip", remoteProbePublicIPaddr);
lua_newtable(vm);
lua_push_int_table_entry(vm, "packets", getNumPackets());
lua_push_int_table_entry(vm, "bytes", getNumBytes());
lua_push_int_table_entry(vm, "flows", getNumFlows());
lua_push_int_table_entry(vm, "hosts", getNumHosts());
lua_push_int_table_entry(vm, "http_hosts", getNumHTTPHosts());
lua_push_int_table_entry(vm, "drops", getNumPacketDrops());
lua_push_int_table_entry(vm, "devices", numL2Devices);
/* even if the counter is global, we put it here on every interface
as we may decide to make an elasticsearch thread per interface.
*/
if(ntop->getPrefs()->do_dump_flows_on_es()) {
ntop->getElasticSearch()->lua(vm, false /* Overall */);
} else if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
if(db) db->lua(vm, false /* Overall */);
}
lua_pushstring(vm, "stats");
lua_insert(vm, -2);
lua_settable(vm, -3);
lua_newtable(vm);
lua_push_int_table_entry(vm, "packets", getNumPackets() - getCheckPointNumPackets());
lua_push_int_table_entry(vm, "bytes", getNumBytes() - getCheckPointNumBytes());
lua_push_int_table_entry(vm, "drops", getNumPacketDrops() - getCheckPointNumPacketDrops());
if(ntop->getPrefs()->do_dump_flows_on_es()) {
ntop->getElasticSearch()->lua(vm, true /* Since last checkpoint */);
} else if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
if(db) db->lua(vm, true /* Since last checkpoint */);
}
lua_pushstring(vm, "stats_since_reset");
lua_insert(vm, -2);
lua_settable(vm, -3);
lua_push_int_table_entry(vm, "remote_pps", last_remote_pps);
lua_push_int_table_entry(vm, "remote_bps", last_remote_bps);
lua_push_str_table_entry(vm, "type", (char*)get_type());
lua_push_int_table_entry(vm, "speed", ifSpeed);
lua_push_int_table_entry(vm, "mtu", ifMTU);
lua_push_int_table_entry(vm, "alertLevel", alertLevel);
lua_push_str_table_entry(vm, "ip_addresses", (char*)getLocalIPAddresses());
sumStats(&_tcpFlowStats, &_ethStats, &_localStats,
&_ndpiStats, &_pktStats, &_tcpPacketStats);
for(u_int8_t s = 0; s<numSubInterfaces; s++)
subInterfaces[s]->sumStats(&_tcpFlowStats, &_ethStats,
&_localStats, &_ndpiStats, &_pktStats, &_tcpPacketStats);
_tcpFlowStats.lua(vm, "tcpFlowStats");
_ethStats.lua(vm);
_localStats.lua(vm);
_ndpiStats.lua(this, vm);
_pktStats.lua(vm, "pktSizeDistribution");
_tcpPacketStats.lua(vm, "tcpPacketStats");
if(!isView()) {
if(pkt_dumper) pkt_dumper->lua(vm);
#ifdef NTOPNG_PRO
if(flow_profiles) flow_profiles->lua(vm);
#endif
}
}
/* **************************************************** */
void NetworkInterface::runHousekeepingTasks() {
/* NOTE NOTE NOTE
This task runs asynchronously with respect to ntopng
so if you need to allocate memory you must LOCK
Example HTTPStats::updateHTTPHostRequest() is called
by both this function and the main thread
*/
periodicStatsUpdate();
}
/* **************************************************** */
Mac* NetworkInterface::getMac(u_int8_t _mac[6], u_int16_t vlanId,
bool createIfNotPresent) {
Mac *ret = NULL;
if(_mac == NULL) return(NULL);
if(!isView())
ret = macs_hash->get(vlanId, _mac);
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
if((ret = subInterfaces[s]->get_macs_hash()->get(vlanId, _mac)) != NULL)
break;
}
}
if((ret == NULL) && createIfNotPresent) {
try {
if((ret = new Mac(this, _mac, vlanId)) != NULL)
macs_hash->add(ret);
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
return(NULL);
}
}
return(ret);
}
/* **************************************************** */
Flow* NetworkInterface::findFlowByKey(u_int32_t key,
AddressTree *allowed_hosts) {
Flow *f;
if(!isView())
f = (Flow*)(flows_hash->findByKey(key));
else {
for(u_int8_t s = 0; s<numSubInterfaces; s++) {
f = (Flow*)subInterfaces[s]->get_flows_hash()->findByKey(key);
if(f) break;
}
}
if(f && (!f->match(allowed_hosts))) f = NULL;
return(f);
}
/* **************************************************** */
struct search_host_info {
lua_State *vm;
char *host_name_or_ip;
u_int num_matches;
AddressTree *allowed_hosts;
};
/* **************************************************** */
static bool hosts_search_walker(GenericHashEntry *h, void *user_data) {
Host *host = (Host*)h;
struct search_host_info *info = (struct search_host_info*)user_data;
if(host->addIfMatching(info->vm, info->allowed_hosts, info->host_name_or_ip))
info->num_matches++;
/* Stop after CONST_MAX_NUM_FIND_HITS matches */
return((info->num_matches > CONST_MAX_NUM_FIND_HITS) ? true /* stop */ : false /* keep walking */);
}
/* **************************************************** */
bool NetworkInterface::findHostsByName(lua_State* vm,
AddressTree *allowed_hosts,
char *key) {
struct search_host_info info;
info.vm = vm, info.host_name_or_ip = key, info.num_matches = 0, info.allowed_hosts = allowed_hosts;
lua_newtable(vm);
walker(walker_hosts, hosts_search_walker, (void*)&info);
return(info.num_matches > 0);
}
/* **************************************************** */
bool NetworkInterface::validInterface(char *name) {
if(name &&
(strstr(name, "PPP") /* Avoid to use the PPP interface */
|| strstr(name, "dialup") /* Avoid to use the dialup interface */
|| strstr(name, "ICSHARE") /* Avoid to use the internet sharing interface */
|| strstr(name, "NdisWan"))) { /* Avoid to use the internet sharing interface */
return(false);
}
return(true);
}
/* **************************************************** */
u_int NetworkInterface::printAvailableInterfaces(bool printHelp, int idx,
char *ifname, u_int ifname_len) {
char ebuf[256];
int numInterfaces = 0;
pcap_if_t *devpointer;
if(printHelp && help_printed)
return(0);
ebuf[0] = '\0';
if(pcap_findalldevs(&devpointer, ebuf) < 0) {
;
} else {
if(ifname == NULL) {
if(printHelp)
printf("Available interfaces (-i <interface index>):\n");
else if(!help_printed)
ntop->getTrace()->traceEvent(TRACE_NORMAL,
"Available interfaces (-i <interface index>):");
}
for(int i = 0; devpointer != NULL; i++) {
if(validInterface(devpointer->description)) {
numInterfaces++;
if(ifname == NULL) {
if(printHelp) {
#ifdef WIN32
printf(" %d. %s\n"
"\t%s\n", numInterfaces,
devpointer->description ? devpointer->description : "",
devpointer->name);
#else
printf(" %d. %s\n", numInterfaces, devpointer->name);
#endif
} else if(!help_printed)
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%d. %s (%s)\n",
numInterfaces, devpointer->name,
devpointer->description ? devpointer->description : devpointer->name);
} else if(numInterfaces == idx) {
snprintf(ifname, ifname_len, "%s", devpointer->name);
break;
}
}
devpointer = devpointer->next;
} /* for */
} /* else */
if(numInterfaces == 0) {
#ifdef WIN32
ntop->getTrace()->traceEvent(TRACE_WARNING, "No interfaces available! This application cannot work");
ntop->getTrace()->traceEvent(TRACE_WARNING, "Make sure that winpcap is installed properly,");
ntop->getTrace()->traceEvent(TRACE_WARNING, "that you have administrative rights,");
ntop->getTrace()->traceEvent(TRACE_WARNING, "and that you have network interfaces installed.");
#else
ntop->getTrace()->traceEvent(TRACE_WARNING, "No interfaces available: are you superuser?");
#endif
}
help_printed = true;
return(numInterfaces);
}
/* **************************************************** */
bool NetworkInterface::isNumber(const char *str) {
while(*str) {
if(!isdigit(*str))
return(false);
str++;
}
return(true);
}
/* **************************************************** */
struct correlator_host_info {
lua_State* vm;
Host *h;
activity_bitmap x;
};
static bool correlator_walker(GenericHashEntry *node, void *user_data) {
Host *h = (Host*)node;
struct correlator_host_info *info = (struct correlator_host_info*)user_data;
if(h
// && h->isLocalHost() /* Consider only local hosts */
&& h->get_ip()
&& (h != info->h)) {
char buf[32], *name = h->get_ip()->print(buf, sizeof(buf));
activity_bitmap y;
double pearson;
h->getActivityStats()->extractPoints(&y);
pearson = Utils::pearsonValueCorrelation(&(info->x), &y);
/* ntop->getTrace()->traceEvent(TRACE_WARNING, "%s: %f", name, pearson); */
lua_push_float_table_entry(info->vm, name, (float)pearson);
}
return(false); /* false = keep on walking */
}
static bool similarity_walker(GenericHashEntry *node, void *user_data) {
Host *h = (Host*)node;
struct correlator_host_info *info = (struct correlator_host_info*)user_data;
if(h
// && h->isLocalHost() /* Consider only local hosts */
&& h->get_ip()
&& (h != info->h)) {
char buf[32], name[64];
if(h->get_vlan_id() == 0) {
sprintf(name, "%s",h->get_ip()->print(buf, sizeof(buf)));
} else {
sprintf(name, "%s@%d",h->get_ip()->print(buf, sizeof(buf)),h->get_vlan_id());
}
activity_bitmap y;
double jaccard;
h->getActivityStats()->extractPoints(&y);
jaccard = Utils::JaccardSimilarity(&(info->x), &y);
/* ntop->getTrace()->traceEvent(TRACE_WARNING, "%s: %f", name, pearson); */
lua_push_float_table_entry(info->vm, name, (float)jaccard);
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
bool NetworkInterface::correlateHostActivity(lua_State* vm,
AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
Host *h = getHost(host_ip, vlan_id);
if(h) {
struct correlator_host_info info;
memset(&info, 0, sizeof(info));
info.vm = vm, info.h = h;
h->getActivityStats()->extractPoints(&info.x);
walker(walker_hosts, correlator_walker, &info);
return(true);
} else
return(false);
}
/* **************************************************** */
bool NetworkInterface::similarHostActivity(lua_State* vm,
AddressTree *allowed_hosts,
char *host_ip, u_int16_t vlan_id) {
Host *h = getHost(host_ip, vlan_id);
if(h) {
struct correlator_host_info info;
memset(&info, 0, sizeof(info));
info.vm = vm, info.h = h;
h->getActivityStats()->extractPoints(&info.x);
walker(walker_hosts, similarity_walker, &info);
return(true);
} else
return(false);
}
/* **************************************************** */
struct user_flows {
lua_State* vm;
char *username;
};
static bool userfinder_walker(GenericHashEntry *node, void *user_data) {
Flow *f = (Flow*)node;
struct user_flows *info = (struct user_flows*)user_data;
char *user = f->get_username(true);
if(user == NULL)
user = f->get_username(false);
if(user && (strcmp(user, info->username) == 0)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
}
return(false); /* false = keep on walking */
}
/* **************************************************** */
void NetworkInterface::findUserFlows(lua_State *vm, char *username) {
struct user_flows u;
u.vm = vm, u.username = username;
walker(walker_flows, userfinder_walker, &u);
}
/* **************************************************** */
struct proc_name_flows {
lua_State* vm;
char *proc_name;
};
static bool proc_name_finder_walker(GenericHashEntry *node, void *user_data) {
Flow *f = (Flow*)node;
struct proc_name_flows *info = (struct proc_name_flows*)user_data;
char *name = f->get_proc_name(true);
if(name && (strcmp(name, info->proc_name) == 0)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
} else {
name = f->get_proc_name(false);
if(name && (strcmp(name, info->proc_name) == 0)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
}
}
return(false); /* false = keep on walking */
}
void NetworkInterface::findProcNameFlows(lua_State *vm, char *proc_name) {
struct proc_name_flows u;
u.vm = vm, u.proc_name = proc_name;
walker(walker_flows, proc_name_finder_walker, &u);
}
/* **************************************************** */
struct pid_flows {
lua_State* vm;
u_int32_t pid;
};
static bool pidfinder_walker(GenericHashEntry *node, void *pid_data) {
Flow *f = (Flow*)node;
struct pid_flows *info = (struct pid_flows*)pid_data;
if((f->getPid(true) == info->pid) || (f->getPid(false) == info->pid)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
}
return(false); /* false = keep on walking */
}
/* **************************************** */
void NetworkInterface::findPidFlows(lua_State *vm, u_int32_t pid) {
struct pid_flows u;
u.vm = vm, u.pid = pid;
walker(walker_flows, pidfinder_walker, &u);
}
/* **************************************** */
static bool father_pidfinder_walker(GenericHashEntry *node, void *father_pid_data) {
Flow *f = (Flow*)node;
struct pid_flows *info = (struct pid_flows*)father_pid_data;
if((f->getFatherPid(true) == info->pid) || (f->getFatherPid(false) == info->pid)) {
f->lua(info->vm, NULL, details_normal /* Minimum details */, false);
lua_pushnumber(info->vm, f->key()); // Key
lua_insert(info->vm, -2);
lua_settable(info->vm, -3);
}
return(false); /* false = keep on walking */
}
/* **************************************** */
void NetworkInterface::findFatherPidFlows(lua_State *vm, u_int32_t father_pid) {
struct pid_flows u;
u.vm = vm, u.pid = father_pid;
walker(walker_flows, father_pidfinder_walker, &u);
}
/* **************************************** */
struct virtual_host_valk_info {
lua_State *vm;
char *key;
u_int32_t num;
};
static bool virtual_http_hosts_walker(GenericHashEntry *node, void *data) {
Host *h = (Host*)node;
struct virtual_host_valk_info *info = (struct virtual_host_valk_info*)data;
HTTPstats *s = h->getHTTPstats();
if(s)
info->num += s->luaVirtualHosts(info->vm, info->key, h);
return(false); /* false = keep on walking */
}
/* **************************************** */
void NetworkInterface::listHTTPHosts(lua_State *vm, char *key) {
struct virtual_host_valk_info info;
lua_newtable(vm);
info.vm = vm, info.key = key, info.num = 0;
walker(walker_hosts, virtual_http_hosts_walker, &info);
}
/* **************************************** */
bool NetworkInterface::isInterfaceUp(char *name) {
#ifdef WIN32
return(true);
#else
struct ifreq ifr;
int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if(strlen(name) >= sizeof(ifr.ifr_name))
return(false);
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, name);
if(ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
closesocket(sock);
return(false);
}
closesocket(sock);
return(!!(ifr.ifr_flags & IFF_UP));
#endif
}
/* **************************************** */
void NetworkInterface::addAllAvailableInterfaces() {
char ebuf[256] = { '\0' };
pcap_if_t *devpointer;
if(pcap_findalldevs(&devpointer, ebuf) < 0) {
;
} else {
for(int i = 0; devpointer != 0; i++) {
if(validInterface(devpointer->description)
&& isInterfaceUp(devpointer->name)) {
ntop->getPrefs()->add_network_interface(devpointer->name,
devpointer->description);
} else
ntop->getTrace()->traceEvent(TRACE_INFO, "Interface [%s][%s] not valid or down: discarded",
devpointer->name, devpointer->description);
devpointer = devpointer->next;
} /* for */
pcap_freealldevs(devpointer);
}
}
/* **************************************** */
#ifdef NTOPNG_PRO
void NetworkInterface::refreshL7Rules() {
if(ntop->getPro()->has_valid_license() && policer)
policer->refreshL7Rules();
}
#endif
/* **************************************** */
#ifdef NTOPNG_PRO
void NetworkInterface::refreshShapers() {
if(ntop->getPro()->has_valid_license() && policer)
policer->refreshShapers();
}
#endif
/* **************************************** */
void NetworkInterface::addInterfaceAddress(char *addr) {
if(ip_addresses.size() == 0)
ip_addresses = addr;
else {
string s = addr;
ip_addresses = ip_addresses + "," + s;
}
}
/* **************************************** */
void NetworkInterface::allocateNetworkStats() {
u_int8_t numNetworks = ntop->getNumLocalNetworks();
try {
networkStats = new NetworkStats[numNetworks];
} catch(std::bad_alloc& ba) {
static bool oom_warning_sent = false;
if(!oom_warning_sent) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
oom_warning_sent = true;
}
networkStats = NULL;
}
}
/* **************************************** */
NetworkStats* NetworkInterface::getNetworkStats(u_int8_t networkId) {
if((networkStats == NULL) || (networkId >= ntop->getNumLocalNetworks()))
return(NULL);
else
return(&networkStats[networkId]);
}
/* **************************************** */
void NetworkInterface::updateSecondTraffic(time_t when) {
u_int64_t bytes = ethStats.getNumBytes();
u_int16_t sec = when % 60;
if(sec == 0) {
/* Beginning of a new minute */
memcpy(lastMinuteTraffic, currentMinuteTraffic, sizeof(currentMinuteTraffic));
resetSecondTraffic();
}
currentMinuteTraffic[sec] = max_val(0, bytes-lastSecTraffic);
lastSecTraffic = bytes;
};
/* **************************************** */
void NetworkInterface::checkPointCounters(bool drops_only) {
if(!drops_only) {
checkpointPktCount = getNumPackets(),
checkpointBytesCount = getNumBytes();
}
checkpointPktDropCount = getNumPacketDrops();
if(ntop->getPrefs()->do_dump_flows_on_es()) {
ntop->getElasticSearch()->checkPointCounters(drops_only);
} else if(ntop->getPrefs()->do_dump_flows_on_mysql()) {
if(db) db->checkPointCounters(drops_only);
}
}
/* **************************************************** */
u_int64_t NetworkInterface::getCheckPointNumPackets() {
u_int64_t tot = checkpointPktCount;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getCheckPointNumPackets();
return(tot);
};
/* **************************************************** */
u_int64_t NetworkInterface::getCheckPointNumBytes() {
u_int64_t tot = checkpointBytesCount;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getCheckPointNumBytes();
return(tot);
}
/* **************************************************** */
u_int32_t NetworkInterface::getCheckPointNumPacketDrops() {
u_int32_t tot = checkpointPktDropCount;
for(u_int8_t s = 0; s<numSubInterfaces; s++) tot += subInterfaces[s]->getCheckPointNumPacketDrops();
return(tot);
};
/* **************************************** */
void NetworkInterface::setRemoteStats(char *name, char *address, u_int32_t speedMbit,
char *remoteProbeAddress, char *remoteProbePublicAddress,
u_int64_t remBytes, u_int64_t remPkts,
u_int32_t remTime, u_int32_t last_pps, u_int32_t last_bps) {
if(name) setRemoteIfname(name);
if(address) setRemoteIfIPaddr(address);
if(remoteProbeAddress) setRemoteProbeAddr(remoteProbeAddress);
if(remoteProbePublicAddress) setRemoteProbePublicAddr(remoteProbePublicAddress);
ifSpeed = speedMbit, last_pkt_rcvd_remote = remTime, last_remote_pps = last_pps, last_remote_bps = last_bps;
if((zmq_initial_pkts == 0) /* ntopng has been restarted */
|| (remBytes < zmq_initial_bytes) /* nProbe has been restarted */
) {
/* Start over */
zmq_initial_bytes = remBytes, zmq_initial_pkts = remPkts;
} else {
remBytes -= zmq_initial_bytes, remPkts -= zmq_initial_pkts;
ntop->getTrace()->traceEvent(TRACE_INFO, "[%s][bytes=%u/%u (%d)][pkts=%u/%u (%d)]",
ifname, remBytes, ethStats.getNumBytes(), remBytes-ethStats.getNumBytes(),
remPkts, ethStats.getNumPackets(), remPkts-ethStats.getNumPackets());
/*
* Don't override ethStats here, these stats are properly updated
* inside NetworkInterface::processFlow for ZMQ interfaces.
* Overriding values here may cause glitches and non-strictly-increasing counters
* yielding negative rates.
ethStats.setNumBytes(remBytes), ethStats.setNumPackets(remPkts);
*
*/
}
}
/* **************************************** */
void NetworkInterface::processInterfaceStats(sFlowInterfaceStats *stats) {
if(interfaceStats == NULL)
interfaceStats = new InterfaceStatsHash(NUM_IFACE_STATS_HASH);
if(interfaceStats) {
char a[64];
ntop->getTrace()->traceEvent(TRACE_INFO, "[%s][ifIndex=%u]",
Utils::intoaV4(stats->deviceIP, a, sizeof(a)),
stats->ifIndex);
interfaceStats->set(stats->deviceIP, stats->ifIndex, stats);
}
}
/* **************************************** */
ndpi_protocol_category_t NetworkInterface::get_ndpi_proto_category(u_int protoid) {
ndpi_protocol proto;
proto.protocol = NDPI_PROTOCOL_UNKNOWN;
proto.master_protocol = protoid;
return get_ndpi_proto_category(proto);
}
/* **************************************** */
static int lua_flow_get_ndpi_category(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushstring(vm, ndpi_category_str(f->get_detected_protocol_category()));
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_ndpi_proto(lua_State* vm) {
Flow *f;
char buf[32];
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushstring(vm, f->get_detected_protocol_name(buf, sizeof(buf)));
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_ndpi_proto_id(lua_State* vm) {
Flow *f;
ndpi_protocol p;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR); else p = f->get_detected_protocol();
lua_pushnumber(vm, (p.protocol != NDPI_PROTOCOL_UNKNOWN) ? p.protocol : p.master_protocol);
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_first_seen(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushnumber(vm, f->get_first_seen());
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_last_seen(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushnumber(vm, f->get_last_seen());
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_server_name(lua_State* vm) {
Flow *f;
char buf[64];
const char *srv;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
srv = f->getFlowServerInfo();
if(!srv && f->get_srv_host())
srv = f->get_srv_host()->get_name(buf, sizeof(buf), false);
if(!srv) srv = "";
lua_pushstring(vm, srv);
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_http_url(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushstring(vm, f->getHTTPURL());
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_get_http_content_type(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
lua_pushstring(vm, f->getHTTPContentType());
return(CONST_LUA_OK);
}
/* **************************************** */
static int lua_flow_dump(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
f->lua(vm, NULL, details_high, false);
return(CONST_LUA_OK);
}
/* **************************************** */
/* -1 on error */
static int lua_flow_get_profile_id(lua_State* vm) {
Flow *f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
UserActivityID uaid;
lua_pushnumber(vm, f->getActivityId(&uaid) ? uaid : -1);
return(CONST_LUA_OK);
}
/* ****************************************** */
/* -1 on error */
static int lua_flow_get_activity_filter_id(lua_State* vm) {
Flow * f;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
ActivityFilterID fid;
lua_pushnumber(vm, f->getActivityFilterId(&fid) ? fid : -1);
return(CONST_LUA_OK);
}
/* ****************************************** */
/*
* lua params:
* activityID - ID of the activity to apply for filtered bytes
* filterID - ID of the filter to apply to the flow for activity recording
* *parametes - parameters to pass to the filter - See below
*
* SMA/WMA filter params:
* edge - moving average edge to trigger activity
* minsamples - minimum number of samples for activity detection
* WMA filter params:
* timescale - division scale for each second difference from previous packet. 0 to disable
* aggrsecs - max packet seconds difference to aggregate. 0 to disable
* SMA filter params:
* timebound - expected time tick in milliseconds between activity packets. 0 to disable
* sustain - time, in milliseconds, between packets to be considered activity. 0 to disable
*
* CommandSequence filter params:
* mustwait - if true, activity trigger requires server to wait after command request
* minbytes - minimum number of bytes to trigger activity
* maxinterval - maximum milliseconds difference between interactions
* mincommands - minimum number of commands seen in the flow to trigger activity
* minflips - minimum number of server interactions to trigger activity
*
* Web filter params:
* numsamples - number of packets to process for detection
* minbytes - minimum number of bytes to trigger activity
* maxinterval - maximum milliseconds difference between packets
* serverdominant - if true, server bytes must be more then client bytes
* forceWebProfile - if true, force 'web' profile for unknown and 'other' flow profiles
*
* Ratio filter params:
* numsamples - number of packets to process for detection
* minbytes - minimum number of bytes to trigger activity
* clisrv_ratio - minimum (positive ? client/server : server/client) bytes to trigger activity
*
* Interflow filter params:
* minflows - minimum number of concurrent flows. -1 to disable [1]
* minpkts - minimum number of cumulative packets in concurrent flows to trigger activity
* minduration - minimum (max duration of cumulative packets) in concurrent flows. -1 to disable [1]
* sslonly - if true, only SSL traffic can trigger activity
* NOTE: At least one of [1] must be satisfied to trigger activity
*/
static int lua_flow_set_activity_filter(lua_State* vm) {
UserActivityID activityID;
ActivityFilterID filterID;
Flow *f;
activity_filter_config config = {};
u_int8_t params = 0;
lua_getglobal(vm, CONST_USERACTIVITY_FLOW);
f = (Flow*)lua_touserdata(vm, lua_gettop(vm));
if(!f) return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, params+1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
activityID = (UserActivityID)lua_tonumber(vm, ++params);
if(activityID >= UserActivitiesN) return(CONST_LUA_ERROR);
if(lua_type(vm, params+1) == LUA_TNUMBER)
filterID = (ActivityFilterID)lua_tonumber(vm, ++params);
else
return(CONST_LUA_ERROR);
// filter specific parameters
switch(filterID) {
case activity_filter_all:
if(lua_type(vm, params+1) == LUA_TBOOLEAN) {
config.all.pass = lua_toboolean(vm, ++params);
}
switch (params) {
case 2+0: config.all.pass = true;
}
break;
case activity_filter_web:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.web.numsamples = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.web.minbytes = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.web.maxinterval = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TBOOLEAN) {
config.web.forceWebProfile = lua_toboolean(vm, ++params);
if(lua_type(vm, params+1) == LUA_TBOOLEAN)
config.web.serverdominant = lua_toboolean(vm, ++params);
}
}
}
}
// defaults
switch (params) {
case 2+0: config.web.numsamples = 4;
case 2+1: config.web.minbytes = 0;
case 2+2: config.web.maxinterval = 2000;
case 2+3: config.web.forceWebProfile = true;
case 2+4: config.web.serverdominant = true;
}
break;
case activity_filter_ratio:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.ratio.numsamples = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.ratio.minbytes = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER)
config.ratio.clisrv_ratio = lua_tonumber(vm, ++params);
}
}
// defaults
switch (params) {
case 2+0: config.ratio.numsamples = 4;
case 2+1: config.ratio.minbytes = 0;
case 2+2: config.ratio.clisrv_ratio = -1.f;
}
break;
case activity_filter_interflow:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.interflow.minflows = min((int)lua_tonumber(vm, ++params), INTER_FLOW_ACTIVITY_SLOTS);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.interflow.minpkts = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.interflow.minduration = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TBOOLEAN)
config.interflow.sslonly = lua_toboolean(vm, ++params);
}
}
}
// defaults
switch (params) {
case 2+0: config.interflow.minflows = INTER_FLOW_ACTIVITY_SLOTS;
case 2+1: config.interflow.minpkts = 200;
case 2+2: config.interflow.minduration = -1;
case 2+3: config.interflow.sslonly = false;
}
break;
case activity_filter_metrics_test:
break;
case activity_filter_sma:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.sma.edge = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.sma.minsamples = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.sma.timebound = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER)
config.sma.sustain = lua_tonumber(vm, ++params);
}
}
}
// defaults
switch (params) {
case 2+0: config.sma.edge = 0;
case 2+1: config.sma.minsamples = ACTIVITY_FILTER_WMA_SAMPLES;
case 2+2: config.sma.timebound = 2000;
case 2+3: config.sma.sustain = 1000;
}
break;
case activity_filter_wma:
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.wma.edge = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.wma.minsamples = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.wma.timescale = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER)
config.wma.aggrsecs = lua_tonumber(vm, ++params);
}
}
}
// defaults
switch (params) {
case 2+0: config.wma.edge = 0;
case 2+1: config.wma.minsamples = ACTIVITY_FILTER_WMA_SAMPLES;
case 2+2: config.wma.timescale = 1.f;
case 2+3: config.wma.aggrsecs = 0;
}
break;
case activity_filter_command_sequence:
if(lua_type(vm, params+1) == LUA_TBOOLEAN) {
config.command_sequence.mustwait = lua_toboolean(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.command_sequence.minbytes = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.command_sequence.maxinterval = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER) {
config.command_sequence.mincommands = lua_tonumber(vm, ++params);
if(lua_type(vm, params+1) == LUA_TNUMBER)
config.command_sequence.minflips = lua_tonumber(vm, ++params);
}
}
}
}
switch (params) {
case 2+0: config.command_sequence.mustwait = false;
case 2+1: config.command_sequence.minbytes = 0;
case 2+2: config.command_sequence.maxinterval = 3000;
case 2+3: config.command_sequence.mincommands = 1;
case 2+4: config.command_sequence.minflips = 1;
}
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Invalid activity filter (%d)", filterID);
return (CONST_LUA_ERROR);
}
ntop->getTrace()->traceEvent(TRACE_DEBUG, "Flow %p setActivityFilter: filter=%d activity=%d", f, filterID, activityID);
f->setActivityFilter(filterID, &config);
f->setActivityId(activityID);
return(CONST_LUA_OK);
}
/* ****************************************** */
static const luaL_Reg flow_reg[] = {
{ "getNdpiCategory", lua_flow_get_ndpi_category },
{ "getNdpiProto", lua_flow_get_ndpi_proto },
{ "getNdpiProtoId", lua_flow_get_ndpi_proto_id },
{ "getFirstSeen", lua_flow_get_first_seen },
{ "getLastSeen", lua_flow_get_last_seen },
{ "getServerName", lua_flow_get_server_name },
{ "getHTTPUrl", lua_flow_get_http_url },
{ "getHTTPContentType",lua_flow_get_http_content_type },
{ "dump", lua_flow_dump },
{ "setActivityFilter", lua_flow_set_activity_filter },
{ "getProfileId", lua_flow_get_profile_id },
{ "getActivityFilterId", lua_flow_get_activity_filter_id },
{ NULL, NULL }
};
ntop_class_reg ntop_lua_reg[] = {
{ "flow", flow_reg },
{NULL, NULL}
};
lua_State* NetworkInterface::initLuaInterpreter(const char *lua_file) {
static const luaL_Reg _meta[] = { { NULL, NULL } };
int i;
char script_path[256];
lua_State *L;
L = luaL_newstate();
if(!L) {
ntop->getTrace()->traceEvent(TRACE_ERROR, "Unable to initialize lua interpreter");
return(NULL);
}
snprintf(script_path, sizeof(script_path), "%s/%s",
ntop->getPrefs()->get_callbacks_dir(),
lua_file);
/* ******************************************** */
luaL_openlibs(L); /* Load base libraries */
for(i=0; ntop_lua_reg[i].class_name != NULL; i++) {
int lib_id, meta_id;
/* newclass = {} */
lua_createtable(L, 0, 0);
lib_id = lua_gettop(L);
/* metatable = {} */
luaL_newmetatable(L, ntop_lua_reg[i].class_name);
meta_id = lua_gettop(L);
luaL_register(L, NULL, _meta);
/* metatable.__index = class_methods */
lua_newtable(L), luaL_register(L, NULL, ntop_lua_reg[i].class_methods);
lua_setfield(L, meta_id, "__index");
/* class.__metatable = metatable */
lua_setmetatable(L, lib_id);
/* _G["Foo"] = newclass */
lua_setglobal(L, ntop_lua_reg[i].class_name);
}
lua_register(L, "print", ntop_lua_cli_print);
// Activity profiles - see ntop_typedefs.h
lua_newtable(L);
for(int i=0; i<UserActivitiesN; i++)
lua_push_int_table_entry(L, activity_names[i], i);
lua_setglobal(L, CONST_USERACTIVITY_PROFILES);
// Activity filters
lua_newtable(L);
lua_push_int_table_entry(L, "All", activity_filter_all);
lua_push_int_table_entry(L, "SMA", activity_filter_sma);
lua_push_int_table_entry(L, "WMA", activity_filter_wma);
lua_push_int_table_entry(L, "CommandSequence", activity_filter_command_sequence);
lua_push_int_table_entry(L, "Web", activity_filter_web);
lua_push_int_table_entry(L, "Ratio", activity_filter_ratio);
lua_push_int_table_entry(L, "Interflow", activity_filter_interflow);
lua_push_int_table_entry(L, "Metrics", activity_filter_metrics_test);
lua_setglobal(L, CONST_USERACTIVITY_FILTERS);
if(luaL_loadfile(L, script_path) || lua_pcall(L, 0, 0, 0)) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Cannot run lua file %s: %s",
script_path, lua_tostring(L, -1));
lua_close(L);
L = NULL;
} else {
ntop->getTrace()->traceEvent(TRACE_INFO, "Successfully interpreted %s", script_path);
lua_pushlightuserdata(L, NULL);
lua_setglobal(L, CONST_USERACTIVITY_FLOW);
}
return(L);
}
/* **************************************** */
void NetworkInterface::termLuaInterpreter() {
if(L_flow_create_delete_ndpi) { lua_close(L_flow_create_delete_ndpi); L_flow_create_delete_ndpi = NULL; }
if(L_flow_update) { lua_close(L_flow_update); L_flow_update = NULL; }
}
/* **************************************** */
int NetworkInterface::luaEvalFlow(Flow *f, const LuaCallback cb) {
int rc;
lua_State *L;
const char *luaFunction;
return(0); // FIX
if(reloadLuaInterpreter) {
if(L_flow_create_delete_ndpi || L_flow_update) termLuaInterpreter();
L_flow_create_delete_ndpi = initLuaInterpreter(CONST_FLOWACTIVITY_SCRIPT);
L_flow_update = initLuaInterpreter(CONST_FLOWACTIVITY_SCRIPT);
reloadLuaInterpreter = false;
}
switch(cb) {
case callback_flow_create:
L = L_flow_create_delete_ndpi, luaFunction = CONST_LUA_FLOW_CREATE;
break;
case callback_flow_delete:
L = L_flow_create_delete_ndpi, luaFunction = CONST_LUA_FLOW_DELETE;
break;
case callback_flow_update:
L = L_flow_update, luaFunction = CONST_LUA_FLOW_UPDATE;
break;
case callback_flow_proto_callback:
L = L_flow_create_delete_ndpi, luaFunction = CONST_LUA_FLOW_NDPI_DETECT;
break;
default:
ntop->getTrace()->traceEvent(TRACE_WARNING, "Invalid lua callback (%d)", cb);
return(-1);
}
if(L == NULL)
return(-2);
lua_settop(L, 0); /* Reset stack */
lua_pushlightuserdata(L, f);
lua_setglobal(L, CONST_USERACTIVITY_FLOW);
lua_getglobal(L, luaFunction); /* function to be called */
if((rc = lua_pcall(L, 0 /* 0 parameters */, 0 /* no return values */, 0)) != 0) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Error while executing %s [rc=%d][%s]", luaFunction, rc, lua_tostring(L, -1));
}
return(rc);
}
/* **************************************** */
int NetworkInterface::getActiveMacList(lua_State* vm, u_int16_t vlan_id,
bool skipSpecialMacs,
bool hostMacsOnly,
char *sortColumn, u_int32_t maxHits,
u_int32_t toSkip, bool a2zSortOrder) {
struct flowHostRetriever retriever;
bool show_details = true;
disablePurge(false);
if(sortMacs(&retriever, vlan_id, skipSpecialMacs, hostMacsOnly, sortColumn) < 0) {
enablePurge(false);
return -1;
}
lua_newtable(vm);
lua_push_int_table_entry(vm, "numMacs", retriever.actNumEntries);
lua_newtable(vm);
if(a2zSortOrder) {
for(int i = toSkip, num=0; i<(int)retriever.actNumEntries && num < (int)maxHits; i++, num++) {
Mac *m = retriever.elems[i].macValue;
m->lua(vm, show_details, false);
lua_rawseti(vm, -2, num + 1); /* Must use integer keys to preserve and iterate inorder with ipairs */
}
} else {
for(int i = (retriever.actNumEntries-1-toSkip), num=0; i >= 0 && num < (int)maxHits; i--, num++) {
Mac *m = retriever.elems[i].macValue;
m->lua(vm, show_details, false);
lua_rawseti(vm, -2, num + 1);
}
}
lua_pushstring(vm, "macs");
lua_insert(vm, -2);
lua_settable(vm, -3);
enablePurge(false);
// finally free the elements regardless of the sorted kind
if(retriever.elems) free(retriever.elems);
return(retriever.actNumEntries);
}
/* **************************************** */
bool NetworkInterface::getMacInfo(lua_State* vm, char *mac, u_int16_t vlan_id) {
struct mac_find_info info;
memset(&info, 0, sizeof(info));
Utils::parseMac(info.mac, mac), info.vlan_id = vlan_id;
walker(walker_macs, find_mac_by_name, (void*)&info);
if(info.m) {
info.m->lua(vm, true, false);
return(true);
} else
return(false);
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_3266_1 |
crossvul-cpp_data_bad_2811_0 | /*****************************************************************
|
| AP4 - hdlr Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4HdlrAtom.h"
#include "Ap4AtomFactory.h"
#include "Ap4Utils.h"
/*----------------------------------------------------------------------
| dynamic cast support
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_HdlrAtom)
/*----------------------------------------------------------------------
| AP4_HdlrAtom::Create
+---------------------------------------------------------------------*/
AP4_HdlrAtom*
AP4_HdlrAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI08 version;
AP4_UI32 flags;
if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
if (version != 0) return NULL;
return new AP4_HdlrAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_HdlrAtom::AP4_HdlrAtom
+---------------------------------------------------------------------*/
AP4_HdlrAtom::AP4_HdlrAtom(AP4_Atom::Type hdlr_type, const char* hdlr_name) :
AP4_Atom(AP4_ATOM_TYPE_HDLR, AP4_FULL_ATOM_HEADER_SIZE, 0, 0),
m_HandlerType(hdlr_type),
m_HandlerName(hdlr_name)
{
m_Size32 += 20+m_HandlerName.GetLength()+1;
m_Reserved[0] = m_Reserved[1] = m_Reserved[2] = 0;
}
/*----------------------------------------------------------------------
| AP4_HdlrAtom::AP4_HdlrAtom
+---------------------------------------------------------------------*/
AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)
{
AP4_UI32 predefined;
stream.ReadUI32(predefined);
stream.ReadUI32(m_HandlerType);
stream.ReadUI32(m_Reserved[0]);
stream.ReadUI32(m_Reserved[1]);
stream.ReadUI32(m_Reserved[2]);
// read the name unless it is empty
int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);
if (name_size == 0) return;
char* name = new char[name_size+1];
stream.Read(name, name_size);
name[name_size] = '\0'; // force a null termination
// handle a special case: the Quicktime files have a pascal
// string here, but ISO MP4 files have a C string.
// we try to detect a pascal encoding and correct it.
if (name[0] == name_size-1) {
m_HandlerName = name+1;
} else {
m_HandlerName = name;
}
delete[] name;
}
/*----------------------------------------------------------------------
| AP4_HdlrAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_HdlrAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
// write the data
result = stream.WriteUI32(0); // predefined
if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_HandlerType);
if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved[0]);
if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved[1]);
if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved[2]);
if (AP4_FAILED(result)) return result;
AP4_UI08 name_size = (AP4_UI08)m_HandlerName.GetLength();
if (AP4_FULL_ATOM_HEADER_SIZE+20+name_size > m_Size32) {
name_size = (AP4_UI08)(m_Size32-AP4_FULL_ATOM_HEADER_SIZE+20);
}
if (name_size) {
result = stream.Write(m_HandlerName.GetChars(), name_size);
if (AP4_FAILED(result)) return result;
}
// pad with zeros if necessary
AP4_Size padding = m_Size32-(AP4_FULL_ATOM_HEADER_SIZE+20+name_size);
while (padding--) stream.WriteUI08(0);
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_HdlrAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_HdlrAtom::InspectFields(AP4_AtomInspector& inspector)
{
char type[5];
AP4_FormatFourChars(type, m_HandlerType);
inspector.AddField("handler_type", type);
inspector.AddField("handler_name", m_HandlerName.GetChars());
return AP4_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_2811_0 |
crossvul-cpp_data_good_2810_0 | /*****************************************************************
|
| AP4 - MetaData
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4File.h"
#include "Ap4Movie.h"
#include "Ap4MetaData.h"
#include "Ap4ContainerAtom.h"
#include "Ap4MoovAtom.h"
#include "Ap4HdlrAtom.h"
#include "Ap4DataBuffer.h"
#include "Ap4Utils.h"
#include "Ap4String.h"
/*----------------------------------------------------------------------
| dynamic cast support
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_3GppLocalizedStringAtom)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_DcfdAtom)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_DcfStringAtom)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_DataAtom)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_MetaDataStringAtom)
/*----------------------------------------------------------------------
| metadata keys
+---------------------------------------------------------------------*/
static const AP4_MetaData::KeyInfo AP4_MetaData_KeyInfos [] = {
{"Name", "Name", AP4_ATOM_TYPE_cNAM, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Artist", "Artist", AP4_ATOM_TYPE_cART, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"AlbumArtist", "Album Artist", AP4_ATOM_TYPE_aART, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Composer", "Composer", AP4_ATOM_TYPE_cCOM, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Writer", "Writer", AP4_ATOM_TYPE_cWRT, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Album", "Album", AP4_ATOM_TYPE_cALB, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"GenreCode", "Genre", AP4_ATOM_TYPE_GNRE, AP4_MetaData::Value::TYPE_BINARY},
{"GenreName", "Genre", AP4_ATOM_TYPE_cGEN, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Grouping", "Grouping", AP4_ATOM_TYPE_cGRP, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Date", "Date", AP4_ATOM_TYPE_cDAY, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Tool", "Encoding Tool", AP4_ATOM_TYPE_cTOO, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Comment", "Comment", AP4_ATOM_TYPE_cCMT, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Lyrics", "Lyrics", AP4_ATOM_TYPE_cLYR, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Copyright", "Copyright", AP4_ATOM_TYPE_CPRT, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Track", "Track Number", AP4_ATOM_TYPE_TRKN, AP4_MetaData::Value::TYPE_BINARY},
{"Disc", "Disc Number", AP4_ATOM_TYPE_DISK, AP4_MetaData::Value::TYPE_BINARY},
{"Cover", "Cover Art", AP4_ATOM_TYPE_COVR, AP4_MetaData::Value::TYPE_BINARY},
{"Description", "Description", AP4_ATOM_TYPE_DESC, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Rating", "Rating", AP4_ATOM_TYPE_RTNG, AP4_MetaData::Value::TYPE_INT_08_BE},
{"Tempo", "Tempo", AP4_ATOM_TYPE_TMPO, AP4_MetaData::Value::TYPE_INT_16_BE},
{"Compilation", "Compilation", AP4_ATOM_TYPE_CPIL, AP4_MetaData::Value::TYPE_INT_08_BE},
{"IsGapless", "Is Gapless", AP4_ATOM_TYPE_PGAP, AP4_MetaData::Value::TYPE_INT_08_BE},
{"Title", "Title", AP4_ATOM_TYPE_TITL, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Description", "Description", AP4_ATOM_TYPE_DSCP, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"StoreFrontID", "Store Front ID", AP4_ATOM_TYPE_sfID, AP4_MetaData::Value::TYPE_INT_32_BE},
{"FileKind", "File Kind", AP4_ATOM_TYPE_STIK, AP4_MetaData::Value::TYPE_INT_08_BE},
{"ShowName", "Show Name", AP4_ATOM_TYPE_TVSH, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"ShowSeason", "Show Season Number", AP4_ATOM_TYPE_TVSN, AP4_MetaData::Value::TYPE_INT_32_BE},
{"ShowEpisodeNumber", "Show Episode Number", AP4_ATOM_TYPE_TVES, AP4_MetaData::Value::TYPE_INT_32_BE},
{"ShowEpisodeName", "Show Episode Name", AP4_ATOM_TYPE_TVEN, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"TVNetworkName", "TV Network Name", AP4_ATOM_TYPE_TVNN, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"IsPodcast", "Is a Podcast", AP4_ATOM_TYPE_PCST, AP4_MetaData::Value::TYPE_INT_08_BE},
{"PodcastUrl", "Podcast URL", AP4_ATOM_TYPE_PURL, AP4_MetaData::Value::TYPE_BINARY},
{"PodcastGuid", "Podcast GUID", AP4_ATOM_TYPE_EGID, AP4_MetaData::Value::TYPE_BINARY},
{"PodcastCategory", "Podcast Category", AP4_ATOM_TYPE_CATG, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Keywords", "Keywords", AP4_ATOM_TYPE_KEYW, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"PurchaseDate", "Purchase Date", AP4_ATOM_TYPE_PURD, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"IconUri", "Icon URI", AP4_ATOM_TYPE_ICNU, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"InfoUrl", "Info URL", AP4_ATOM_TYPE_INFU, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"CoverUri", "Cover Art URI", AP4_ATOM_TYPE_CVRU, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"LyricsUri", "Lyrics URI", AP4_ATOM_TYPE_LRCU, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Duration", "Duration", AP4_ATOM_TYPE_DCFD, AP4_MetaData::Value::TYPE_INT_32_BE},
{"Performer", "Performer", AP4_ATOM_TYPE_PERF, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Author", "Author", AP4_ATOM_TYPE_AUTH, AP4_MetaData::Value::TYPE_STRING_UTF_8},
};
AP4_Array<AP4_MetaData::KeyInfo> AP4_MetaData::KeyInfos(
AP4_MetaData_KeyInfos,
sizeof(AP4_MetaData_KeyInfos)/sizeof(KeyInfo));
AP4_Result
AP4_MetaData::Initialized() { return AP4_MetaData::KeyInfos.ItemCount() != 0; }
AP4_Result
AP4_MetaData::Initialize() {
unsigned int item_count = sizeof(AP4_MetaData_KeyInfos)/sizeof(KeyInfo);
KeyInfos.SetItemCount(item_count);
for (unsigned int i=0; i<item_count; i++) {
KeyInfos[i] = AP4_MetaData_KeyInfos[i];
}
return AP4_SUCCESS;
}
AP4_Result
AP4_MetaData::UnInitialize() {
return AP4_MetaData::KeyInfos.Clear();
}
/*----------------------------------------------------------------------
| genre IDs
+---------------------------------------------------------------------*/
static const char* const Ap4Id3Genres[] =
{
"Blues",
"Classic Rock",
"Country",
"Dance",
"Disco",
"Funk",
"Grunge",
"Hip-Hop",
"Jazz",
"Metal",
"New Age",
"Oldies",
"Other",
"Pop",
"R&B",
"Rap",
"Reggae",
"Rock",
"Techno",
"Industrial",
"Alternative",
"Ska",
"Death Metal",
"Pranks",
"Soundtrack",
"Euro-Techno",
"Ambient",
"Trip-Hop",
"Vocal",
"Jazz+Funk",
"Fusion",
"Trance",
"Classical",
"Instrumental",
"Acid",
"House",
"Game",
"Sound Clip",
"Gospel",
"Noise",
"AlternRock",
"Bass",
"Soul",
"Punk",
"Space",
"Meditative",
"Instrumental Pop",
"Instrumental Rock",
"Ethnic",
"Gothic",
"Darkwave",
"Techno-Industrial",
"Electronic",
"Pop-Folk",
"Eurodance",
"Dream",
"Southern Rock",
"Comedy",
"Cult",
"Gangsta",
"Top 40",
"Christian Rap",
"Pop/Funk",
"Jungle",
"Native American",
"Cabaret",
"New Wave",
"Psychadelic",
"Rave",
"Showtunes",
"Trailer",
"Lo-Fi",
"Tribal",
"Acid Punk",
"Acid Jazz",
"Polka",
"Retro",
"Musical",
"Rock & Roll",
"Hard Rock",
"Folk",
"Folk-Rock",
"National Folk",
"Swing",
"Fast Fusion",
"Bebob",
"Latin",
"Revival",
"Celtic",
"Bluegrass",
"Avantgarde",
"Gothic Rock",
"Progressive Rock",
"Psychedelic Rock",
"Symphonic Rock",
"Slow Rock",
"Big Band",
"Chorus",
"Easy Listening",
"Acoustic",
"Humour",
"Speech",
"Chanson",
"Opera",
"Chamber Music",
"Sonata",
"Symphony",
"Booty Bass",
"Primus",
"Porn Groove",
"Satire",
"Slow Jam",
"Club",
"Tango",
"Samba",
"Folklore",
"Ballad",
"Power Ballad",
"Rhythmic Soul",
"Freestyle",
"Duet",
"Punk Rock",
"Drum Solo",
"Acapella",
"Euro-House",
"Dance Hall"
};
static const char*
Ap4StikNames[] = {
"Movie", // 0
"Normal", // 1
"Audiobook", // 2
"?", // 3
"?", // 4
"Whacked Bookmark", // 5
"Music Video", // 6
"?", // 7
"?", // 8
"Short Film", // 9
"TV Show", // 10
"Booklet", // 11
"?", // 12
"?", // 13
"Ring Tone" // 14
};
/* sfID Store Front country
Australia => 143460,
Austria => 143445,
Belgium => 143446,
Canada => 143455,
Denmark => 143458,
Finland => 143447,
France => 143442,
Germany => 143443,
Greece => 143448,
Ireland => 143449,
Italy => 143450,
Japan => 143462,
Luxembourg => 143451,
Netherlands => 143452,
Norway => 143457,
Portugal => 143453,
Spain => 143454,
Sweden => 143456,
Switzerland => 143459,
UK => 143444,
USA => 143441,
*/
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
const AP4_Size AP4_DATA_ATOM_MAX_SIZE = 0x40000000;
/*----------------------------------------------------------------------
| 3GPP localized string atoms
+---------------------------------------------------------------------*/
const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypes[] = {
AP4_ATOM_TYPE_TITL,
AP4_ATOM_TYPE_DSCP,
AP4_ATOM_TYPE_CPRT,
AP4_ATOM_TYPE_PERF,
AP4_ATOM_TYPE_AUTH,
AP4_ATOM_TYPE_GNRE
};
const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypeList = {
_3gppLocalizedStringTypes,
sizeof(_3gppLocalizedStringTypes)/sizeof(_3gppLocalizedStringTypes[0])
};
/*----------------------------------------------------------------------
| other 3GPP atoms
+---------------------------------------------------------------------*/
const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppOtherTypes[] = {
AP4_ATOM_TYPE_RTNG,
AP4_ATOM_TYPE_CLSF,
AP4_ATOM_TYPE_KYWD,
AP4_ATOM_TYPE_LOCI,
AP4_ATOM_TYPE_ALBM,
AP4_ATOM_TYPE_YRRC,
};
const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::_3gppOtherTypeList = {
_3gppOtherTypes,
sizeof(_3gppOtherTypes)/sizeof(_3gppOtherTypes[0])
};
/*----------------------------------------------------------------------
| DCF string atoms
+---------------------------------------------------------------------*/
const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::DcfStringTypes[] = {
AP4_ATOM_TYPE_ICNU,
AP4_ATOM_TYPE_INFU,
AP4_ATOM_TYPE_CVRU,
AP4_ATOM_TYPE_LRCU
};
const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::DcfStringTypeList = {
DcfStringTypes,
sizeof(DcfStringTypes)/sizeof(DcfStringTypes[0])
};
/*----------------------------------------------------------------------
| atom type lists
+---------------------------------------------------------------------*/
const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::IlstTypes[] =
{
AP4_ATOM_TYPE_dddd,
AP4_ATOM_TYPE_cNAM,
AP4_ATOM_TYPE_cART,
AP4_ATOM_TYPE_cCOM,
AP4_ATOM_TYPE_cWRT,
AP4_ATOM_TYPE_cALB,
AP4_ATOM_TYPE_cGEN,
AP4_ATOM_TYPE_cGRP,
AP4_ATOM_TYPE_cDAY,
AP4_ATOM_TYPE_cTOO,
AP4_ATOM_TYPE_cCMT,
AP4_ATOM_TYPE_CPRT,
AP4_ATOM_TYPE_TRKN,
AP4_ATOM_TYPE_DISK,
AP4_ATOM_TYPE_COVR,
AP4_ATOM_TYPE_DESC,
AP4_ATOM_TYPE_GNRE,
AP4_ATOM_TYPE_CPIL,
AP4_ATOM_TYPE_TMPO,
AP4_ATOM_TYPE_RTNG,
AP4_ATOM_TYPE_apID,
AP4_ATOM_TYPE_cnID,
AP4_ATOM_TYPE_cmID,
AP4_ATOM_TYPE_atID,
AP4_ATOM_TYPE_plID,
AP4_ATOM_TYPE_geID,
AP4_ATOM_TYPE_sfID,
AP4_ATOM_TYPE_akID,
AP4_ATOM_TYPE_aART,
AP4_ATOM_TYPE_TVNN,
AP4_ATOM_TYPE_TVSH,
AP4_ATOM_TYPE_TVEN,
AP4_ATOM_TYPE_TVSN,
AP4_ATOM_TYPE_TVES,
AP4_ATOM_TYPE_STIK,
AP4_ATOM_TYPE_PGAP,
AP4_ATOM_TYPE_PCST,
AP4_ATOM_TYPE_PURD,
AP4_ATOM_TYPE_PURL,
AP4_ATOM_TYPE_EGID,
AP4_ATOM_TYPE_SONM,
AP4_ATOM_TYPE_SOAL,
AP4_ATOM_TYPE_SOAR,
AP4_ATOM_TYPE_SOAA,
AP4_ATOM_TYPE_SOCO,
AP4_ATOM_TYPE_SOSN
};
const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::IlstTypeList = {
IlstTypes,
sizeof(IlstTypes)/sizeof(IlstTypes[0])
};
/*----------------------------------------------------------------------
| AP4_MetaDataAtomTypeHandler::CreateAtom
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaDataAtomTypeHandler::CreateAtom(AP4_Atom::Type type,
AP4_UI32 size,
AP4_ByteStream& stream,
AP4_Atom::Type context,
AP4_Atom*& atom)
{
atom = NULL;
if (context == AP4_ATOM_TYPE_ILST) {
if (IsTypeInList(type, IlstTypeList)) {
m_AtomFactory->PushContext(type);
atom = AP4_ContainerAtom::Create(type, size, false, false, stream, *m_AtomFactory);
m_AtomFactory->PopContext();
}
} else if (type == AP4_ATOM_TYPE_DATA) {
if (IsTypeInList(context, IlstTypeList)) {
atom = new AP4_DataAtom(size, stream);
}
} else if (context == AP4_ATOM_TYPE_dddd) {
if (type == AP4_ATOM_TYPE_MEAN || type == AP4_ATOM_TYPE_NAME) {
atom = new AP4_MetaDataStringAtom(type, size, stream);
}
} else if (context == AP4_ATOM_TYPE_UDTA) {
if (IsTypeInList(type, _3gppLocalizedStringTypeList)) {
atom = AP4_3GppLocalizedStringAtom::Create(type, size, stream);
} else if (IsTypeInList(type, DcfStringTypeList)) {
atom = AP4_DcfStringAtom::Create(type, size, stream);
} else if (type == AP4_ATOM_TYPE_DCFD) {
atom = AP4_DcfdAtom::Create(size, stream);
}
}
return atom?AP4_SUCCESS:AP4_FAILURE;
}
/*----------------------------------------------------------------------
| AP4_MetaDataAtomTypeHandler::IsTypeInList
+---------------------------------------------------------------------*/
bool
AP4_MetaDataAtomTypeHandler::IsTypeInList(AP4_Atom::Type type, const AP4_MetaDataAtomTypeHandler::TypeList& list)
{
for (unsigned int i=0; i<list.m_Size; i++) {
if (type == list.m_Types[i]) return true;
}
return false;
}
/*----------------------------------------------------------------------
| AP4_MetaData::AP4_MetaData
+---------------------------------------------------------------------*/
AP4_MetaData::AP4_MetaData(AP4_File* file)
{
// get the file's movie
AP4_Movie* movie = file->GetMovie();
// handle the movie's metadata if there is a movie in the file
if (movie) {
AP4_MoovAtom* moov = movie->GetMoovAtom();
if (moov == NULL) return;
ParseMoov(moov);
AP4_Atom* udta = moov->GetChild(AP4_ATOM_TYPE_UDTA);
if (udta) {
AP4_ContainerAtom* udta_container = AP4_DYNAMIC_CAST(AP4_ContainerAtom, udta);
if (udta_container) {
ParseUdta(udta_container, "3gpp");
}
}
} else {
// if we don't have a movie, try to show metadata from a udta atom
AP4_List<AP4_Atom>& top_level_atoms = file->GetTopLevelAtoms();
AP4_List<AP4_Atom>::Item* atom_item = top_level_atoms.FirstItem();
while (atom_item) {
AP4_ContainerAtom* container = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom_item->GetData());
if (container) {
// look for a udta in a DCF layout
AP4_Atom* udta = container->FindChild("odhe/udta");
if (udta) {
AP4_ContainerAtom* udta_container = AP4_DYNAMIC_CAST(AP4_ContainerAtom, udta);
if (udta_container) {
ParseUdta(udta_container, "dcf");
}
}
}
atom_item = atom_item->GetNext();
}
}
}
/*----------------------------------------------------------------------
| AP4_MetaData::ParseMoov
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::ParseMoov(AP4_MoovAtom* moov)
{
// look for a 'meta' atom with 'hdlr' type 'mdir'
AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, moov->FindChild("udta/meta/hdlr"));
if (hdlr == NULL || hdlr->GetHandlerType() != AP4_HANDLER_TYPE_MDIR) return AP4_ERROR_NO_SUCH_ITEM;
// get the list of entries
AP4_ContainerAtom* ilst = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->FindChild("udta/meta/ilst"));
if (ilst == NULL) return AP4_ERROR_NO_SUCH_ITEM;
AP4_List<AP4_Atom>::Item* ilst_item = ilst->GetChildren().FirstItem();
while (ilst_item) {
AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst_item->GetData());
if (entry_atom) {
AddIlstEntries(entry_atom, "meta");
}
ilst_item = ilst_item->GetNext();
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::ParseUdta
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::ParseUdta(AP4_ContainerAtom* udta, const char* namespc)
{
// check that the atom is indeed a 'udta' atom
if (udta->GetType() != AP4_ATOM_TYPE_UDTA) {
return AP4_ERROR_INVALID_PARAMETERS;
}
AP4_List<AP4_Atom>::Item* udta_item = udta->GetChildren().FirstItem();
for (; udta_item; udta_item = udta_item->GetNext()) {
AP4_3GppLocalizedStringAtom* _3gpp_atom = AP4_DYNAMIC_CAST(AP4_3GppLocalizedStringAtom, udta_item->GetData());
if (_3gpp_atom) {
Add3GppEntry(_3gpp_atom, namespc);
continue;
}
AP4_DcfStringAtom* dcfs_atom = AP4_DYNAMIC_CAST(AP4_DcfStringAtom, udta_item->GetData());
if (dcfs_atom) {
AddDcfStringEntry(dcfs_atom, namespc);
continue;
}
AP4_DcfdAtom* dcfd_atom = AP4_DYNAMIC_CAST(AP4_DcfdAtom, udta_item->GetData());
if (dcfd_atom) {
AddDcfdEntry(dcfd_atom, namespc);
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::~AP4_MetaData
+---------------------------------------------------------------------*/
AP4_MetaData::~AP4_MetaData()
{
m_Entries.DeleteReferences();
}
/*----------------------------------------------------------------------
| AP4_MetaData::ResolveKeyName
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::ResolveKeyName(AP4_Atom::Type atom_type, AP4_String& value)
{
const char* key_name = NULL;
char four_cc[5];
// look for a match in the key infos
for (unsigned int i=0;
i<sizeof(AP4_MetaData_KeyInfos)/sizeof(AP4_MetaData_KeyInfos[0]);
i++) {
if (AP4_MetaData_KeyInfos[i].four_cc == atom_type) {
key_name = AP4_MetaData_KeyInfos[i].name;
break;
}
}
if (key_name == NULL) {
// this key was not found in the key infos, create a name for it
AP4_FormatFourChars(four_cc, (AP4_UI32)atom_type);
key_name = four_cc;
}
value = key_name;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::AddIlstEntries
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::AddIlstEntries(AP4_ContainerAtom* atom, const char* namespc)
{
AP4_MetaData::Value* value = NULL;
if (atom->GetType() == AP4_ATOM_TYPE_dddd) {
// look for the namespace
AP4_MetaDataStringAtom* mean = static_cast<AP4_MetaDataStringAtom*>(atom->GetChild(AP4_ATOM_TYPE_MEAN));
if (mean == NULL) return AP4_ERROR_INVALID_FORMAT;
// look for the name
AP4_MetaDataStringAtom* name = static_cast<AP4_MetaDataStringAtom*>(atom->GetChild(AP4_ATOM_TYPE_NAME));
if (name == NULL) return AP4_ERROR_INVALID_FORMAT;
// get the value
AP4_DataAtom* data_atom = static_cast<AP4_DataAtom*>(atom->GetChild(AP4_ATOM_TYPE_DATA));
if (data_atom == NULL) return AP4_ERROR_INVALID_FORMAT;
value = new AP4_AtomMetaDataValue(data_atom, atom->GetType());
return m_Entries.Add(new Entry(name->GetValue().GetChars(),
mean->GetValue().GetChars(),
value));
} else {
const char* key_name = NULL;
char four_cc[5];
// convert the atom type to a name
AP4_FormatFourChars(four_cc, (AP4_UI32)atom->GetType());
key_name = four_cc;
// add one entry for each data atom
AP4_List<AP4_Atom>::Item* data_item = atom->GetChildren().FirstItem();
while (data_item) {
AP4_Atom* item_atom = data_item->GetData();
if (item_atom->GetType() == AP4_ATOM_TYPE_DATA) {
AP4_DataAtom* data_atom = static_cast<AP4_DataAtom*>(item_atom);
value = new AP4_AtomMetaDataValue(data_atom, atom->GetType());
m_Entries.Add(new Entry(key_name, namespc, value));
}
data_item = data_item->GetNext();
}
return AP4_SUCCESS;
}
}
/*----------------------------------------------------------------------
| AP4_MetaData::Add3GppEntry
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Add3GppEntry(AP4_3GppLocalizedStringAtom* atom, const char* namespc)
{
AP4_String key_name;
ResolveKeyName(atom->GetType(), key_name);
const char* language = NULL;
if (atom->GetLanguage()[0]) {
language = atom->GetLanguage();
}
AP4_MetaData::Value* value = new AP4_StringMetaDataValue(atom->GetValue().GetChars(),
language);
m_Entries.Add(new Entry(key_name.GetChars(), namespc, value));
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::AddDcfStringEntry
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::AddDcfStringEntry(AP4_DcfStringAtom* atom, const char* namespc)
{
AP4_String key_name;
ResolveKeyName(atom->GetType(), key_name);
AP4_MetaData::Value* value = new AP4_StringMetaDataValue(atom->GetValue().GetChars());
m_Entries.Add(new Entry(key_name.GetChars(), namespc, value));
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::AddDcfdEntry
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::AddDcfdEntry(AP4_DcfdAtom* atom, const char* namespc)
{
AP4_String key_name;
ResolveKeyName(atom->GetType(), key_name);
AP4_MetaData::Value* value = new AP4_IntegerMetaDataValue(AP4_MetaData::Value::TYPE_INT_32_BE,
atom->GetDuration());
m_Entries.Add(new Entry(key_name.GetChars(), namespc, value));
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Value::MapDataTypeToCategory
+---------------------------------------------------------------------*/
AP4_MetaData::Value::TypeCategory
AP4_MetaData::Value::MapTypeToCategory(Type type)
{
switch (type) {
case AP4_MetaData::Value::TYPE_INT_08_BE:
case AP4_MetaData::Value::TYPE_INT_16_BE:
case AP4_MetaData::Value::TYPE_INT_32_BE:
return AP4_MetaData::Value::TYPE_CATEGORY_INTEGER;
case AP4_MetaData::Value::TYPE_STRING_UTF_8:
case AP4_MetaData::Value::TYPE_STRING_UTF_16:
case AP4_MetaData::Value::TYPE_STRING_PASCAL:
return AP4_MetaData::Value::TYPE_CATEGORY_STRING;
case AP4_MetaData::Value::TYPE_FLOAT_32_BE:
case AP4_MetaData::Value::TYPE_FLOAT_64_BE:
return AP4_MetaData::Value::TYPE_CATEGORY_FLOAT;
default:
return AP4_MetaData::Value::TYPE_CATEGORY_BINARY;
}
}
/*----------------------------------------------------------------------
| AP4_MetaData::Value::GetTypeCategory
+---------------------------------------------------------------------*/
AP4_MetaData::Value::TypeCategory
AP4_MetaData::Value::GetTypeCategory() const
{
return MapTypeToCategory(m_Type);
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::ToAtom
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::ToAtom(AP4_Atom*& atom) const
{
atom = NULL;
if (m_Value == NULL) {
return AP4_ERROR_INVALID_PARAMETERS;
}
if (m_Key.GetNamespace() == "meta") {
// convert the name into an atom type
if (m_Key.GetName().GetLength() != 4) {
// the name is not in the right format
return AP4_ERROR_INVALID_PARAMETERS;
}
AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
// create a container atom for the data
AP4_ContainerAtom* container = new AP4_ContainerAtom(atom_type);
// add the data atom
AP4_DataAtom* data = new AP4_DataAtom(*m_Value);
container->AddChild(data);
atom = container;
return AP4_SUCCESS;
} else if (m_Key.GetNamespace() == "dcf") {
// convert the name into an atom type
if (m_Key.GetName().GetLength() != 4) {
// the name is not in the right format
return AP4_ERROR_INVALID_PARAMETERS;
}
AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
if (AP4_MetaDataAtomTypeHandler::IsTypeInList(atom_type,
AP4_MetaDataAtomTypeHandler::DcfStringTypeList)) {
AP4_String atom_value = m_Value->ToString();
atom = new AP4_DcfStringAtom(atom_type, atom_value.GetChars());
return AP4_SUCCESS;
} else if (AP4_MetaDataAtomTypeHandler::IsTypeInList(atom_type,
AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypeList)) {
AP4_String atom_value = m_Value->ToString();
const char* language = "eng"; // default
if (m_Value->GetLanguage().GetLength() != 0) {
language = m_Value->GetLanguage().GetChars();
}
atom = new AP4_3GppLocalizedStringAtom(atom_type, language, atom_value.GetChars());
return AP4_SUCCESS;
} else if (atom_type == AP4_ATOM_TYPE_DCFD) {
atom = new AP4_DcfdAtom((AP4_UI32)m_Value->ToInteger());
return AP4_SUCCESS;
}
// not supported
return AP4_ERROR_NOT_SUPPORTED;
} else {
// create a '----' atom
AP4_ContainerAtom* container = new AP4_ContainerAtom(AP4_ATOM_TYPE_dddd);
// add a 'mean' string
container->AddChild(new AP4_MetaDataStringAtom(AP4_ATOM_TYPE_MEAN, m_Key.GetNamespace().GetChars()));
// add a 'name' string
container->AddChild(new AP4_MetaDataStringAtom(AP4_ATOM_TYPE_NAME, m_Key.GetName().GetChars()));
// add the data atom
AP4_DataAtom* data = new AP4_DataAtom(*m_Value);
container->AddChild(data);
atom = container;
return AP4_SUCCESS;
}
// unreachable - return AP4_ERROR_NOT_SUPPORTED;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::FindInIlst
+---------------------------------------------------------------------*/
AP4_ContainerAtom*
AP4_MetaData::Entry::FindInIlst(AP4_ContainerAtom* ilst) const
{
if (m_Key.GetNamespace() == "meta") {
AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
return AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst->GetChild(atom_type));
} else {
AP4_List<AP4_Atom>::Item* ilst_item = ilst->GetChildren().FirstItem();
while (ilst_item) {
AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst_item->GetData());
if (entry_atom) {
AP4_MetaDataStringAtom* mean = static_cast<AP4_MetaDataStringAtom*>(entry_atom->GetChild(AP4_ATOM_TYPE_MEAN));
AP4_MetaDataStringAtom* name = static_cast<AP4_MetaDataStringAtom*>(entry_atom->GetChild(AP4_ATOM_TYPE_NAME));
if (mean && name &&
mean->GetValue() == m_Key.GetNamespace() &&
name->GetValue() == m_Key.GetName()) {
return entry_atom;
}
}
ilst_item = ilst_item->GetNext();
}
}
// not found
return NULL;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::AddToFileIlst
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::AddToFileIlst(AP4_File& file, AP4_Ordinal index)
{
// check that we have a correct entry
if (m_Value == NULL) return AP4_ERROR_INVALID_STATE;
// convert the entry into an atom
AP4_Atom* atom;
AP4_Result result = ToAtom(atom);
if (AP4_FAILED(result)) return result;
AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
if (entry_atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// look for the 'moov'
AP4_Movie* movie = file.GetMovie();
if (movie == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_MoovAtom* moov = movie->GetMoovAtom();
if (moov == NULL) return AP4_ERROR_INVALID_FORMAT;
// look for 'udta', and create if it does not exist
AP4_ContainerAtom* udta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->FindChild("udta", true));
if (udta == NULL) return AP4_ERROR_INTERNAL;
// look for 'meta', and create if it does not exist ('meta' is a FULL atom)
AP4_ContainerAtom* meta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, udta->FindChild("meta", true, true));
if (meta == NULL) return AP4_ERROR_INTERNAL;
// look for a 'hdlr' atom type 'mdir'
AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, meta->FindChild("hdlr"));
if (hdlr == NULL) {
hdlr = new AP4_HdlrAtom(AP4_HANDLER_TYPE_MDIR, "");
meta->AddChild(hdlr);
} else {
if (hdlr->GetHandlerType() != AP4_HANDLER_TYPE_MDIR) {
return AP4_ERROR_INVALID_FORMAT;
}
}
// get/create the list of entries
AP4_ContainerAtom* ilst = AP4_DYNAMIC_CAST(AP4_ContainerAtom, meta->FindChild("ilst", true));
if (ilst == NULL) return AP4_ERROR_INTERNAL;
// look if there is already a container for this entry
AP4_ContainerAtom* existing = FindInIlst(ilst);
if (existing == NULL) {
// just add the one we have
ilst->AddChild(entry_atom);
} else {
// add the entry's data to the existing entry
AP4_DataAtom* data_atom = AP4_DYNAMIC_CAST(AP4_DataAtom, entry_atom->GetChild(AP4_ATOM_TYPE_DATA));
if (data_atom == NULL) return AP4_ERROR_INTERNAL;
entry_atom->RemoveChild(data_atom);
existing->AddChild(data_atom, index);
delete entry_atom;
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::AddToFileDcf
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::AddToFileDcf(AP4_File& file, AP4_Ordinal index)
{
// check that we have a correct entry
if (m_Value == NULL) return AP4_ERROR_INVALID_STATE;
// look for 'odrm/odhe'
AP4_ContainerAtom* odhe = AP4_DYNAMIC_CAST(AP4_ContainerAtom, file.FindChild("odrm/odhe"));
if (odhe == NULL) return AP4_ERROR_NO_SUCH_ITEM;
// get/create the list of entries
AP4_ContainerAtom* udta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, odhe->FindChild("udta", true));
if (udta == NULL) return AP4_ERROR_INTERNAL;
// convert the entry into an atom
AP4_Atom* data_atom;
AP4_Result result = ToAtom(data_atom);
if (AP4_FAILED(result)) return result;
// add the entry's data to the container
return udta->AddChild(data_atom, index);
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::AddToFile
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::AddToFile(AP4_File& file, AP4_Ordinal index)
{
// check that we have a correct entry
if (m_Value == NULL) return AP4_ERROR_INVALID_STATE;
// check the namespace of the key to know where to add the atom
if (m_Key.GetNamespace() == "meta") {
return AddToFileIlst(file, index);
} else if (m_Key.GetNamespace() == "dcf") {
return AddToFileDcf(file, index);
} else {
// custom namespace
return AddToFileIlst(file, index);
}
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::RemoveFromFileIlst
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::RemoveFromFileIlst(AP4_File& file, AP4_Ordinal index)
{
// look for the 'moov'
AP4_Movie* movie = file.GetMovie();
if (movie == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_MoovAtom* moov = movie->GetMoovAtom();
if (moov == NULL) return AP4_ERROR_INVALID_FORMAT;
// look for 'udta/meta/ilst'
AP4_ContainerAtom* ilst = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->FindChild("udta/meta/ilst"));
if (ilst == NULL) return AP4_ERROR_NO_SUCH_ITEM;
// look if there is already a container for this entry
AP4_ContainerAtom* existing = FindInIlst(ilst);
if (existing == NULL) return AP4_ERROR_NO_SUCH_ITEM;
// remove the data atom in the entry
AP4_Result result = existing->DeleteChild(AP4_ATOM_TYPE_DATA, index);
if (AP4_FAILED(result)) return result;
// cleanup
if (existing->GetType() == AP4_ATOM_TYPE_dddd) {
// custom entry: if there are no more 'data' children, remove the entry
if (existing->GetChild(AP4_ATOM_TYPE_DATA) == NULL) {
ilst->RemoveChild(existing);
delete existing;
}
} else {
// normal entry: if the entry is empty, remove it
if (existing->GetChildren().ItemCount() == 0) {
ilst->RemoveChild(existing);
delete existing;
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::RemoveFromFileDcf
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::RemoveFromFileDcf(AP4_File& file, AP4_Ordinal index)
{
// look for 'odrm/odhe/udta'
AP4_ContainerAtom* udta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, file.FindChild("odrm/odhe/udta"));
if (udta == NULL) return AP4_ERROR_NO_SUCH_ITEM;
// remove the data atom in the entry
AP4_UI32 type = AP4_BytesToUInt32BE((const unsigned char*)m_Key.GetName().GetChars());
AP4_Result result = udta->DeleteChild(type, index);
if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::RemoveFromFile
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::RemoveFromFile(AP4_File& file, AP4_Ordinal index)
{
// check the namespace of the key to know where to add the atom
if (m_Key.GetNamespace() == "meta") {
return RemoveFromFileIlst(file, index);
} else if (m_Key.GetNamespace() == "dcf") {
return RemoveFromFileDcf(file, index);
} else {
// custom namespace
return RemoveFromFileIlst(file, index);
}
}
/*----------------------------------------------------------------------
| AP4_StringMetaDataValue::ToString
+---------------------------------------------------------------------*/
AP4_String
AP4_StringMetaDataValue::ToString() const
{
return m_Value;
}
/*----------------------------------------------------------------------
| AP4_StringMetaDataValue::ToBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_StringMetaDataValue::ToBytes(AP4_DataBuffer& /* bytes */) const
{
return AP4_ERROR_NOT_SUPPORTED;
}
/*----------------------------------------------------------------------
| AP4_StringMetaDataValue::ToInteger
+---------------------------------------------------------------------*/
long
AP4_StringMetaDataValue::ToInteger() const
{
return 0;
}
/*----------------------------------------------------------------------
| AP4_IntegerMetaDataValue::ToString
+---------------------------------------------------------------------*/
AP4_String
AP4_IntegerMetaDataValue::ToString() const
{
char value[16];
AP4_FormatString(value, sizeof(value), "%ld", m_Value);
return AP4_String(value);
}
/*----------------------------------------------------------------------
| AP4_IntegerMetaDataValue::ToBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_IntegerMetaDataValue::ToBytes(AP4_DataBuffer& /* bytes */) const
{
return AP4_ERROR_NOT_SUPPORTED;
}
/*----------------------------------------------------------------------
| AP4_IntegerMetaDataValue::ToInteger
+---------------------------------------------------------------------*/
long
AP4_IntegerMetaDataValue::ToInteger() const
{
return m_Value;
}
/*----------------------------------------------------------------------
| AP4_BinaryMetaDataValue::ToString
+---------------------------------------------------------------------*/
AP4_String
AP4_BinaryMetaDataValue::ToString() const
{
return AP4_String(); // not supported
}
/*----------------------------------------------------------------------
| AP4_BinaryMetaDataValue::ToBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_BinaryMetaDataValue::ToBytes(AP4_DataBuffer& bytes) const
{
bytes.SetDataSize(m_Value.GetDataSize());
AP4_CopyMemory(bytes.UseData(), m_Value.GetData(), m_Value.GetDataSize());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_BinaryMetaDataValue::ToInteger
+---------------------------------------------------------------------*/
long
AP4_BinaryMetaDataValue::ToInteger() const
{
return 0; // NOT SUPPORTED
}
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::AP4_AtomMetaDataValue
+---------------------------------------------------------------------*/
AP4_AtomMetaDataValue::AP4_AtomMetaDataValue(AP4_DataAtom* atom,
AP4_UI32 parent_type) :
Value(atom->GetValueType()),
m_DataAtom(atom)
{
switch (parent_type) {
case AP4_ATOM_TYPE_GNRE:
m_Meaning = MEANING_ID3_GENRE;
break;
case AP4_ATOM_TYPE_CPIL:
m_Meaning = MEANING_BOOLEAN;
break;
case AP4_ATOM_TYPE_PGAP:
case AP4_ATOM_TYPE_PCST:
m_Meaning = MEANING_BOOLEAN;
break;
case AP4_ATOM_TYPE_STIK:
m_Meaning = MEANING_FILE_KIND;
break;
case AP4_ATOM_TYPE_PURL:
case AP4_ATOM_TYPE_EGID:
m_Meaning = MEANING_BINARY_ENCODED_CHARS;
break;
default:
break;
}
}
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::ToString
+---------------------------------------------------------------------*/
AP4_String
AP4_AtomMetaDataValue::ToString() const
{
char string[256] = "";
AP4_MetaData::Value::Type value_type = m_DataAtom->GetValueType();
switch (AP4_MetaData::Value::MapTypeToCategory(value_type)) {
case AP4_MetaData::Value::TYPE_CATEGORY_INTEGER:
{
long value;
if (AP4_SUCCEEDED(m_DataAtom->LoadInteger(value))) {
if (m_Meaning == MEANING_BOOLEAN) {
if (value) {
return "True";
} else {
return "False";
}
} else if (m_Meaning == MEANING_FILE_KIND) {
if (value >= 0 && ((unsigned int)value) <= sizeof(Ap4StikNames)/sizeof(Ap4StikNames[0])) {
AP4_FormatString(string, sizeof(string), "(%ld) %s", value, Ap4StikNames[value]);
} else {
return "Unknown";
}
} else {
AP4_FormatString(string, sizeof(string), "%ld", value);
}
}
return AP4_String((const char*)string);
break;
}
case AP4_MetaData::Value::TYPE_CATEGORY_STRING:
{
AP4_String* category_string;
if (AP4_SUCCEEDED(m_DataAtom->LoadString(category_string))) {
AP4_String result(*category_string);
delete category_string;
return result;
}
break;
}
case AP4_MetaData::Value::TYPE_CATEGORY_BINARY:
{
AP4_DataBuffer data;
if (AP4_SUCCEEDED(m_DataAtom->LoadBytes(data))) {
if (m_Meaning == MEANING_ID3_GENRE && data.GetDataSize() == 2) {
unsigned int genre = (data.GetData()[0])*256+data.GetData()[1];
if (genre >= 1 && genre <= sizeof(Ap4Id3Genres)/sizeof(Ap4Id3Genres[0])) {
AP4_FormatString(string, sizeof(string), "(%d) %s", genre, Ap4Id3Genres[genre-1]);
return AP4_String((const char*)string);
} else {
return "Unknown";
}
} else if (m_Meaning == MEANING_BINARY_ENCODED_CHARS) {
AP4_String result;
result.Assign((const char*)data.GetData(), data.GetDataSize());
return result;
} else {
unsigned int dump_length = data.GetDataSize();
bool truncate = false;
if (dump_length > 16) {
dump_length = 16;
truncate = true;
}
char* out = string;
for (unsigned int i=0; i<dump_length; i++) {
AP4_FormatString(out, sizeof(string)-(out-string), "%02x ", data.GetData()[i]);
out += 3;
}
if (truncate) {
*out++='.'; *out++='.'; *out++='.'; *out++=' ';
}
AP4_FormatString(out, sizeof(string)-(out-string), "[%d bytes]", (int)data.GetDataSize());
}
}
return AP4_String(string);
}
default:
return AP4_String();
}
return AP4_String();
}
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::ToBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomMetaDataValue::ToBytes(AP4_DataBuffer& bytes) const
{
return m_DataAtom->LoadBytes(bytes);
}
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::ToInteger
+---------------------------------------------------------------------*/
long
AP4_AtomMetaDataValue::ToInteger() const
{
long value;
if (AP4_SUCCEEDED(m_DataAtom->LoadInteger(value))) {
return value;
} else {
return 0;
}
}
/*----------------------------------------------------------------------
| AP4_DataAtom::AP4_DataAtom
+---------------------------------------------------------------------*/
AP4_DataAtom::AP4_DataAtom(const AP4_MetaData::Value& value) :
AP4_Atom(AP4_ATOM_TYPE_DATA, AP4_ATOM_HEADER_SIZE),
m_DataType(DATA_TYPE_BINARY),
m_Source(NULL)
{
AP4_MemoryByteStream* memory = new AP4_MemoryByteStream();
AP4_Size payload_size = 8;
m_Source = memory;
switch (value.GetType()) {
case AP4_MetaData::Value::TYPE_STRING_UTF_8: {
m_DataType = DATA_TYPE_STRING_UTF_8;
AP4_String string_value = value.ToString();
if (string_value.GetLength()) {
memory->Write(string_value.GetChars(), string_value.GetLength());
}
payload_size += string_value.GetLength();
break;
}
case AP4_MetaData::Value::TYPE_INT_08_BE: {
m_DataType = DATA_TYPE_SIGNED_INT_BE;
AP4_UI08 int_value = (AP4_UI08)value.ToInteger();
memory->Write(&int_value, 1);
payload_size += 1;
break;
}
case AP4_MetaData::Value::TYPE_INT_16_BE: {
m_DataType = DATA_TYPE_SIGNED_INT_BE;
AP4_UI16 int_value = (AP4_UI16)value.ToInteger();
memory->Write(&int_value, 2);
payload_size += 2;
break;
}
case AP4_MetaData::Value::TYPE_INT_32_BE: {
m_DataType = DATA_TYPE_SIGNED_INT_BE;
AP4_UI32 int_value = (AP4_UI32)value.ToInteger();
memory->Write(&int_value, 4);
payload_size += 4;
break;
}
case AP4_MetaData::Value::TYPE_JPEG:
m_DataType = DATA_TYPE_JPEG;
// FALLTHROUGH
case AP4_MetaData::Value::TYPE_GIF:
if (m_DataType == DATA_TYPE_BINARY) m_DataType = DATA_TYPE_GIF;
// FALLTHROUGH
case AP4_MetaData::Value::TYPE_BINARY: {
AP4_DataBuffer buffer;
value.ToBytes(buffer);
if (buffer.GetDataSize()) {
memory->Write(buffer.GetData(), buffer.GetDataSize());
}
payload_size += buffer.GetDataSize();
break;
}
default:
break;
}
const AP4_String& language = value.GetLanguage();
if (language == "en") {
m_DataLang = LANGUAGE_ENGLISH;
} else {
// default
m_DataLang = LANGUAGE_ENGLISH;
}
m_Size32 += payload_size;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::AP4_DataAtom
+---------------------------------------------------------------------*/
AP4_DataAtom::AP4_DataAtom(AP4_UI32 size, AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_DATA, size),
m_Source(NULL)
{
if (size < AP4_ATOM_HEADER_SIZE+8) return;
AP4_UI32 i;
stream.ReadUI32(i); m_DataType = (DataType)i;
stream.ReadUI32(i); m_DataLang = (DataLang)i;
// the stream for the data is a substream of this source
AP4_Position data_offset;
stream.Tell(data_offset);
AP4_Size data_size = size-AP4_ATOM_HEADER_SIZE-8;
m_Source = new AP4_SubStream(stream, data_offset, data_size);
}
/*----------------------------------------------------------------------
| AP4_DataAtom::~AP4_DataAtom
+---------------------------------------------------------------------*/
AP4_DataAtom::~AP4_DataAtom()
{
delete(m_Source);
}
/*----------------------------------------------------------------------
| AP4_DataAtom::GetValueType
+---------------------------------------------------------------------*/
AP4_MetaData::Value::Type
AP4_DataAtom::GetValueType()
{
switch (m_DataType) {
case DATA_TYPE_BINARY:
return AP4_MetaData::Value::TYPE_BINARY;
case DATA_TYPE_SIGNED_INT_BE:
switch (m_Size32-16) {
case 1: return AP4_MetaData::Value::TYPE_INT_08_BE;
case 2: return AP4_MetaData::Value::TYPE_INT_16_BE;
case 4: return AP4_MetaData::Value::TYPE_INT_32_BE;
default: return AP4_MetaData::Value::TYPE_BINARY;
}
break;
case DATA_TYPE_STRING_UTF_8:
return AP4_MetaData::Value::TYPE_STRING_UTF_8;
case DATA_TYPE_STRING_UTF_16:
return AP4_MetaData::Value::TYPE_STRING_UTF_16;
case DATA_TYPE_STRING_PASCAL:
return AP4_MetaData::Value::TYPE_STRING_PASCAL;
case DATA_TYPE_GIF:
return AP4_MetaData::Value::TYPE_GIF;
case DATA_TYPE_JPEG:
return AP4_MetaData::Value::TYPE_JPEG;
default:
return AP4_MetaData::Value::TYPE_BINARY;
}
// unreachable - return AP4_MetaData::Value::TYPE_BINARY;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI32(m_DataType);
stream.WriteUI32(m_DataLang);
if (m_Source) {
AP4_LargeSize size = 0;
m_Source->GetSize(size);
m_Source->Seek(0);
m_Source->CopyTo(stream, size);
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("type", m_DataType);
inspector.AddField("lang", m_DataLang);
if (m_DataType == DATA_TYPE_STRING_UTF_8) {
AP4_String* str;
if (AP4_SUCCEEDED(LoadString(str))) {
inspector.AddField("value", str->GetChars());
delete str;
}
} else if (m_DataType == DATA_TYPE_SIGNED_INT_BE) {
long value;
if (AP4_SUCCEEDED(LoadInteger(value))) {
inspector.AddField("value", value);
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::LoadString
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::LoadString(AP4_String*& string)
{
if (m_Source == NULL) {
string = new AP4_String();
return AP4_SUCCESS;
} else {
// create a string with enough capactiy for the data
AP4_LargeSize size = 0;
m_Source->GetSize(size);
if (size > AP4_DATA_ATOM_MAX_SIZE) return AP4_ERROR_OUT_OF_RANGE;
string = new AP4_String((AP4_Size)size);
// read from the start of the stream
m_Source->Seek(0);
AP4_Result result = m_Source->Read(string->UseChars(), (AP4_Size)size);
if (AP4_FAILED(result)) {
delete string;
string = NULL;
}
return result;
}
}
/*----------------------------------------------------------------------
| AP4_DataAtom::LoadBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::LoadBytes(AP4_DataBuffer& bytes)
{
if (m_Source == NULL) {
bytes.SetDataSize(0);
return AP4_SUCCESS;
}
AP4_LargeSize size = 0;
m_Source->GetSize(size);
if (size > AP4_DATA_ATOM_MAX_SIZE) return AP4_ERROR_OUT_OF_RANGE;
bytes.SetDataSize((AP4_Size)size);
m_Source->Seek(0);
AP4_Result result = m_Source->Read(bytes.UseData(), (AP4_Size)size);
if (AP4_FAILED(result)) {
bytes.SetDataSize(0);
}
return result;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::LoadInteger
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::LoadInteger(long& value)
{
AP4_Result result = AP4_FAILURE;
value = 0;
if (m_Source == NULL) return AP4_SUCCESS;
AP4_LargeSize size = 0;
m_Source->GetSize(size);
if (size > 4) {
return AP4_ERROR_OUT_OF_RANGE;
}
unsigned char bytes[4];
m_Source->Seek(0);
m_Source->Read(bytes, (AP4_Size)size);
result = AP4_SUCCESS;
switch (size) {
case 1: value = bytes[0]; break;
case 2: value = AP4_BytesToInt16BE(bytes); break;
case 4: value = AP4_BytesToInt32BE(bytes); break;
default: value = 0; result = AP4_ERROR_INVALID_FORMAT; break;
}
return result;
}
/*----------------------------------------------------------------------
| AP4_MetaDataStringAtom::AP4_MetaDataStringAtom
+---------------------------------------------------------------------*/
AP4_MetaDataStringAtom::AP4_MetaDataStringAtom(Type type, const char* value) :
AP4_Atom(type, AP4_ATOM_HEADER_SIZE),
m_Reserved(0),
m_Value(value)
{
m_Size32 += 4+m_Value.GetLength();
}
/*----------------------------------------------------------------------
| AP4_MetaDataStringAtom::AP4_MetaDataStringAtom
+---------------------------------------------------------------------*/
AP4_MetaDataStringAtom::AP4_MetaDataStringAtom(Type type, AP4_UI32 size, AP4_ByteStream& stream) :
AP4_Atom(type, size),
m_Reserved(0),
m_Value((AP4_Size)(size-AP4_ATOM_HEADER_SIZE-4))
{
stream.ReadUI32(m_Reserved);
stream.Read(m_Value.UseChars(), m_Value.GetLength());
}
/*----------------------------------------------------------------------
| AP4_MetaDataStringAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaDataStringAtom::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI32(m_Reserved);
return stream.Write(m_Value.GetChars(), m_Value.GetLength());
}
/*----------------------------------------------------------------------
| AP4_MetaDataStringAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaDataStringAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("value", m_Value.GetChars());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::Create
+---------------------------------------------------------------------*/
AP4_3GppLocalizedStringAtom*
AP4_3GppLocalizedStringAtom::Create(Type type, AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI08 version;
AP4_UI32 flags;
if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
if (version != 0) return NULL;
return new AP4_3GppLocalizedStringAtom(type, size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom
+---------------------------------------------------------------------*/
AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom(Type type,
const char* language,
const char* value) :
AP4_Atom(type, AP4_FULL_ATOM_HEADER_SIZE+2, 0, 0),
m_Value(value)
{
m_Language[0] = language[0];
m_Language[1] = language[1];
m_Language[2] = language[2];
m_Language[3] = language[3];
m_Size32 += m_Value.GetLength()+1;
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom
+---------------------------------------------------------------------*/
AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom(Type type,
AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(type, size, version, flags)
{
// read the language code
AP4_UI16 packed_language;
stream.ReadUI16(packed_language);
m_Language[0] = 0x60+((packed_language>>10)&0x1F);
m_Language[1] = 0x60+((packed_language>> 5)&0x1F);
m_Language[2] = 0x60+((packed_language )&0x1F);
m_Language[3] = '\0';
// read the value (should be a NULL-terminated string, but we'll
// allow for strings that are not terminated)
if (size > AP4_FULL_ATOM_HEADER_SIZE+2) {
AP4_UI32 value_size = size-(AP4_FULL_ATOM_HEADER_SIZE+2);
char* value = new char[value_size];
stream.Read(value, value_size);
m_Value.Assign(value, value_size);
delete[] value;
}
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_3GppLocalizedStringAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_UI16 packed_language = ((m_Language[0]-0x60)<<10) |
((m_Language[1]-0x60)<< 5) |
((m_Language[2]-0x60));
stream.WriteUI16(packed_language);
AP4_Size payload_size = (AP4_UI32)GetSize()-GetHeaderSize();
if (payload_size < 2) return AP4_ERROR_INVALID_FORMAT;
AP4_Size value_size = m_Value.GetLength()+1;
if (value_size > payload_size-2) {
value_size = payload_size-2;
}
stream.Write(m_Value.GetChars(), value_size);
for (unsigned int i=value_size; i<payload_size-2; i++) {
stream.WriteUI08(0);
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_3GppLocalizedStringAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("language", GetLanguage());
inspector.AddField("value", m_Value.GetChars());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::Create
+---------------------------------------------------------------------*/
AP4_DcfStringAtom*
AP4_DcfStringAtom::Create(Type type, AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI08 version;
AP4_UI32 flags;
if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
if (version != 0) return NULL;
return new AP4_DcfStringAtom(type, size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::AP4_DcfStringAtom
+---------------------------------------------------------------------*/
AP4_DcfStringAtom::AP4_DcfStringAtom(Type type, const char* value) :
AP4_Atom(type, AP4_FULL_ATOM_HEADER_SIZE, 0, 0),
m_Value(value)
{
m_Size32 += m_Value.GetLength();
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::AP4_DcfStringAtom
+---------------------------------------------------------------------*/
AP4_DcfStringAtom::AP4_DcfStringAtom(Type type,
AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(type, size, version, flags)
{
if (size > AP4_FULL_ATOM_HEADER_SIZE) {
AP4_UI32 value_size = size-(AP4_FULL_ATOM_HEADER_SIZE);
char* value = new char[value_size];
stream.Read(value, value_size);
m_Value.Assign(value, value_size);
delete[] value;
}
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DcfStringAtom::WriteFields(AP4_ByteStream& stream)
{
if (m_Value.GetLength()) stream.Write(m_Value.GetChars(), m_Value.GetLength());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DcfStringAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("value", m_Value.GetChars());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::Create
+---------------------------------------------------------------------*/
AP4_DcfdAtom*
AP4_DcfdAtom::Create(AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI08 version;
AP4_UI32 flags;
if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
if (version != 0) return NULL;
if (size != AP4_FULL_ATOM_HEADER_SIZE+4) return NULL;
return new AP4_DcfdAtom(version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::AP4_DcfdAtom
+---------------------------------------------------------------------*/
AP4_DcfdAtom::AP4_DcfdAtom(AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_DCFD, AP4_FULL_ATOM_HEADER_SIZE+4, version, flags),
m_Duration(0)
{
stream.ReadUI32(m_Duration);
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::AP4_DcfdAtom
+---------------------------------------------------------------------*/
AP4_DcfdAtom::AP4_DcfdAtom(AP4_UI32 duration) :
AP4_Atom(AP4_ATOM_TYPE_DCFD, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0),
m_Duration(duration)
{
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DcfdAtom::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI32(m_Duration);
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DcfdAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("duration", m_Duration);
return AP4_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_2810_0 |
crossvul-cpp_data_good_393_0 | #include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <utility>
#include <vector>
#include "Emscripten/Emscripten.h"
#include "IR/Module.h"
#include "IR/Operators.h"
#include "IR/Types.h"
#include "IR/Validate.h"
#include "IR/Value.h"
#include "Inline/BasicTypes.h"
#include "Inline/CLI.h"
#include "Inline/Errors.h"
#include "Inline/Hash.h"
#include "Inline/HashMap.h"
#include "Inline/Serialization.h"
#include "Inline/Timing.h"
#include "Logging/Logging.h"
#include "Runtime/Linker.h"
#include "Runtime/Runtime.h"
#include "ThreadTest/ThreadTest.h"
#include "WASTParse/WASTParse.h"
using namespace IR;
using namespace Runtime;
struct RootResolver : Resolver
{
Compartment* compartment;
HashMap<std::string, ModuleInstance*> moduleNameToInstanceMap;
RootResolver(Compartment* inCompartment) : compartment(inCompartment) {}
bool resolve(const std::string& moduleName,
const std::string& exportName,
ObjectType type,
Object*& outObject) override
{
auto namedInstance = moduleNameToInstanceMap.get(moduleName);
if(namedInstance)
{
outObject = getInstanceExport(*namedInstance, exportName);
if(outObject)
{
if(isA(outObject, type)) { return true; }
else
{
Log::printf(Log::error,
"Resolved import %s.%s to a %s, but was expecting %s\n",
moduleName.c_str(),
exportName.c_str(),
asString(getObjectType(outObject)).c_str(),
asString(type).c_str());
return false;
}
}
}
Log::printf(Log::error,
"Generated stub for missing import %s.%s : %s\n",
moduleName.c_str(),
exportName.c_str(),
asString(type).c_str());
outObject = getStubObject(exportName, type);
return true;
}
Object* getStubObject(const std::string& exportName, ObjectType type) const
{
// If the import couldn't be resolved, stub it in.
switch(type.kind)
{
case IR::ObjectKind::function:
{
// Generate a function body that just uses the unreachable op to fault if called.
Serialization::ArrayOutputStream codeStream;
OperatorEncoderStream encoder(codeStream);
encoder.unreachable();
encoder.end();
// Generate a module for the stub function.
IR::Module stubModule;
DisassemblyNames stubModuleNames;
stubModule.types.push_back(asFunctionType(type));
stubModule.functions.defs.push_back({{0}, {}, std::move(codeStream.getBytes()), {}});
stubModule.exports.push_back({"importStub", IR::ObjectKind::function, 0});
stubModuleNames.functions.push_back({"importStub: " + exportName, {}, {}});
IR::setDisassemblyNames(stubModule, stubModuleNames);
IR::validateDefinitions(stubModule);
// Instantiate the module and return the stub function instance.
auto stubModuleInstance
= instantiateModule(compartment, compileModule(stubModule), {}, "importStub");
return getInstanceExport(stubModuleInstance, "importStub");
}
case IR::ObjectKind::memory:
{
return asObject(Runtime::createMemory(compartment, asMemoryType(type)));
}
case IR::ObjectKind::table:
{
return asObject(Runtime::createTable(compartment, asTableType(type)));
}
case IR::ObjectKind::global:
{
return asObject(Runtime::createGlobal(
compartment,
asGlobalType(type),
IR::Value(asGlobalType(type).valueType, IR::UntaggedValue())));
}
case IR::ObjectKind::exceptionType:
{
return asObject(
Runtime::createExceptionTypeInstance(asExceptionType(type), "importStub"));
}
default: Errors::unreachable();
};
}
};
struct CommandLineOptions
{
const char* filename = nullptr;
const char* functionName = nullptr;
char** args = nullptr;
bool onlyCheck = false;
bool enableEmscripten = true;
bool enableThreadTest = false;
bool precompiled = false;
};
static int run(const CommandLineOptions& options)
{
IR::Module irModule;
// Load the module.
if(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; }
if(options.onlyCheck) { return EXIT_SUCCESS; }
// Compile the module.
Runtime::Module* module = nullptr;
if(!options.precompiled) { module = Runtime::compileModule(irModule); }
else
{
const UserSection* precompiledObjectSection = nullptr;
for(const UserSection& userSection : irModule.userSections)
{
if(userSection.name == "wavm.precompiled_object")
{
precompiledObjectSection = &userSection;
break;
}
}
if(!precompiledObjectSection)
{
Log::printf(Log::error, "Input file did not contain 'wavm.precompiled_object' section");
return EXIT_FAILURE;
}
else
{
module = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data);
}
}
// Link the module with the intrinsic modules.
Compartment* compartment = Runtime::createCompartment();
Context* context = Runtime::createContext(compartment);
RootResolver rootResolver(compartment);
Emscripten::Instance* emscriptenInstance = nullptr;
if(options.enableEmscripten)
{
emscriptenInstance = Emscripten::instantiate(compartment, irModule);
if(emscriptenInstance)
{
rootResolver.moduleNameToInstanceMap.set("env", emscriptenInstance->env);
rootResolver.moduleNameToInstanceMap.set("asm2wasm", emscriptenInstance->asm2wasm);
rootResolver.moduleNameToInstanceMap.set("global", emscriptenInstance->global);
}
}
if(options.enableThreadTest)
{
ModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment);
rootResolver.moduleNameToInstanceMap.set("threadTest", threadTestInstance);
}
LinkResult linkResult = linkModule(irModule, rootResolver);
if(!linkResult.success)
{
Log::printf(Log::error, "Failed to link module:\n");
for(auto& missingImport : linkResult.missingImports)
{
Log::printf(Log::error,
"Missing import: module=\"%s\" export=\"%s\" type=\"%s\"\n",
missingImport.moduleName.c_str(),
missingImport.exportName.c_str(),
asString(missingImport.type).c_str());
}
return EXIT_FAILURE;
}
// Instantiate the module.
ModuleInstance* moduleInstance = instantiateModule(
compartment, module, std::move(linkResult.resolvedImports), options.filename);
if(!moduleInstance) { return EXIT_FAILURE; }
// Call the module start function, if it has one.
FunctionInstance* startFunction = getStartFunction(moduleInstance);
if(startFunction) { invokeFunctionChecked(context, startFunction, {}); }
if(options.enableEmscripten)
{
// Call the Emscripten global initalizers.
Emscripten::initializeGlobals(context, irModule, moduleInstance);
}
// Look up the function export to call.
FunctionInstance* functionInstance;
if(!options.functionName)
{
functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "main"));
if(!functionInstance)
{ functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "_main")); }
if(!functionInstance)
{
Log::printf(Log::error, "Module does not export main function\n");
return EXIT_FAILURE;
}
}
else
{
functionInstance
= asFunctionNullable(getInstanceExport(moduleInstance, options.functionName));
if(!functionInstance)
{
Log::printf(Log::error, "Module does not export '%s'\n", options.functionName);
return EXIT_FAILURE;
}
}
FunctionType functionType = getFunctionType(functionInstance);
// Set up the arguments for the invoke.
std::vector<Value> invokeArgs;
if(!options.functionName)
{
if(functionType.params().size() == 2)
{
if(!emscriptenInstance)
{
Log::printf(
Log::error,
"Module does not declare a default memory object to put arguments in.\n");
return EXIT_FAILURE;
}
else
{
std::vector<const char*> argStrings;
argStrings.push_back(options.filename);
char** args = options.args;
while(*args) { argStrings.push_back(*args++); };
wavmAssert(emscriptenInstance);
Emscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);
}
}
else if(functionType.params().size() > 0)
{
Log::printf(Log::error,
"WebAssembly function requires %" PRIu64
" argument(s), but only 0 or 2 can be passed!",
functionType.params().size());
return EXIT_FAILURE;
}
}
else
{
for(U32 i = 0; options.args[i]; ++i)
{
Value value;
switch(functionType.params()[i])
{
case ValueType::i32: value = (U32)atoi(options.args[i]); break;
case ValueType::i64: value = (U64)atol(options.args[i]); break;
case ValueType::f32: value = (F32)atof(options.args[i]); break;
case ValueType::f64: value = atof(options.args[i]); break;
case ValueType::v128:
case ValueType::anyref:
case ValueType::anyfunc:
Errors::fatalf("Cannot parse command-line argument for %s function parameter",
asString(functionType.params()[i]));
default: Errors::unreachable();
}
invokeArgs.push_back(value);
}
}
// Invoke the function.
Timing::Timer executionTimer;
IR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs);
Timing::logTimer("Invoked function", executionTimer);
if(options.functionName)
{
Log::printf(Log::debug,
"%s returned: %s\n",
options.functionName,
asString(functionResults).c_str());
return EXIT_SUCCESS;
}
else if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32)
{
return functionResults[0].i32;
}
else
{
return EXIT_SUCCESS;
}
}
static void showHelp()
{
Log::printf(Log::error,
"Usage: wavm [switches] [programfile] [--] [arguments]\n"
" in.wast|in.wasm Specify program file (.wast/.wasm)\n"
" -c|--check Exit after checking that the program is valid\n"
" -d|--debug Write additional debug information to stdout\n"
" -f|--function name Specify function name to run in module rather than main\n"
" -h|--help Display this message\n"
" --disable-emscripten Disable Emscripten intrinsics\n"
" --enable-thread-test Enable ThreadTest intrinsics\n"
" --precompiled Use precompiled object code in programfile\n"
" -- Stop parsing arguments\n");
}
int main(int argc, char** argv)
{
CommandLineOptions options;
options.args = argv;
while(*++options.args)
{
if(!strcmp(*options.args, "--function") || !strcmp(*options.args, "-f"))
{
if(!*++options.args)
{
showHelp();
return EXIT_FAILURE;
}
options.functionName = *options.args;
}
else if(!strcmp(*options.args, "--check") || !strcmp(*options.args, "-c"))
{
options.onlyCheck = true;
}
else if(!strcmp(*options.args, "--debug") || !strcmp(*options.args, "-d"))
{
Log::setCategoryEnabled(Log::debug, true);
}
else if(!strcmp(*options.args, "--disable-emscripten"))
{
options.enableEmscripten = false;
}
else if(!strcmp(*options.args, "--enable-thread-test"))
{
options.enableThreadTest = true;
}
else if(!strcmp(*options.args, "--precompiled"))
{
options.precompiled = true;
}
else if(!strcmp(*options.args, "--"))
{
++options.args;
break;
}
else if(!strcmp(*options.args, "--help") || !strcmp(*options.args, "-h"))
{
showHelp();
return EXIT_SUCCESS;
}
else if(!options.filename)
{
options.filename = *options.args;
}
else
{
break;
}
}
if(!options.filename)
{
showHelp();
return EXIT_FAILURE;
}
// Treat any unhandled exception (e.g. in a thread) as a fatal error.
Runtime::setUnhandledExceptionHandler([](Runtime::Exception&& exception) {
Errors::fatalf("Runtime exception: %s\n", describeException(exception).c_str());
});
return run(options);
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_393_0 |
crossvul-cpp_data_bad_2807_0 | /*****************************************************************
|
| AP4 - Atom Factory
|
| Copyright 2002-2012 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4Types.h"
#include "Ap4Utils.h"
#include "Ap4AtomFactory.h"
#include "Ap4SampleEntry.h"
#include "Ap4UuidAtom.h"
#include "Ap4IsmaCryp.h"
#include "Ap4UrlAtom.h"
#include "Ap4MoovAtom.h"
#include "Ap4MvhdAtom.h"
#include "Ap4MehdAtom.h"
#include "Ap4MfhdAtom.h"
#include "Ap4TfhdAtom.h"
#include "Ap4TrunAtom.h"
#include "Ap4TrakAtom.h"
#include "Ap4HdlrAtom.h"
#include "Ap4DrefAtom.h"
#include "Ap4TkhdAtom.h"
#include "Ap4TrexAtom.h"
#include "Ap4TfhdAtom.h"
#include "Ap4MdhdAtom.h"
#include "Ap4StsdAtom.h"
#include "Ap4StscAtom.h"
#include "Ap4StcoAtom.h"
#include "Ap4Co64Atom.h"
#include "Ap4StszAtom.h"
#include "Ap4Stz2Atom.h"
#include "Ap4IodsAtom.h"
#include "Ap4EsdsAtom.h"
#include "Ap4SttsAtom.h"
#include "Ap4CttsAtom.h"
#include "Ap4StssAtom.h"
#include "Ap4FtypAtom.h"
#include "Ap4VmhdAtom.h"
#include "Ap4SmhdAtom.h"
#include "Ap4NmhdAtom.h"
#include "Ap4SthdAtom.h"
#include "Ap4HmhdAtom.h"
#include "Ap4ElstAtom.h"
#include "Ap4SchmAtom.h"
#include "Ap4FrmaAtom.h"
#include "Ap4TimsAtom.h"
#include "Ap4RtpAtom.h"
#include "Ap4SdpAtom.h"
#include "Ap4IkmsAtom.h"
#include "Ap4IsfmAtom.h"
#include "Ap4IsltAtom.h"
#include "Ap4OdheAtom.h"
#include "Ap4OhdrAtom.h"
#include "Ap4OddaAtom.h"
#include "Ap4TrefTypeAtom.h"
#include "Ap4MetaData.h"
#include "Ap4IproAtom.h"
#include "Ap4OdafAtom.h"
#include "Ap4GrpiAtom.h"
#include "Ap4AvccAtom.h"
#include "Ap4HvccAtom.h"
#include "Ap4DvccAtom.h"
#include "Ap4Marlin.h"
#include "Ap48bdlAtom.h"
#include "Ap4Piff.h"
#include "Ap4TfraAtom.h"
#include "Ap4MfroAtom.h"
#include "Ap4TfdtAtom.h"
#include "Ap4TencAtom.h"
#include "Ap4SencAtom.h"
#include "Ap4SaioAtom.h"
#include "Ap4SaizAtom.h"
#include "Ap4PdinAtom.h"
#include "Ap4BlocAtom.h"
#include "Ap4AinfAtom.h"
#include "Ap4PsshAtom.h"
#include "Ap4Dec3Atom.h"
#include "Ap4SidxAtom.h"
#include "Ap4SbgpAtom.h"
#include "Ap4SgpdAtom.h"
/*----------------------------------------------------------------------
| AP4_AtomFactory::~AP4_AtomFactory
+---------------------------------------------------------------------*/
AP4_AtomFactory::~AP4_AtomFactory()
{
m_TypeHandlers.DeleteReferences();
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::AddTypeHandler
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::AddTypeHandler(TypeHandler* handler)
{
return m_TypeHandlers.Add(handler);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::RemoveTypeHandler
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::RemoveTypeHandler(TypeHandler* handler)
{
return m_TypeHandlers.Remove(handler);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_Atom*& atom)
{
AP4_LargeSize stream_size = 0;
AP4_Position stream_position = 0;
AP4_LargeSize bytes_available = (AP4_LargeSize)(-1);
if (AP4_SUCCEEDED(stream.GetSize(stream_size)) &&
stream_size != 0 &&
AP4_SUCCEEDED(stream.Tell(stream_position)) &&
stream_position <= stream_size) {
bytes_available = stream_size-stream_position;
}
return CreateAtomFromStream(stream, bytes_available, atom);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_LargeSize& bytes_available,
AP4_Atom*& atom)
{
AP4_Result result;
// NULL by default
atom = NULL;
// check that there are enough bytes for at least a header
if (bytes_available < 8) return AP4_ERROR_EOS;
// remember current stream offset
AP4_Position start;
stream.Tell(start);
// read atom size
AP4_UI32 size_32;
result = stream.ReadUI32(size_32);
if (AP4_FAILED(result)) {
stream.Seek(start);
return result;
}
AP4_UI64 size = size_32;
// read atom type
AP4_Atom::Type type;
result = stream.ReadUI32(type);
if (AP4_FAILED(result)) {
stream.Seek(start);
return result;
}
// handle special size values
bool atom_is_large = false;
bool force_64 = false;
if (size == 0) {
// atom extends to end of file
AP4_LargeSize stream_size = 0;
stream.GetSize(stream_size);
if (stream_size >= start) {
size = stream_size - start;
}
} else if (size == 1) {
// 64-bit size
atom_is_large = true;
if (bytes_available < 16) {
stream.Seek(start);
return AP4_ERROR_INVALID_FORMAT;
}
stream.ReadUI64(size);
if (size <= 0xFFFFFFFF) {
force_64 = true;
}
}
// check the size
if ((size > 0 && size < 8) || size > bytes_available) {
stream.Seek(start);
return AP4_ERROR_INVALID_FORMAT;
}
// create the atom
result = CreateAtomFromStream(stream, type, size_32, size, atom);
if (AP4_FAILED(result)) return result;
// if we failed to create an atom, use a generic version
if (atom == NULL) {
unsigned int payload_offset = 8;
if (atom_is_large) payload_offset += 8;
stream.Seek(start+payload_offset);
atom = new AP4_UnknownAtom(type, size, stream);
}
// special case: if the atom is poorly encoded and has a 64-bit
// size header but an actual size that fits on 32-bit, adjust the
// object to reflect that.
if (force_64) {
atom->SetSize32(1);
atom->SetSize64(size);
}
// adjust the available size
bytes_available -= size;
// skip to the end of the atom
result = stream.Seek(start+size);
if (AP4_FAILED(result)) {
delete atom;
atom = NULL;
return result;
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_UI32 type,
AP4_UI32 size_32,
AP4_UI64 size_64,
AP4_Atom*& atom)
{
bool atom_is_large = (size_32 == 1);
bool force_64 = (size_32==1 && ((size_64>>32) == 0));
// create the atom
if (GetContext() == AP4_ATOM_TYPE_STSD) {
// sample entry
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
switch (type) {
case AP4_ATOM_TYPE_MP4A:
atom = new AP4_Mp4aSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MP4V:
atom = new AP4_Mp4vSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MP4S:
atom = new AP4_Mp4sSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ENCA:
atom = new AP4_EncaSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ENCV:
atom = new AP4_EncvSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_DRMS:
atom = new AP4_DrmsSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_DRMI:
atom = new AP4_DrmiSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_AVC1:
case AP4_ATOM_TYPE_AVC2:
case AP4_ATOM_TYPE_AVC3:
case AP4_ATOM_TYPE_AVC4:
case AP4_ATOM_TYPE_DVAV:
case AP4_ATOM_TYPE_DVA1:
atom = new AP4_AvcSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_HEV1:
case AP4_ATOM_TYPE_HVC1:
case AP4_ATOM_TYPE_DVHE:
case AP4_ATOM_TYPE_DVH1:
atom = new AP4_HevcSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ALAC:
case AP4_ATOM_TYPE_AC_3:
case AP4_ATOM_TYPE_EC_3:
case AP4_ATOM_TYPE_DTSC:
case AP4_ATOM_TYPE_DTSH:
case AP4_ATOM_TYPE_DTSL:
case AP4_ATOM_TYPE_DTSE:
atom = new AP4_AudioSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_RTP_:
atom = new AP4_RtpHintSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_STPP:
atom = new AP4_SubtitleSampleEntry(type, size_32, stream, *this);
break;
default: {
// try all the external type handlers
AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
while (handler_item) {
TypeHandler* handler = handler_item->GetData();
if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
break;
}
handler_item = handler_item->GetNext();
}
// no custom handler, create a generic entry
if (atom == NULL) {
atom = new AP4_UnknownSampleEntry(type, (AP4_UI32)size_64, stream);
}
break;
}
}
} else {
// regular atom
switch (type) {
case AP4_ATOM_TYPE_MOOV:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MoovAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MVHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MvhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MEHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MehdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MFHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TRAK:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrakAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_TREX:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrexAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HDLR:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HdlrAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TKHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TkhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TRUN:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrunAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFRA:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfraAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MFRO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfroAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MDHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MdhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StsdAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_STSC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StscAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STCO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StcoAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_CO64:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_Co64Atom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSZ:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StszAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STZ2:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_Stz2Atom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STTS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SttsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_CTTS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_CttsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StssAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IODS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IodsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ESDS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_EsdsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_AVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_DVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_DvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HVCE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HvccAtom::Create(size_32, stream);
atom->SetType(AP4_ATOM_TYPE_HVCE);
break;
case AP4_ATOM_TYPE_AVCE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AvccAtom::Create(size_32, stream);
atom->SetType(AP4_ATOM_TYPE_AVCE);
break;
#if !defined(AP4_CONFIG_MINI_BUILD)
case AP4_ATOM_TYPE_UUID: {
AP4_UI08 uuid[16];
AP4_Result result = stream.Read(uuid, 16);
if (AP4_FAILED(result)) return result;
if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 16) == 0) {
atom = AP4_PiffTrackEncryptionAtom::Create((AP4_UI32)size_64, stream);
} else if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 16) == 0) {
atom = AP4_PiffSampleEncryptionAtom::Create((AP4_UI32)size_64, stream);
} else {
atom = new AP4_UnknownUuidAtom(size_64, uuid, stream);
}
break;
}
case AP4_ATOM_TYPE_8ID_:
atom = new AP4_NullTerminatedStringAtom(type, size_64, stream);
break;
case AP4_ATOM_TYPE_8BDL:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_8bdlAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_DREF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_DrefAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_URL:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_UrlAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ELST:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ElstAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_VMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_VmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_NMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_NmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SthdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_FRMA:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FrmaAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SCHM:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SchmAtom::Create(size_32, &m_ContextStack, stream);
break;
case AP4_ATOM_TYPE_FTYP:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FtypAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TIMS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TimsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SDP_:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SdpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IKMS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IkmsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ISFM:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsfmAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ISLT:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsltAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ODHE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdheAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_OHDR:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OhdrAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ODDA:
atom = AP4_OddaAtom::Create(size_64, stream);
break;
case AP4_ATOM_TYPE_ODAF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdafAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_GRPI:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_GrpiAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IPRO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IproAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_RTP_:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_RtpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFDT:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfdtAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TENC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TencAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SENC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SencAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SAIZ:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SaizAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SAIO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SaioAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_PDIN:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_PdinAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_BLOC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_BlocAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_AINF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AinfAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_PSSH:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_PsshAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SIDX:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SidxAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SBGP:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SbgpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SGPD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SgpdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MKID:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
if (GetContext() == AP4_ATOM_TYPE_MARL) {
atom = AP4_MkidAtom::Create(size_32, stream);
}
break;
case AP4_ATOM_TYPE_DEC3:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
if (GetContext() == AP4_ATOM_TYPE_EC_3 || GetContext() == AP4_ATOM_TYPE_ENCA) {
atom = AP4_Dec3Atom::Create(size_32, stream);
}
break;
// track ref types
case AP4_ATOM_TYPE_HINT:
case AP4_ATOM_TYPE_CDSC:
case AP4_ATOM_TYPE_SYNC:
case AP4_ATOM_TYPE_MPOD:
case AP4_ATOM_TYPE_DPND:
case AP4_ATOM_TYPE_IPIR:
case AP4_ATOM_TYPE_ALIS:
case AP4_ATOM_TYPE_CHAP:
if (GetContext() == AP4_ATOM_TYPE_TREF) {
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrefTypeAtom::Create(type, size_32, stream);
}
break;
#endif // AP4_CONFIG_MINI_BUILD
// container atoms
case AP4_ATOM_TYPE_MOOF:
case AP4_ATOM_TYPE_MVEX:
case AP4_ATOM_TYPE_TRAF:
case AP4_ATOM_TYPE_TREF:
case AP4_ATOM_TYPE_MFRA:
case AP4_ATOM_TYPE_HNTI:
case AP4_ATOM_TYPE_STBL:
case AP4_ATOM_TYPE_MDIA:
case AP4_ATOM_TYPE_DINF:
case AP4_ATOM_TYPE_MINF:
case AP4_ATOM_TYPE_SCHI:
case AP4_ATOM_TYPE_SINF:
case AP4_ATOM_TYPE_UDTA:
case AP4_ATOM_TYPE_ILST:
case AP4_ATOM_TYPE_EDTS:
case AP4_ATOM_TYPE_MDRI:
case AP4_ATOM_TYPE_WAVE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this);
break;
// containers, only at the top
case AP4_ATOM_TYPE_MARL:
if (GetContext() == 0) {
atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this);
}
break;
// full container atoms
case AP4_ATOM_TYPE_META:
case AP4_ATOM_TYPE_ODRM:
case AP4_ATOM_TYPE_ODKM:
atom = AP4_ContainerAtom::Create(type, size_64, true, force_64, stream, *this);
break;
case AP4_ATOM_TYPE_FREE:
case AP4_ATOM_TYPE_WIDE:
case AP4_ATOM_TYPE_MDAT:
// generic atoms
break;
default: {
// try all the external type handlers
AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
while (handler_item) {
TypeHandler* handler = handler_item->GetData();
if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
break;
}
handler_item = handler_item->GetNext();
}
break;
}
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomsFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
AP4_AtomParent& atoms)
{
AP4_LargeSize stream_size = 0;
AP4_Position stream_position = 0;
AP4_LargeSize bytes_available = (AP4_LargeSize)(-1);
if (AP4_SUCCEEDED(stream.GetSize(stream_size)) &&
stream_size != 0 &&
AP4_SUCCEEDED(stream.Tell(stream_position)) &&
stream_position <= stream_size) {
bytes_available = stream_size-stream_position;
}
return CreateAtomsFromStream(stream, bytes_available, atoms);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomsFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
AP4_LargeSize bytes_available,
AP4_AtomParent& atoms)
{
AP4_Result result;
do {
AP4_Atom* atom = NULL;
result = CreateAtomFromStream(stream, bytes_available, atom);
if (AP4_SUCCEEDED(result) && atom != NULL) {
atoms.AddChild(atom);
}
} while (AP4_SUCCEEDED(result));
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::PushContext
+---------------------------------------------------------------------*/
void
AP4_AtomFactory::PushContext(AP4_Atom::Type context)
{
m_ContextStack.Append(context);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::PopContext
+---------------------------------------------------------------------*/
void
AP4_AtomFactory::PopContext()
{
m_ContextStack.RemoveLast();
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::GetContext
+---------------------------------------------------------------------*/
AP4_Atom::Type
AP4_AtomFactory::GetContext(AP4_Ordinal depth)
{
AP4_Ordinal available = m_ContextStack.ItemCount();
if (depth >= available) return 0;
return m_ContextStack[available-depth-1];
}
/*----------------------------------------------------------------------
| AP4_DefaultAtomFactory::Instance
+---------------------------------------------------------------------*/
AP4_DefaultAtomFactory AP4_DefaultAtomFactory::Instance_;
/*----------------------------------------------------------------------
| AP4_DefaultAtomFactory::Instance
+---------------------------------------------------------------------*/
AP4_DefaultAtomFactory::AP4_DefaultAtomFactory()
{
Initialize();
}
/*----------------------------------------------------------------------
| AP4_DefaultAtomFactory::Initialize
+---------------------------------------------------------------------*/
AP4_Result
AP4_DefaultAtomFactory::Initialize()
{
// register built-in type handlers
AP4_Result result = AddTypeHandler(new AP4_MetaDataAtomTypeHandler(this));
if (AP4_SUCCEEDED(result)) m_Initialized = true;
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_2807_0 |
crossvul-cpp_data_bad_4037_1 | /*
* Copyright (C) 2004-2020 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gmock/gmock.h>
#include "znctest.h"
using testing::HasSubstr;
namespace znc_inttest {
namespace {
TEST(Config, AlreadyExists) {
QTemporaryDir dir;
WriteConfig(dir.path());
Process p(ZNC_BIN_DIR "/znc", QStringList() << "--debug"
<< "--datadir" << dir.path()
<< "--makeconf");
p.ReadUntil("already exists");
p.CanDie();
}
TEST_F(ZNCTest, Connect) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.ReadUntil("CAP LS");
auto client = ConnectClient();
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
client.ReadUntil("Welcome");
client.Close();
client = ConnectClient();
client.Write("PASS :user:hunter2");
client.Write("NICK nick");
client.Write("USER u x x x");
client.ReadUntil("Welcome");
client.Close();
client = ConnectClient();
client.Write("NICK nick");
client.Write("USER user x x x");
client.ReadUntil("Configure your client to send a server password");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("WHO");
}
TEST_F(ZNCTest, Channel) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.ReadUntil("Welcome");
client.Write("JOIN #znc");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc");
ircd.Write(":nick JOIN :#znc");
ircd.Write(":server 353 nick #znc :nick");
ircd.Write(":server 366 nick #znc :End of /NAMES list");
ircd.Write(":server PING :1");
ircd.ReadUntil("PONG 1");
client = LoginClient();
client.ReadUntil(":nick JOIN :#znc");
}
TEST_F(ZNCTest, HTTP) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto reply = HttpGet(QNetworkRequest(QUrl("http://127.0.0.1:12345/")));
EXPECT_THAT(reply->rawHeader("Server").toStdString(), HasSubstr("ZNC"));
}
TEST_F(ZNCTest, FixCVE20149403) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.Write(":server 005 nick CHANTYPES=# :supports");
ircd.Write(":server PING :1");
ircd.ReadUntil("PONG 1");
QNetworkRequest request;
request.setRawHeader("Authorization",
"Basic " + QByteArray("user:hunter2").toBase64());
request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
HttpPost(request, {
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "znc"},
{"enabled", "1"},
});
EXPECT_THAT(HttpPost(request,
{
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "znc"},
{"enabled", "1"},
})
->readAll()
.toStdString(),
HasSubstr("Channel [#znc] already exists"));
}
TEST_F(ZNCTest, FixFixOfCVE20149403) {
auto znc = Run();
auto ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.Write(":nick JOIN @#znc");
ircd.ReadUntil("MODE @#znc");
ircd.Write(":server 005 nick STATUSMSG=@ :supports");
ircd.Write(":server PING :12345");
ircd.ReadUntil("PONG 12345");
QNetworkRequest request;
request.setRawHeader("Authorization",
"Basic " + QByteArray("user:hunter2").toBase64());
request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
auto reply = HttpPost(request, {
{"user", "user"},
{"network", "test"},
{"submitted", "1"},
{"name", "@#znc"},
{"enabled", "1"},
});
EXPECT_THAT(reply->readAll().toStdString(),
HasSubstr("Could not add channel [@#znc]"));
}
TEST_F(ZNCTest, InvalidConfigInChan) {
QFile conf(m_dir.path() + "/configs/znc.conf");
ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
QTextStream out(&conf);
out << R"(
<User foo>
<Network bar>
<Chan #baz>
Invalid = Line
</Chan>
</Network>
</User>
)";
out.flush();
auto znc = Run();
znc->ShouldFinishItself(1);
}
TEST_F(ZNCTest, Encoding) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
ircd.Write(":server 001 nick :hello");
// legacy
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xE6world");
client.Write("PRIVMSG *controlpanel :SetNetwork Encoding $me $net UTF-8");
client.ReadUntil("Encoding = UTF-8");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xEF\xBF\xBDworld");
client.Write(
"PRIVMSG *controlpanel :SetNetwork Encoding $me $net ^CP-1251");
client.ReadUntil("Encoding = ^CP-1251");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
client.ReadUntil("Hello\xD0\xB6world");
ircd.Write(":n!u@h PRIVMSG nick :Hello\xD0\xB6world");
client.ReadUntil("Hello\xD0\xB6world");
}
TEST_F(ZNCTest, BuildMod) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
QTemporaryDir srcd;
QDir srcdir(srcd.path());
QFile file(srcdir.filePath("testmod.cpp"));
ASSERT_TRUE(file.open(QIODevice::WriteOnly | QIODevice::Text));
QTextStream out(&file);
out << R"(
#include <znc/Modules.h>
class TestModule : public CModule {
public:
MODCONSTRUCTOR(TestModule) {}
void OnModCommand(const CString& sLine) override {
PutModule("Lorem ipsum");
}
};
MODULEDEFS(TestModule, "Test")
)";
file.close();
QDir dir(m_dir.path());
EXPECT_TRUE(dir.mkdir("modules"));
EXPECT_TRUE(dir.cd("modules"));
{
Process p(ZNC_BIN_DIR "/znc-buildmod",
QStringList() << srcdir.filePath("file-not-found.cpp"),
[&](QProcess* proc) {
proc->setWorkingDirectory(dir.absolutePath());
proc->setProcessChannelMode(QProcess::ForwardedChannels);
});
p.ShouldFinishItself(1);
p.ShouldFinishInSec(300);
}
{
Process p(ZNC_BIN_DIR "/znc-buildmod",
QStringList() << srcdir.filePath("testmod.cpp"),
[&](QProcess* proc) {
proc->setWorkingDirectory(dir.absolutePath());
proc->setProcessChannelMode(QProcess::ForwardedChannels);
});
p.ShouldFinishItself();
p.ShouldFinishInSec(300);
}
client.Write("znc loadmod testmod");
client.Write("PRIVMSG *testmod :hi");
client.ReadUntil("Lorem ipsum");
}
TEST_F(ZNCTest, AwayNotify) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = ConnectClient();
client.Write("CAP LS");
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
QByteArray cap_ls;
client.ReadUntilAndGet(" LS :", cap_ls);
ASSERT_THAT(cap_ls.toStdString(),
AllOf(HasSubstr("cap-notify"), Not(HasSubstr("away-notify"))));
client.Write("CAP REQ :cap-notify");
client.ReadUntil("ACK :cap-notify");
client.Write("CAP END");
client.ReadUntil(" 001 ");
ircd.ReadUntil("USER");
ircd.Write("CAP user LS :away-notify");
ircd.ReadUntil("CAP REQ :away-notify");
ircd.Write("CAP user ACK :away-notify");
ircd.ReadUntil("CAP END");
ircd.Write(":server 001 user :welcome");
client.ReadUntil("CAP user NEW :away-notify");
client.Write("CAP REQ :away-notify");
client.ReadUntil("ACK :away-notify");
ircd.Write(":x!y@z AWAY :reason");
client.ReadUntil(":x!y@z AWAY :reason");
ircd.Close();
client.ReadUntil("DEL :away-notify");
// This test often fails on macos due to ZNC process not finishing.
// No idea why. Let's try to shutdown it more explicitly...
client.Write("znc shutdown");
}
TEST_F(ZNCTest, JoinKey) {
QFile conf(m_dir.path() + "/configs/znc.conf");
ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
QTextStream(&conf) << "ServerThrottle = 1\n";
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
ircd.Write(":server 001 nick :Hello");
client.Write("JOIN #znc secret");
ircd.ReadUntil("JOIN #znc secret");
ircd.Write(":nick JOIN :#znc");
client.ReadUntil("JOIN :#znc");
ircd.Close();
ircd = ConnectIRCd();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc secret");
}
TEST_F(ZNCTest, StatusEchoMessage) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("CAP REQ :echo-message");
client.Write("PRIVMSG *status :blah");
client.ReadUntil(":nick!user@irc.znc.in PRIVMSG *status :blah");
client.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command");
}
} // namespace
} // namespace znc_inttest
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_4037_1 |
crossvul-cpp_data_bad_656_1 | /* GRAPHITE2 LICENSING
Copyright 2012, SIL International
All rights reserved.
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 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
Lesser General Public License for more details.
You should also have received a copy of the GNU Lesser General Public
License along with this library in the file named "LICENSE".
If not, write to the Free Software Foundation, 51 Franklin Street,
Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
internet at http://www.fsf.org/licenses/lgpl.html.
Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or 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 "graphite2/Font.h"
#include "inc/Main.h"
#include "inc/Face.h" //for the tags
#include "inc/GlyphCache.h"
#include "inc/GlyphFace.h"
#include "inc/Endian.h"
#include "inc/bits.h"
using namespace graphite2;
namespace
{
// Iterator over version 1 or 2 glat entries which consist of a series of
// +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+
// v1 |k|n|v1 |v2 |...|vN | or v2 | k | n |v1 |v2 |...|vN |
// +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+
// variable length structures.
template<typename W>
class _glat_iterator : public std::iterator<std::input_iterator_tag, std::pair<sparse::key_type, sparse::mapped_type> >
{
unsigned short key() const { return be::peek<W>(_e) + _n; }
unsigned int run() const { return be::peek<W>(_e+sizeof(W)); }
void advance_entry() { _n = 0; _e = _v; be::skip<W>(_v,2); }
public:
_glat_iterator(const void * glat=0) : _e(reinterpret_cast<const byte *>(glat)), _v(_e+2*sizeof(W)), _n(0) {}
_glat_iterator<W> & operator ++ () {
++_n; be::skip<uint16>(_v);
if (_n == run()) advance_entry();
return *this;
}
_glat_iterator<W> operator ++ (int) { _glat_iterator<W> tmp(*this); operator++(); return tmp; }
// This is strictly a >= operator. A true == operator could be
// implemented that test for overlap but it would be more expensive a
// test.
bool operator == (const _glat_iterator<W> & rhs) { return _v >= rhs._e - 1; }
bool operator != (const _glat_iterator<W> & rhs) { return !operator==(rhs); }
value_type operator * () const {
return value_type(key(), be::peek<uint16>(_v));
}
protected:
const byte * _e, * _v;
size_t _n;
};
typedef _glat_iterator<uint8> glat_iterator;
typedef _glat_iterator<uint16> glat2_iterator;
}
const SlantBox SlantBox::empty = {0,0,0,0};
class GlyphCache::Loader
{
public:
Loader(const Face & face, const bool dumb_font); //return result indicates success. Do not use if failed.
operator bool () const throw();
unsigned short int units_per_em() const throw();
unsigned short int num_glyphs() const throw();
unsigned short int num_attrs() const throw();
bool has_boxes() const throw();
const GlyphFace * read_glyph(unsigned short gid, GlyphFace &, int *numsubs) const throw();
GlyphBox * read_box(uint16 gid, GlyphBox *curr, const GlyphFace & face) const throw();
CLASS_NEW_DELETE;
private:
Face::Table _head,
_hhea,
_hmtx,
_glyf,
_loca,
m_pGlat,
m_pGloc;
bool _long_fmt;
bool _has_boxes;
unsigned short _num_glyphs_graphics, //i.e. boundary box and advance
_num_glyphs_attributes,
_num_attrs; // number of glyph attributes per glyph
};
GlyphCache::GlyphCache(const Face & face, const uint32 face_options)
: _glyph_loader(new Loader(face, bool(face_options & gr_face_dumbRendering))),
_glyphs(_glyph_loader && *_glyph_loader && _glyph_loader->num_glyphs()
? grzeroalloc<const GlyphFace *>(_glyph_loader->num_glyphs()) : 0),
_boxes(_glyph_loader && _glyph_loader->has_boxes() && _glyph_loader->num_glyphs()
? grzeroalloc<GlyphBox *>(_glyph_loader->num_glyphs()) : 0),
_num_glyphs(_glyphs ? _glyph_loader->num_glyphs() : 0),
_num_attrs(_glyphs ? _glyph_loader->num_attrs() : 0),
_upem(_glyphs ? _glyph_loader->units_per_em() : 0)
{
if ((face_options & gr_face_preloadGlyphs) && _glyph_loader && _glyphs)
{
int numsubs = 0;
GlyphFace * const glyphs = new GlyphFace [_num_glyphs];
if (!glyphs)
return;
// The 0 glyph is definately required.
_glyphs[0] = _glyph_loader->read_glyph(0, glyphs[0], &numsubs);
// glyphs[0] has the same address as the glyphs array just allocated,
// thus assigning the &glyphs[0] to _glyphs[0] means _glyphs[0] points
// to the entire array.
const GlyphFace * loaded = _glyphs[0];
for (uint16 gid = 1; loaded && gid != _num_glyphs; ++gid)
_glyphs[gid] = loaded = _glyph_loader->read_glyph(gid, glyphs[gid], &numsubs);
if (!loaded)
{
_glyphs[0] = 0;
delete [] glyphs;
}
else if (numsubs > 0 && _boxes)
{
GlyphBox * boxes = (GlyphBox *)gralloc<char>(_num_glyphs * sizeof(GlyphBox) + numsubs * 8 * sizeof(float));
GlyphBox * currbox = boxes;
for (uint16 gid = 0; currbox && gid != _num_glyphs; ++gid)
{
_boxes[gid] = currbox;
currbox = _glyph_loader->read_box(gid, currbox, *_glyphs[gid]);
}
if (!currbox)
{
free(boxes);
_boxes[0] = 0;
}
}
delete _glyph_loader;
_glyph_loader = 0;
}
if (_glyphs && glyph(0) == 0)
{
free(_glyphs);
_glyphs = 0;
if (_boxes)
{
free(_boxes);
_boxes = 0;
}
_num_glyphs = _num_attrs = _upem = 0;
}
}
GlyphCache::~GlyphCache()
{
if (_glyphs)
{
if (_glyph_loader)
{
const GlyphFace * * g = _glyphs;
for(unsigned short n = _num_glyphs; n; --n, ++g)
delete *g;
}
else
delete [] _glyphs[0];
free(_glyphs);
}
if (_boxes)
{
if (_glyph_loader)
{
GlyphBox * * g = _boxes;
for (uint16 n = _num_glyphs; n; --n, ++g)
free(*g);
}
else
free(_boxes[0]);
free(_boxes);
}
delete _glyph_loader;
}
const GlyphFace *GlyphCache::glyph(unsigned short glyphid) const //result may be changed by subsequent call with a different glyphid
{
if (glyphid >= numGlyphs())
return _glyphs[0];
const GlyphFace * & p = _glyphs[glyphid];
if (p == 0 && _glyph_loader)
{
int numsubs = 0;
GlyphFace * g = new GlyphFace();
if (g) p = _glyph_loader->read_glyph(glyphid, *g, &numsubs);
if (!p)
{
delete g;
return *_glyphs;
}
if (_boxes)
{
_boxes[glyphid] = (GlyphBox *)gralloc<char>(sizeof(GlyphBox) + 8 * numsubs * sizeof(float));
if (!_glyph_loader->read_box(glyphid, _boxes[glyphid], *_glyphs[glyphid]))
{
free(_boxes[glyphid]);
_boxes[glyphid] = 0;
}
}
}
return p;
}
GlyphCache::Loader::Loader(const Face & face, const bool dumb_font)
: _head(face, Tag::head),
_hhea(face, Tag::hhea),
_hmtx(face, Tag::hmtx),
_glyf(face, Tag::glyf),
_loca(face, Tag::loca),
_long_fmt(false),
_has_boxes(false),
_num_glyphs_graphics(0),
_num_glyphs_attributes(0),
_num_attrs(0)
{
if (!operator bool())
return;
const Face::Table maxp = Face::Table(face, Tag::maxp);
if (!maxp) { _head = Face::Table(); return; }
_num_glyphs_graphics = TtfUtil::GlyphCount(maxp);
// This will fail if the number of glyphs is wildly out of range.
if (_glyf && TtfUtil::LocaLookup(_num_glyphs_graphics-1, _loca, _loca.size(), _head) == size_t(-2))
{
_head = Face::Table();
return;
}
if (!dumb_font)
{
if ((m_pGlat = Face::Table(face, Tag::Glat, 0x00030000)) == NULL
|| (m_pGloc = Face::Table(face, Tag::Gloc)) == NULL
|| m_pGloc.size() < 8)
{
_head = Face::Table();
return;
}
const byte * p = m_pGloc;
int version = be::read<uint32>(p);
const uint16 flags = be::read<uint16>(p);
_num_attrs = be::read<uint16>(p);
// We can accurately calculate the number of attributed glyphs by
// subtracting the length of the attribids array (numAttribs long if present)
// and dividing by either 2 or 4 depending on shor or lonf format
_long_fmt = flags & 1;
int tmpnumgattrs = (m_pGloc.size()
- (p - m_pGloc)
- sizeof(uint16)*(flags & 0x2 ? _num_attrs : 0))
/ (_long_fmt ? sizeof(uint32) : sizeof(uint16)) - 1;
if (version >= 0x00020000 || tmpnumgattrs < 0 || tmpnumgattrs > 65535
|| _num_attrs == 0 || _num_attrs > 0x3000 // is this hard limit appropriate?
|| _num_glyphs_graphics > tmpnumgattrs
|| m_pGlat.size() < 4)
{
_head = Face::Table();
return;
}
_num_glyphs_attributes = static_cast<unsigned short>(tmpnumgattrs);
p = m_pGlat;
version = be::read<uint32>(p);
if (version >= 0x00040000 || (version >= 0x00030000 && m_pGlat.size() < 8)) // reject Glat tables that are too new
{
_head = Face::Table();
return;
}
else if (version >= 0x00030000)
{
unsigned int glatflags = be::read<uint32>(p);
_has_boxes = glatflags & 1;
// delete this once the compiler is fixed
_has_boxes = true;
}
}
}
inline
GlyphCache::Loader::operator bool () const throw()
{
return _head && _hhea && _hmtx && !(bool(_glyf) != bool(_loca));
}
inline
unsigned short int GlyphCache::Loader::units_per_em() const throw()
{
return _head ? TtfUtil::DesignUnits(_head) : 0;
}
inline
unsigned short int GlyphCache::Loader::num_glyphs() const throw()
{
return max(_num_glyphs_graphics, _num_glyphs_attributes);
}
inline
unsigned short int GlyphCache::Loader::num_attrs() const throw()
{
return _num_attrs;
}
inline
bool GlyphCache::Loader::has_boxes () const throw()
{
return _has_boxes;
}
const GlyphFace * GlyphCache::Loader::read_glyph(unsigned short glyphid, GlyphFace & glyph, int *numsubs) const throw()
{
Rect bbox;
Position advance;
if (glyphid < _num_glyphs_graphics)
{
int nLsb;
unsigned int nAdvWid;
if (_glyf)
{
int xMin, yMin, xMax, yMax;
size_t locidx = TtfUtil::LocaLookup(glyphid, _loca, _loca.size(), _head);
void *pGlyph = TtfUtil::GlyfLookup(_glyf, locidx, _glyf.size());
if (pGlyph && TtfUtil::GlyfBox(pGlyph, xMin, yMin, xMax, yMax))
{
if ((xMin > xMax) || (yMin > yMax))
return 0;
bbox = Rect(Position(static_cast<float>(xMin), static_cast<float>(yMin)),
Position(static_cast<float>(xMax), static_cast<float>(yMax)));
}
}
if (TtfUtil::HorMetrics(glyphid, _hmtx, _hmtx.size(), _hhea, nLsb, nAdvWid))
advance = Position(static_cast<float>(nAdvWid), 0);
}
if (glyphid < _num_glyphs_attributes)
{
const byte * gloc = m_pGloc;
size_t glocs = 0, gloce = 0;
be::skip<uint32>(gloc);
be::skip<uint16>(gloc,2);
if (_long_fmt)
{
if (8 + glyphid * sizeof(uint32) > m_pGloc.size())
return 0;
be::skip<uint32>(gloc, glyphid);
glocs = be::read<uint32>(gloc);
gloce = be::peek<uint32>(gloc);
}
else
{
if (8 + glyphid * sizeof(uint16) > m_pGloc.size())
return 0;
be::skip<uint16>(gloc, glyphid);
glocs = be::read<uint16>(gloc);
gloce = be::peek<uint16>(gloc);
}
if (glocs >= m_pGlat.size() - 1 || gloce > m_pGlat.size())
return 0;
const uint32 glat_version = be::peek<uint32>(m_pGlat);
if (glat_version >= 0x00030000)
{
if (glocs >= gloce)
return 0;
const byte * p = m_pGlat + glocs;
uint16 bmap = be::read<uint16>(p);
int num = bit_set_count((uint32)bmap);
if (numsubs) *numsubs += num;
glocs += 6 + 8 * num;
if (glocs > gloce)
return 0;
}
if (glat_version < 0x00020000)
{
if (gloce - glocs < 2*sizeof(byte)+sizeof(uint16)
|| gloce - glocs > _num_attrs*(2*sizeof(byte)+sizeof(uint16)))
return 0;
new (&glyph) GlyphFace(bbox, advance, glat_iterator(m_pGlat + glocs), glat_iterator(m_pGlat + gloce));
}
else
{
if (gloce - glocs < 3*sizeof(uint16) // can a glyph have no attributes? why not?
|| gloce - glocs > _num_attrs*3*sizeof(uint16)
|| glocs > m_pGlat.size() - 2*sizeof(uint16))
return 0;
new (&glyph) GlyphFace(bbox, advance, glat2_iterator(m_pGlat + glocs), glat2_iterator(m_pGlat + gloce));
}
if (!glyph.attrs() || glyph.attrs().capacity() > _num_attrs)
return 0;
}
return &glyph;
}
inline float scale_to(uint8 t, float zmin, float zmax)
{
return (zmin + t * (zmax - zmin) / 255);
}
Rect readbox(Rect &b, uint8 zxmin, uint8 zymin, uint8 zxmax, uint8 zymax)
{
return Rect(Position(scale_to(zxmin, b.bl.x, b.tr.x), scale_to(zymin, b.bl.y, b.tr.y)),
Position(scale_to(zxmax, b.bl.x, b.tr.x), scale_to(zymax, b.bl.y, b.tr.y)));
}
GlyphBox * GlyphCache::Loader::read_box(uint16 gid, GlyphBox *curr, const GlyphFace & glyph) const throw()
{
if (gid >= _num_glyphs_attributes) return 0;
const byte * gloc = m_pGloc;
size_t glocs = 0, gloce = 0;
be::skip<uint32>(gloc);
be::skip<uint16>(gloc,2);
if (_long_fmt)
{
be::skip<uint32>(gloc, gid);
glocs = be::read<uint32>(gloc);
gloce = be::peek<uint32>(gloc);
}
else
{
be::skip<uint16>(gloc, gid);
glocs = be::read<uint16>(gloc);
gloce = be::peek<uint16>(gloc);
}
if (gloce > m_pGlat.size() || glocs + 6 >= gloce)
return 0;
const byte * p = m_pGlat + glocs;
uint16 bmap = be::read<uint16>(p);
int num = bit_set_count((uint32)bmap);
Rect bbox = glyph.theBBox();
Rect diamax(Position(bbox.bl.x + bbox.bl.y, bbox.bl.x - bbox.tr.y),
Position(bbox.tr.x + bbox.tr.y, bbox.tr.x - bbox.bl.y));
Rect diabound = readbox(diamax, p[0], p[2], p[1], p[3]);
::new (curr) GlyphBox(num, bmap, &diabound);
be::skip<uint8>(p, 4);
if (glocs + 6 + num * 8 >= gloce)
return 0;
for (int i = 0; i < num * 2; ++i)
{
Rect box = readbox((i & 1) ? diamax : bbox, p[0], p[2], p[1], p[3]);
curr->addSubBox(i >> 1, i & 1, &box);
be::skip<uint8>(p, 4);
}
return (GlyphBox *)((char *)(curr) + sizeof(GlyphBox) + 2 * num * sizeof(Rect));
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_656_1 |
crossvul-cpp_data_bad_2810_0 | /*****************************************************************
|
| AP4 - MetaData
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4File.h"
#include "Ap4Movie.h"
#include "Ap4MetaData.h"
#include "Ap4ContainerAtom.h"
#include "Ap4MoovAtom.h"
#include "Ap4HdlrAtom.h"
#include "Ap4DataBuffer.h"
#include "Ap4Utils.h"
#include "Ap4String.h"
/*----------------------------------------------------------------------
| dynamic cast support
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_3GppLocalizedStringAtom)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_DcfdAtom)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_DcfStringAtom)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_DataAtom)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_MetaDataStringAtom)
/*----------------------------------------------------------------------
| metadata keys
+---------------------------------------------------------------------*/
static const AP4_MetaData::KeyInfo AP4_MetaData_KeyInfos [] = {
{"Name", "Name", AP4_ATOM_TYPE_cNAM, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Artist", "Artist", AP4_ATOM_TYPE_cART, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"AlbumArtist", "Album Artist", AP4_ATOM_TYPE_aART, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Composer", "Composer", AP4_ATOM_TYPE_cCOM, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Writer", "Writer", AP4_ATOM_TYPE_cWRT, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Album", "Album", AP4_ATOM_TYPE_cALB, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"GenreCode", "Genre", AP4_ATOM_TYPE_GNRE, AP4_MetaData::Value::TYPE_BINARY},
{"GenreName", "Genre", AP4_ATOM_TYPE_cGEN, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Grouping", "Grouping", AP4_ATOM_TYPE_cGRP, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Date", "Date", AP4_ATOM_TYPE_cDAY, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Tool", "Encoding Tool", AP4_ATOM_TYPE_cTOO, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Comment", "Comment", AP4_ATOM_TYPE_cCMT, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Lyrics", "Lyrics", AP4_ATOM_TYPE_cLYR, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Copyright", "Copyright", AP4_ATOM_TYPE_CPRT, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Track", "Track Number", AP4_ATOM_TYPE_TRKN, AP4_MetaData::Value::TYPE_BINARY},
{"Disc", "Disc Number", AP4_ATOM_TYPE_DISK, AP4_MetaData::Value::TYPE_BINARY},
{"Cover", "Cover Art", AP4_ATOM_TYPE_COVR, AP4_MetaData::Value::TYPE_BINARY},
{"Description", "Description", AP4_ATOM_TYPE_DESC, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Rating", "Rating", AP4_ATOM_TYPE_RTNG, AP4_MetaData::Value::TYPE_INT_08_BE},
{"Tempo", "Tempo", AP4_ATOM_TYPE_TMPO, AP4_MetaData::Value::TYPE_INT_16_BE},
{"Compilation", "Compilation", AP4_ATOM_TYPE_CPIL, AP4_MetaData::Value::TYPE_INT_08_BE},
{"IsGapless", "Is Gapless", AP4_ATOM_TYPE_PGAP, AP4_MetaData::Value::TYPE_INT_08_BE},
{"Title", "Title", AP4_ATOM_TYPE_TITL, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Description", "Description", AP4_ATOM_TYPE_DSCP, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"StoreFrontID", "Store Front ID", AP4_ATOM_TYPE_sfID, AP4_MetaData::Value::TYPE_INT_32_BE},
{"FileKind", "File Kind", AP4_ATOM_TYPE_STIK, AP4_MetaData::Value::TYPE_INT_08_BE},
{"ShowName", "Show Name", AP4_ATOM_TYPE_TVSH, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"ShowSeason", "Show Season Number", AP4_ATOM_TYPE_TVSN, AP4_MetaData::Value::TYPE_INT_32_BE},
{"ShowEpisodeNumber", "Show Episode Number", AP4_ATOM_TYPE_TVES, AP4_MetaData::Value::TYPE_INT_32_BE},
{"ShowEpisodeName", "Show Episode Name", AP4_ATOM_TYPE_TVEN, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"TVNetworkName", "TV Network Name", AP4_ATOM_TYPE_TVNN, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"IsPodcast", "Is a Podcast", AP4_ATOM_TYPE_PCST, AP4_MetaData::Value::TYPE_INT_08_BE},
{"PodcastUrl", "Podcast URL", AP4_ATOM_TYPE_PURL, AP4_MetaData::Value::TYPE_BINARY},
{"PodcastGuid", "Podcast GUID", AP4_ATOM_TYPE_EGID, AP4_MetaData::Value::TYPE_BINARY},
{"PodcastCategory", "Podcast Category", AP4_ATOM_TYPE_CATG, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Keywords", "Keywords", AP4_ATOM_TYPE_KEYW, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"PurchaseDate", "Purchase Date", AP4_ATOM_TYPE_PURD, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"IconUri", "Icon URI", AP4_ATOM_TYPE_ICNU, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"InfoUrl", "Info URL", AP4_ATOM_TYPE_INFU, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"CoverUri", "Cover Art URI", AP4_ATOM_TYPE_CVRU, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"LyricsUri", "Lyrics URI", AP4_ATOM_TYPE_LRCU, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Duration", "Duration", AP4_ATOM_TYPE_DCFD, AP4_MetaData::Value::TYPE_INT_32_BE},
{"Performer", "Performer", AP4_ATOM_TYPE_PERF, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Author", "Author", AP4_ATOM_TYPE_AUTH, AP4_MetaData::Value::TYPE_STRING_UTF_8},
};
AP4_Array<AP4_MetaData::KeyInfo> AP4_MetaData::KeyInfos(
AP4_MetaData_KeyInfos,
sizeof(AP4_MetaData_KeyInfos)/sizeof(KeyInfo));
AP4_Result
AP4_MetaData::Initialized() { return AP4_MetaData::KeyInfos.ItemCount() != 0; }
AP4_Result
AP4_MetaData::Initialize() {
unsigned int item_count = sizeof(AP4_MetaData_KeyInfos)/sizeof(KeyInfo);
KeyInfos.SetItemCount(item_count);
for (unsigned int i=0; i<item_count; i++) {
KeyInfos[i] = AP4_MetaData_KeyInfos[i];
}
return AP4_SUCCESS;
}
AP4_Result
AP4_MetaData::UnInitialize() {
return AP4_MetaData::KeyInfos.Clear();
}
/*----------------------------------------------------------------------
| genre IDs
+---------------------------------------------------------------------*/
static const char* const Ap4Id3Genres[] =
{
"Blues",
"Classic Rock",
"Country",
"Dance",
"Disco",
"Funk",
"Grunge",
"Hip-Hop",
"Jazz",
"Metal",
"New Age",
"Oldies",
"Other",
"Pop",
"R&B",
"Rap",
"Reggae",
"Rock",
"Techno",
"Industrial",
"Alternative",
"Ska",
"Death Metal",
"Pranks",
"Soundtrack",
"Euro-Techno",
"Ambient",
"Trip-Hop",
"Vocal",
"Jazz+Funk",
"Fusion",
"Trance",
"Classical",
"Instrumental",
"Acid",
"House",
"Game",
"Sound Clip",
"Gospel",
"Noise",
"AlternRock",
"Bass",
"Soul",
"Punk",
"Space",
"Meditative",
"Instrumental Pop",
"Instrumental Rock",
"Ethnic",
"Gothic",
"Darkwave",
"Techno-Industrial",
"Electronic",
"Pop-Folk",
"Eurodance",
"Dream",
"Southern Rock",
"Comedy",
"Cult",
"Gangsta",
"Top 40",
"Christian Rap",
"Pop/Funk",
"Jungle",
"Native American",
"Cabaret",
"New Wave",
"Psychadelic",
"Rave",
"Showtunes",
"Trailer",
"Lo-Fi",
"Tribal",
"Acid Punk",
"Acid Jazz",
"Polka",
"Retro",
"Musical",
"Rock & Roll",
"Hard Rock",
"Folk",
"Folk-Rock",
"National Folk",
"Swing",
"Fast Fusion",
"Bebob",
"Latin",
"Revival",
"Celtic",
"Bluegrass",
"Avantgarde",
"Gothic Rock",
"Progressive Rock",
"Psychedelic Rock",
"Symphonic Rock",
"Slow Rock",
"Big Band",
"Chorus",
"Easy Listening",
"Acoustic",
"Humour",
"Speech",
"Chanson",
"Opera",
"Chamber Music",
"Sonata",
"Symphony",
"Booty Bass",
"Primus",
"Porn Groove",
"Satire",
"Slow Jam",
"Club",
"Tango",
"Samba",
"Folklore",
"Ballad",
"Power Ballad",
"Rhythmic Soul",
"Freestyle",
"Duet",
"Punk Rock",
"Drum Solo",
"Acapella",
"Euro-House",
"Dance Hall"
};
static const char*
Ap4StikNames[] = {
"Movie", // 0
"Normal", // 1
"Audiobook", // 2
"?", // 3
"?", // 4
"Whacked Bookmark", // 5
"Music Video", // 6
"?", // 7
"?", // 8
"Short Film", // 9
"TV Show", // 10
"Booklet", // 11
"?", // 12
"?", // 13
"Ring Tone" // 14
};
/* sfID Store Front country
Australia => 143460,
Austria => 143445,
Belgium => 143446,
Canada => 143455,
Denmark => 143458,
Finland => 143447,
France => 143442,
Germany => 143443,
Greece => 143448,
Ireland => 143449,
Italy => 143450,
Japan => 143462,
Luxembourg => 143451,
Netherlands => 143452,
Norway => 143457,
Portugal => 143453,
Spain => 143454,
Sweden => 143456,
Switzerland => 143459,
UK => 143444,
USA => 143441,
*/
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
const AP4_Size AP4_DATA_ATOM_MAX_SIZE = 0x40000000;
/*----------------------------------------------------------------------
| 3GPP localized string atoms
+---------------------------------------------------------------------*/
const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypes[] = {
AP4_ATOM_TYPE_TITL,
AP4_ATOM_TYPE_DSCP,
AP4_ATOM_TYPE_CPRT,
AP4_ATOM_TYPE_PERF,
AP4_ATOM_TYPE_AUTH,
AP4_ATOM_TYPE_GNRE
};
const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypeList = {
_3gppLocalizedStringTypes,
sizeof(_3gppLocalizedStringTypes)/sizeof(_3gppLocalizedStringTypes[0])
};
/*----------------------------------------------------------------------
| other 3GPP atoms
+---------------------------------------------------------------------*/
const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppOtherTypes[] = {
AP4_ATOM_TYPE_RTNG,
AP4_ATOM_TYPE_CLSF,
AP4_ATOM_TYPE_KYWD,
AP4_ATOM_TYPE_LOCI,
AP4_ATOM_TYPE_ALBM,
AP4_ATOM_TYPE_YRRC,
};
const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::_3gppOtherTypeList = {
_3gppOtherTypes,
sizeof(_3gppOtherTypes)/sizeof(_3gppOtherTypes[0])
};
/*----------------------------------------------------------------------
| DCF string atoms
+---------------------------------------------------------------------*/
const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::DcfStringTypes[] = {
AP4_ATOM_TYPE_ICNU,
AP4_ATOM_TYPE_INFU,
AP4_ATOM_TYPE_CVRU,
AP4_ATOM_TYPE_LRCU
};
const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::DcfStringTypeList = {
DcfStringTypes,
sizeof(DcfStringTypes)/sizeof(DcfStringTypes[0])
};
/*----------------------------------------------------------------------
| atom type lists
+---------------------------------------------------------------------*/
const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::IlstTypes[] =
{
AP4_ATOM_TYPE_dddd,
AP4_ATOM_TYPE_cNAM,
AP4_ATOM_TYPE_cART,
AP4_ATOM_TYPE_cCOM,
AP4_ATOM_TYPE_cWRT,
AP4_ATOM_TYPE_cALB,
AP4_ATOM_TYPE_cGEN,
AP4_ATOM_TYPE_cGRP,
AP4_ATOM_TYPE_cDAY,
AP4_ATOM_TYPE_cTOO,
AP4_ATOM_TYPE_cCMT,
AP4_ATOM_TYPE_CPRT,
AP4_ATOM_TYPE_TRKN,
AP4_ATOM_TYPE_DISK,
AP4_ATOM_TYPE_COVR,
AP4_ATOM_TYPE_DESC,
AP4_ATOM_TYPE_GNRE,
AP4_ATOM_TYPE_CPIL,
AP4_ATOM_TYPE_TMPO,
AP4_ATOM_TYPE_RTNG,
AP4_ATOM_TYPE_apID,
AP4_ATOM_TYPE_cnID,
AP4_ATOM_TYPE_cmID,
AP4_ATOM_TYPE_atID,
AP4_ATOM_TYPE_plID,
AP4_ATOM_TYPE_geID,
AP4_ATOM_TYPE_sfID,
AP4_ATOM_TYPE_akID,
AP4_ATOM_TYPE_aART,
AP4_ATOM_TYPE_TVNN,
AP4_ATOM_TYPE_TVSH,
AP4_ATOM_TYPE_TVEN,
AP4_ATOM_TYPE_TVSN,
AP4_ATOM_TYPE_TVES,
AP4_ATOM_TYPE_STIK,
AP4_ATOM_TYPE_PGAP,
AP4_ATOM_TYPE_PCST,
AP4_ATOM_TYPE_PURD,
AP4_ATOM_TYPE_PURL,
AP4_ATOM_TYPE_EGID,
AP4_ATOM_TYPE_SONM,
AP4_ATOM_TYPE_SOAL,
AP4_ATOM_TYPE_SOAR,
AP4_ATOM_TYPE_SOAA,
AP4_ATOM_TYPE_SOCO,
AP4_ATOM_TYPE_SOSN
};
const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::IlstTypeList = {
IlstTypes,
sizeof(IlstTypes)/sizeof(IlstTypes[0])
};
/*----------------------------------------------------------------------
| AP4_MetaDataAtomTypeHandler::CreateAtom
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaDataAtomTypeHandler::CreateAtom(AP4_Atom::Type type,
AP4_UI32 size,
AP4_ByteStream& stream,
AP4_Atom::Type context,
AP4_Atom*& atom)
{
atom = NULL;
if (context == AP4_ATOM_TYPE_ILST) {
if (IsTypeInList(type, IlstTypeList)) {
m_AtomFactory->PushContext(type);
atom = AP4_ContainerAtom::Create(type, size, false, false, stream, *m_AtomFactory);
m_AtomFactory->PopContext();
}
} else if (type == AP4_ATOM_TYPE_DATA) {
if (IsTypeInList(context, IlstTypeList)) {
atom = new AP4_DataAtom(size, stream);
}
} else if (context == AP4_ATOM_TYPE_dddd) {
if (type == AP4_ATOM_TYPE_MEAN || type == AP4_ATOM_TYPE_NAME) {
atom = new AP4_MetaDataStringAtom(type, size, stream);
}
} else if (context == AP4_ATOM_TYPE_UDTA) {
if (IsTypeInList(type, _3gppLocalizedStringTypeList)) {
atom = AP4_3GppLocalizedStringAtom::Create(type, size, stream);
} else if (IsTypeInList(type, DcfStringTypeList)) {
atom = AP4_DcfStringAtom::Create(type, size, stream);
} else if (type == AP4_ATOM_TYPE_DCFD) {
atom = AP4_DcfdAtom::Create(size, stream);
}
}
return atom?AP4_SUCCESS:AP4_FAILURE;
}
/*----------------------------------------------------------------------
| AP4_MetaDataAtomTypeHandler::IsTypeInList
+---------------------------------------------------------------------*/
bool
AP4_MetaDataAtomTypeHandler::IsTypeInList(AP4_Atom::Type type, const AP4_MetaDataAtomTypeHandler::TypeList& list)
{
for (unsigned int i=0; i<list.m_Size; i++) {
if (type == list.m_Types[i]) return true;
}
return false;
}
/*----------------------------------------------------------------------
| AP4_MetaData::AP4_MetaData
+---------------------------------------------------------------------*/
AP4_MetaData::AP4_MetaData(AP4_File* file)
{
// get the file's movie
AP4_Movie* movie = file->GetMovie();
// handle the movie's metadata if there is a movie in the file
if (movie) {
AP4_MoovAtom* moov = movie->GetMoovAtom();
if (moov == NULL) return;
ParseMoov(moov);
AP4_Atom* udta = moov->GetChild(AP4_ATOM_TYPE_UDTA);
if (udta) {
AP4_ContainerAtom* udta_container = AP4_DYNAMIC_CAST(AP4_ContainerAtom, udta);
if (udta_container) {
ParseUdta(udta_container, "3gpp");
}
}
} else {
// if we don't have a movie, try to show metadata from a udta atom
AP4_List<AP4_Atom>& top_level_atoms = file->GetTopLevelAtoms();
AP4_List<AP4_Atom>::Item* atom_item = top_level_atoms.FirstItem();
while (atom_item) {
AP4_ContainerAtom* container = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom_item->GetData());
if (container) {
// look for a udta in a DCF layout
AP4_Atom* udta = container->FindChild("odhe/udta");
if (udta) {
AP4_ContainerAtom* udta_container = AP4_DYNAMIC_CAST(AP4_ContainerAtom, udta);
if (udta_container) {
ParseUdta(udta_container, "dcf");
}
}
}
atom_item = atom_item->GetNext();
}
}
}
/*----------------------------------------------------------------------
| AP4_MetaData::ParseMoov
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::ParseMoov(AP4_MoovAtom* moov)
{
// look for a 'meta' atom with 'hdlr' type 'mdir'
AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, moov->FindChild("udta/meta/hdlr"));
if (hdlr == NULL || hdlr->GetHandlerType() != AP4_HANDLER_TYPE_MDIR) return AP4_ERROR_NO_SUCH_ITEM;
// get the list of entries
AP4_ContainerAtom* ilst = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->FindChild("udta/meta/ilst"));
if (ilst == NULL) return AP4_ERROR_NO_SUCH_ITEM;
AP4_List<AP4_Atom>::Item* ilst_item = ilst->GetChildren().FirstItem();
while (ilst_item) {
AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst_item->GetData());
if (entry_atom) {
AddIlstEntries(entry_atom, "meta");
}
ilst_item = ilst_item->GetNext();
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::ParseUdta
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::ParseUdta(AP4_ContainerAtom* udta, const char* namespc)
{
// check that the atom is indeed a 'udta' atom
if (udta->GetType() != AP4_ATOM_TYPE_UDTA) {
return AP4_ERROR_INVALID_PARAMETERS;
}
AP4_List<AP4_Atom>::Item* udta_item = udta->GetChildren().FirstItem();
for (; udta_item; udta_item = udta_item->GetNext()) {
AP4_3GppLocalizedStringAtom* _3gpp_atom = AP4_DYNAMIC_CAST(AP4_3GppLocalizedStringAtom, udta_item->GetData());
if (_3gpp_atom) {
Add3GppEntry(_3gpp_atom, namespc);
continue;
}
AP4_DcfStringAtom* dcfs_atom = AP4_DYNAMIC_CAST(AP4_DcfStringAtom, udta_item->GetData());
if (dcfs_atom) {
AddDcfStringEntry(dcfs_atom, namespc);
continue;
}
AP4_DcfdAtom* dcfd_atom = AP4_DYNAMIC_CAST(AP4_DcfdAtom, udta_item->GetData());
if (dcfd_atom) {
AddDcfdEntry(dcfd_atom, namespc);
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::~AP4_MetaData
+---------------------------------------------------------------------*/
AP4_MetaData::~AP4_MetaData()
{
m_Entries.DeleteReferences();
}
/*----------------------------------------------------------------------
| AP4_MetaData::ResolveKeyName
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::ResolveKeyName(AP4_Atom::Type atom_type, AP4_String& value)
{
const char* key_name = NULL;
char four_cc[5];
// look for a match in the key infos
for (unsigned int i=0;
i<sizeof(AP4_MetaData_KeyInfos)/sizeof(AP4_MetaData_KeyInfos[0]);
i++) {
if (AP4_MetaData_KeyInfos[i].four_cc == atom_type) {
key_name = AP4_MetaData_KeyInfos[i].name;
break;
}
}
if (key_name == NULL) {
// this key was not found in the key infos, create a name for it
AP4_FormatFourChars(four_cc, (AP4_UI32)atom_type);
key_name = four_cc;
}
value = key_name;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::AddIlstEntries
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::AddIlstEntries(AP4_ContainerAtom* atom, const char* namespc)
{
AP4_MetaData::Value* value = NULL;
if (atom->GetType() == AP4_ATOM_TYPE_dddd) {
// look for the namespace
AP4_MetaDataStringAtom* mean = static_cast<AP4_MetaDataStringAtom*>(atom->GetChild(AP4_ATOM_TYPE_MEAN));
if (mean == NULL) return AP4_ERROR_INVALID_FORMAT;
// look for the name
AP4_MetaDataStringAtom* name = static_cast<AP4_MetaDataStringAtom*>(atom->GetChild(AP4_ATOM_TYPE_NAME));
if (name == NULL) return AP4_ERROR_INVALID_FORMAT;
// get the value
AP4_DataAtom* data_atom = static_cast<AP4_DataAtom*>(atom->GetChild(AP4_ATOM_TYPE_DATA));
if (data_atom == NULL) return AP4_ERROR_INVALID_FORMAT;
value = new AP4_AtomMetaDataValue(data_atom, atom->GetType());
return m_Entries.Add(new Entry(name->GetValue().GetChars(),
mean->GetValue().GetChars(),
value));
} else {
const char* key_name = NULL;
char four_cc[5];
// convert the atom type to a name
AP4_FormatFourChars(four_cc, (AP4_UI32)atom->GetType());
key_name = four_cc;
// add one entry for each data atom
AP4_List<AP4_Atom>::Item* data_item = atom->GetChildren().FirstItem();
while (data_item) {
AP4_Atom* item_atom = data_item->GetData();
if (item_atom->GetType() == AP4_ATOM_TYPE_DATA) {
AP4_DataAtom* data_atom = static_cast<AP4_DataAtom*>(item_atom);
value = new AP4_AtomMetaDataValue(data_atom, atom->GetType());
m_Entries.Add(new Entry(key_name, namespc, value));
}
data_item = data_item->GetNext();
}
return AP4_SUCCESS;
}
}
/*----------------------------------------------------------------------
| AP4_MetaData::Add3GppEntry
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Add3GppEntry(AP4_3GppLocalizedStringAtom* atom, const char* namespc)
{
AP4_String key_name;
ResolveKeyName(atom->GetType(), key_name);
const char* language = NULL;
if (atom->GetLanguage()[0]) {
language = atom->GetLanguage();
}
AP4_MetaData::Value* value = new AP4_StringMetaDataValue(atom->GetValue().GetChars(),
language);
m_Entries.Add(new Entry(key_name.GetChars(), namespc, value));
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::AddDcfStringEntry
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::AddDcfStringEntry(AP4_DcfStringAtom* atom, const char* namespc)
{
AP4_String key_name;
ResolveKeyName(atom->GetType(), key_name);
AP4_MetaData::Value* value = new AP4_StringMetaDataValue(atom->GetValue().GetChars());
m_Entries.Add(new Entry(key_name.GetChars(), namespc, value));
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::AddDcfdEntry
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::AddDcfdEntry(AP4_DcfdAtom* atom, const char* namespc)
{
AP4_String key_name;
ResolveKeyName(atom->GetType(), key_name);
AP4_MetaData::Value* value = new AP4_IntegerMetaDataValue(AP4_MetaData::Value::TYPE_INT_32_BE,
atom->GetDuration());
m_Entries.Add(new Entry(key_name.GetChars(), namespc, value));
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Value::MapDataTypeToCategory
+---------------------------------------------------------------------*/
AP4_MetaData::Value::TypeCategory
AP4_MetaData::Value::MapTypeToCategory(Type type)
{
switch (type) {
case AP4_MetaData::Value::TYPE_INT_08_BE:
case AP4_MetaData::Value::TYPE_INT_16_BE:
case AP4_MetaData::Value::TYPE_INT_32_BE:
return AP4_MetaData::Value::TYPE_CATEGORY_INTEGER;
case AP4_MetaData::Value::TYPE_STRING_UTF_8:
case AP4_MetaData::Value::TYPE_STRING_UTF_16:
case AP4_MetaData::Value::TYPE_STRING_PASCAL:
return AP4_MetaData::Value::TYPE_CATEGORY_STRING;
case AP4_MetaData::Value::TYPE_FLOAT_32_BE:
case AP4_MetaData::Value::TYPE_FLOAT_64_BE:
return AP4_MetaData::Value::TYPE_CATEGORY_FLOAT;
default:
return AP4_MetaData::Value::TYPE_CATEGORY_BINARY;
}
}
/*----------------------------------------------------------------------
| AP4_MetaData::Value::GetTypeCategory
+---------------------------------------------------------------------*/
AP4_MetaData::Value::TypeCategory
AP4_MetaData::Value::GetTypeCategory() const
{
return MapTypeToCategory(m_Type);
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::ToAtom
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::ToAtom(AP4_Atom*& atom) const
{
atom = NULL;
if (m_Value == NULL) {
return AP4_ERROR_INVALID_PARAMETERS;
}
if (m_Key.GetNamespace() == "meta") {
// convert the name into an atom type
if (m_Key.GetName().GetLength() != 4) {
// the name is not in the right format
return AP4_ERROR_INVALID_PARAMETERS;
}
AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
// create a container atom for the data
AP4_ContainerAtom* container = new AP4_ContainerAtom(atom_type);
// add the data atom
AP4_DataAtom* data = new AP4_DataAtom(*m_Value);
container->AddChild(data);
atom = container;
return AP4_SUCCESS;
} else if (m_Key.GetNamespace() == "dcf") {
// convert the name into an atom type
if (m_Key.GetName().GetLength() != 4) {
// the name is not in the right format
return AP4_ERROR_INVALID_PARAMETERS;
}
AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
if (AP4_MetaDataAtomTypeHandler::IsTypeInList(atom_type,
AP4_MetaDataAtomTypeHandler::DcfStringTypeList)) {
AP4_String atom_value = m_Value->ToString();
atom = new AP4_DcfStringAtom(atom_type, atom_value.GetChars());
return AP4_SUCCESS;
} else if (AP4_MetaDataAtomTypeHandler::IsTypeInList(atom_type,
AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypeList)) {
AP4_String atom_value = m_Value->ToString();
const char* language = "eng"; // default
if (m_Value->GetLanguage().GetLength() != 0) {
language = m_Value->GetLanguage().GetChars();
}
atom = new AP4_3GppLocalizedStringAtom(atom_type, language, atom_value.GetChars());
return AP4_SUCCESS;
} else if (atom_type == AP4_ATOM_TYPE_DCFD) {
atom = new AP4_DcfdAtom((AP4_UI32)m_Value->ToInteger());
return AP4_SUCCESS;
}
// not supported
return AP4_ERROR_NOT_SUPPORTED;
} else {
// create a '----' atom
AP4_ContainerAtom* container = new AP4_ContainerAtom(AP4_ATOM_TYPE_dddd);
// add a 'mean' string
container->AddChild(new AP4_MetaDataStringAtom(AP4_ATOM_TYPE_MEAN, m_Key.GetNamespace().GetChars()));
// add a 'name' string
container->AddChild(new AP4_MetaDataStringAtom(AP4_ATOM_TYPE_NAME, m_Key.GetName().GetChars()));
// add the data atom
AP4_DataAtom* data = new AP4_DataAtom(*m_Value);
container->AddChild(data);
atom = container;
return AP4_SUCCESS;
}
// unreachable - return AP4_ERROR_NOT_SUPPORTED;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::FindInIlst
+---------------------------------------------------------------------*/
AP4_ContainerAtom*
AP4_MetaData::Entry::FindInIlst(AP4_ContainerAtom* ilst) const
{
if (m_Key.GetNamespace() == "meta") {
AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
return AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst->GetChild(atom_type));
} else {
AP4_List<AP4_Atom>::Item* ilst_item = ilst->GetChildren().FirstItem();
while (ilst_item) {
AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst_item->GetData());
if (entry_atom) {
AP4_MetaDataStringAtom* mean = static_cast<AP4_MetaDataStringAtom*>(entry_atom->GetChild(AP4_ATOM_TYPE_MEAN));
AP4_MetaDataStringAtom* name = static_cast<AP4_MetaDataStringAtom*>(entry_atom->GetChild(AP4_ATOM_TYPE_NAME));
if (mean && name &&
mean->GetValue() == m_Key.GetNamespace() &&
name->GetValue() == m_Key.GetName()) {
return entry_atom;
}
}
ilst_item = ilst_item->GetNext();
}
}
// not found
return NULL;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::AddToFileIlst
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::AddToFileIlst(AP4_File& file, AP4_Ordinal index)
{
// check that we have a correct entry
if (m_Value == NULL) return AP4_ERROR_INVALID_STATE;
// convert the entry into an atom
AP4_Atom* atom;
AP4_Result result = ToAtom(atom);
if (AP4_FAILED(result)) return result;
AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
if (entry_atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// look for the 'moov'
AP4_Movie* movie = file.GetMovie();
if (movie == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_MoovAtom* moov = movie->GetMoovAtom();
if (moov == NULL) return AP4_ERROR_INVALID_FORMAT;
// look for 'udta', and create if it does not exist
AP4_ContainerAtom* udta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->FindChild("udta", true));
if (udta == NULL) return AP4_ERROR_INTERNAL;
// look for 'meta', and create if it does not exist ('meta' is a FULL atom)
AP4_ContainerAtom* meta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, udta->FindChild("meta", true, true));
if (meta == NULL) return AP4_ERROR_INTERNAL;
// look for a 'hdlr' atom type 'mdir'
AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, meta->FindChild("hdlr"));
if (hdlr == NULL) {
hdlr = new AP4_HdlrAtom(AP4_HANDLER_TYPE_MDIR, "");
meta->AddChild(hdlr);
} else {
if (hdlr->GetHandlerType() != AP4_HANDLER_TYPE_MDIR) {
return AP4_ERROR_INVALID_FORMAT;
}
}
// get/create the list of entries
AP4_ContainerAtom* ilst = AP4_DYNAMIC_CAST(AP4_ContainerAtom, meta->FindChild("ilst", true));
if (ilst == NULL) return AP4_ERROR_INTERNAL;
// look if there is already a container for this entry
AP4_ContainerAtom* existing = FindInIlst(ilst);
if (existing == NULL) {
// just add the one we have
ilst->AddChild(entry_atom);
} else {
// add the entry's data to the existing entry
AP4_DataAtom* data_atom = AP4_DYNAMIC_CAST(AP4_DataAtom, entry_atom->GetChild(AP4_ATOM_TYPE_DATA));
if (data_atom == NULL) return AP4_ERROR_INTERNAL;
entry_atom->RemoveChild(data_atom);
existing->AddChild(data_atom, index);
delete entry_atom;
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::AddToFileDcf
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::AddToFileDcf(AP4_File& file, AP4_Ordinal index)
{
// check that we have a correct entry
if (m_Value == NULL) return AP4_ERROR_INVALID_STATE;
// look for 'odrm/odhe'
AP4_ContainerAtom* odhe = AP4_DYNAMIC_CAST(AP4_ContainerAtom, file.FindChild("odrm/odhe"));
if (odhe == NULL) return AP4_ERROR_NO_SUCH_ITEM;
// get/create the list of entries
AP4_ContainerAtom* udta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, odhe->FindChild("udta", true));
if (udta == NULL) return AP4_ERROR_INTERNAL;
// convert the entry into an atom
AP4_Atom* data_atom;
AP4_Result result = ToAtom(data_atom);
if (AP4_FAILED(result)) return result;
// add the entry's data to the container
return udta->AddChild(data_atom, index);
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::AddToFile
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::AddToFile(AP4_File& file, AP4_Ordinal index)
{
// check that we have a correct entry
if (m_Value == NULL) return AP4_ERROR_INVALID_STATE;
// check the namespace of the key to know where to add the atom
if (m_Key.GetNamespace() == "meta") {
return AddToFileIlst(file, index);
} else if (m_Key.GetNamespace() == "dcf") {
return AddToFileDcf(file, index);
} else {
// custom namespace
return AddToFileIlst(file, index);
}
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::RemoveFromFileIlst
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::RemoveFromFileIlst(AP4_File& file, AP4_Ordinal index)
{
// look for the 'moov'
AP4_Movie* movie = file.GetMovie();
if (movie == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_MoovAtom* moov = movie->GetMoovAtom();
if (moov == NULL) return AP4_ERROR_INVALID_FORMAT;
// look for 'udta/meta/ilst'
AP4_ContainerAtom* ilst = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->FindChild("udta/meta/ilst"));
if (ilst == NULL) return AP4_ERROR_NO_SUCH_ITEM;
// look if there is already a container for this entry
AP4_ContainerAtom* existing = FindInIlst(ilst);
if (existing == NULL) return AP4_ERROR_NO_SUCH_ITEM;
// remove the data atom in the entry
AP4_Result result = existing->DeleteChild(AP4_ATOM_TYPE_DATA, index);
if (AP4_FAILED(result)) return result;
// cleanup
if (existing->GetType() == AP4_ATOM_TYPE_dddd) {
// custom entry: if there are no more 'data' children, remove the entry
if (existing->GetChild(AP4_ATOM_TYPE_DATA) == NULL) {
ilst->RemoveChild(existing);
delete existing;
}
} else {
// normal entry: if the entry is empty, remove it
if (existing->GetChildren().ItemCount() == 0) {
ilst->RemoveChild(existing);
delete existing;
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::RemoveFromFileDcf
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::RemoveFromFileDcf(AP4_File& file, AP4_Ordinal index)
{
// look for 'odrm/odhe/udta'
AP4_ContainerAtom* udta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, file.FindChild("odrm/odhe/udta"));
if (udta == NULL) return AP4_ERROR_NO_SUCH_ITEM;
// remove the data atom in the entry
AP4_UI32 type = AP4_BytesToUInt32BE((const unsigned char*)m_Key.GetName().GetChars());
AP4_Result result = udta->DeleteChild(type, index);
if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::RemoveFromFile
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaData::Entry::RemoveFromFile(AP4_File& file, AP4_Ordinal index)
{
// check the namespace of the key to know where to add the atom
if (m_Key.GetNamespace() == "meta") {
return RemoveFromFileIlst(file, index);
} else if (m_Key.GetNamespace() == "dcf") {
return RemoveFromFileDcf(file, index);
} else {
// custom namespace
return RemoveFromFileIlst(file, index);
}
}
/*----------------------------------------------------------------------
| AP4_StringMetaDataValue::ToString
+---------------------------------------------------------------------*/
AP4_String
AP4_StringMetaDataValue::ToString() const
{
return m_Value;
}
/*----------------------------------------------------------------------
| AP4_StringMetaDataValue::ToBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_StringMetaDataValue::ToBytes(AP4_DataBuffer& /* bytes */) const
{
return AP4_ERROR_NOT_SUPPORTED;
}
/*----------------------------------------------------------------------
| AP4_StringMetaDataValue::ToInteger
+---------------------------------------------------------------------*/
long
AP4_StringMetaDataValue::ToInteger() const
{
return 0;
}
/*----------------------------------------------------------------------
| AP4_IntegerMetaDataValue::ToString
+---------------------------------------------------------------------*/
AP4_String
AP4_IntegerMetaDataValue::ToString() const
{
char value[16];
AP4_FormatString(value, sizeof(value), "%ld", m_Value);
return AP4_String(value);
}
/*----------------------------------------------------------------------
| AP4_IntegerMetaDataValue::ToBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_IntegerMetaDataValue::ToBytes(AP4_DataBuffer& /* bytes */) const
{
return AP4_ERROR_NOT_SUPPORTED;
}
/*----------------------------------------------------------------------
| AP4_IntegerMetaDataValue::ToInteger
+---------------------------------------------------------------------*/
long
AP4_IntegerMetaDataValue::ToInteger() const
{
return m_Value;
}
/*----------------------------------------------------------------------
| AP4_BinaryMetaDataValue::ToString
+---------------------------------------------------------------------*/
AP4_String
AP4_BinaryMetaDataValue::ToString() const
{
return AP4_String(); // not supported
}
/*----------------------------------------------------------------------
| AP4_BinaryMetaDataValue::ToBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_BinaryMetaDataValue::ToBytes(AP4_DataBuffer& bytes) const
{
bytes.SetDataSize(m_Value.GetDataSize());
AP4_CopyMemory(bytes.UseData(), m_Value.GetData(), m_Value.GetDataSize());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_BinaryMetaDataValue::ToInteger
+---------------------------------------------------------------------*/
long
AP4_BinaryMetaDataValue::ToInteger() const
{
return 0; // NOT SUPPORTED
}
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::AP4_AtomMetaDataValue
+---------------------------------------------------------------------*/
AP4_AtomMetaDataValue::AP4_AtomMetaDataValue(AP4_DataAtom* atom,
AP4_UI32 parent_type) :
Value(atom->GetValueType()),
m_DataAtom(atom)
{
switch (parent_type) {
case AP4_ATOM_TYPE_GNRE:
m_Meaning = MEANING_ID3_GENRE;
break;
case AP4_ATOM_TYPE_CPIL:
m_Meaning = MEANING_BOOLEAN;
break;
case AP4_ATOM_TYPE_PGAP:
case AP4_ATOM_TYPE_PCST:
m_Meaning = MEANING_BOOLEAN;
break;
case AP4_ATOM_TYPE_STIK:
m_Meaning = MEANING_FILE_KIND;
break;
case AP4_ATOM_TYPE_PURL:
case AP4_ATOM_TYPE_EGID:
m_Meaning = MEANING_BINARY_ENCODED_CHARS;
break;
default:
break;
}
}
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::ToString
+---------------------------------------------------------------------*/
AP4_String
AP4_AtomMetaDataValue::ToString() const
{
char string[256] = "";
AP4_MetaData::Value::Type value_type = m_DataAtom->GetValueType();
switch (AP4_MetaData::Value::MapTypeToCategory(value_type)) {
case AP4_MetaData::Value::TYPE_CATEGORY_INTEGER:
{
long value;
if (AP4_SUCCEEDED(m_DataAtom->LoadInteger(value))) {
if (m_Meaning == MEANING_BOOLEAN) {
if (value) {
return "True";
} else {
return "False";
}
} else if (m_Meaning == MEANING_FILE_KIND) {
if (value >= 0 && ((unsigned int)value) <= sizeof(Ap4StikNames)/sizeof(Ap4StikNames[0])) {
AP4_FormatString(string, sizeof(string), "(%ld) %s", value, Ap4StikNames[value]);
} else {
return "Unknown";
}
} else {
AP4_FormatString(string, sizeof(string), "%ld", value);
}
}
return AP4_String((const char*)string);
break;
}
case AP4_MetaData::Value::TYPE_CATEGORY_STRING:
{
AP4_String* category_string;
if (AP4_SUCCEEDED(m_DataAtom->LoadString(category_string))) {
AP4_String result(*category_string);
delete category_string;
return result;
}
break;
}
case AP4_MetaData::Value::TYPE_CATEGORY_BINARY:
{
AP4_DataBuffer data;
if (AP4_SUCCEEDED(m_DataAtom->LoadBytes(data))) {
if (m_Meaning == MEANING_ID3_GENRE && data.GetDataSize() == 2) {
unsigned int genre = (data.GetData()[0])*256+data.GetData()[1];
if (genre >= 1 && genre <= sizeof(Ap4Id3Genres)/sizeof(Ap4Id3Genres[0])) {
AP4_FormatString(string, sizeof(string), "(%d) %s", genre, Ap4Id3Genres[genre-1]);
return AP4_String((const char*)string);
} else {
return "Unknown";
}
} else if (m_Meaning == MEANING_BINARY_ENCODED_CHARS) {
AP4_String result;
result.Assign((const char*)data.GetData(), data.GetDataSize());
return result;
} else {
unsigned int dump_length = data.GetDataSize();
bool truncate = false;
if (dump_length > 16) {
dump_length = 16;
truncate = true;
}
char* out = string;
for (unsigned int i=0; i<dump_length; i++) {
AP4_FormatString(out, sizeof(string)-(out-string), "%02x ", data.GetData()[i]);
out += 3;
}
if (truncate) {
*out++='.'; *out++='.'; *out++='.'; *out++=' ';
}
AP4_FormatString(out, sizeof(string)-(out-string), "[%d bytes]", (int)data.GetDataSize());
}
}
return AP4_String(string);
}
default:
return AP4_String();
}
return AP4_String();
}
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::ToBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomMetaDataValue::ToBytes(AP4_DataBuffer& bytes) const
{
return m_DataAtom->LoadBytes(bytes);
}
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::ToInteger
+---------------------------------------------------------------------*/
long
AP4_AtomMetaDataValue::ToInteger() const
{
long value;
if (AP4_SUCCEEDED(m_DataAtom->LoadInteger(value))) {
return value;
} else {
return 0;
}
}
/*----------------------------------------------------------------------
| AP4_DataAtom::AP4_DataAtom
+---------------------------------------------------------------------*/
AP4_DataAtom::AP4_DataAtom(const AP4_MetaData::Value& value) :
AP4_Atom(AP4_ATOM_TYPE_DATA, AP4_ATOM_HEADER_SIZE),
m_DataType(DATA_TYPE_BINARY)
{
AP4_MemoryByteStream* memory = new AP4_MemoryByteStream();
AP4_Size payload_size = 8;
m_Source = memory;
switch (value.GetType()) {
case AP4_MetaData::Value::TYPE_STRING_UTF_8: {
m_DataType = DATA_TYPE_STRING_UTF_8;
AP4_String string_value = value.ToString();
if (string_value.GetLength()) {
memory->Write(string_value.GetChars(), string_value.GetLength());
}
payload_size += string_value.GetLength();
break;
}
case AP4_MetaData::Value::TYPE_INT_08_BE: {
m_DataType = DATA_TYPE_SIGNED_INT_BE;
AP4_UI08 int_value = (AP4_UI08)value.ToInteger();
memory->Write(&int_value, 1);
payload_size += 1;
break;
}
case AP4_MetaData::Value::TYPE_INT_16_BE: {
m_DataType = DATA_TYPE_SIGNED_INT_BE;
AP4_UI16 int_value = (AP4_UI16)value.ToInteger();
memory->Write(&int_value, 2);
payload_size += 2;
break;
}
case AP4_MetaData::Value::TYPE_INT_32_BE: {
m_DataType = DATA_TYPE_SIGNED_INT_BE;
AP4_UI32 int_value = (AP4_UI32)value.ToInteger();
memory->Write(&int_value, 4);
payload_size += 4;
break;
}
case AP4_MetaData::Value::TYPE_JPEG:
m_DataType = DATA_TYPE_JPEG;
// FALLTHROUGH
case AP4_MetaData::Value::TYPE_GIF:
if (m_DataType == DATA_TYPE_BINARY) m_DataType = DATA_TYPE_GIF;
// FALLTHROUGH
case AP4_MetaData::Value::TYPE_BINARY: {
AP4_DataBuffer buffer;
value.ToBytes(buffer);
if (buffer.GetDataSize()) {
memory->Write(buffer.GetData(), buffer.GetDataSize());
}
payload_size += buffer.GetDataSize();
break;
}
default:
break;
}
const AP4_String& language = value.GetLanguage();
if (language == "en") {
m_DataLang = LANGUAGE_ENGLISH;
} else {
// default
m_DataLang = LANGUAGE_ENGLISH;
}
m_Size32 += payload_size;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::AP4_DataAtom
+---------------------------------------------------------------------*/
AP4_DataAtom::AP4_DataAtom(AP4_UI32 size, AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_DATA, size)
{
if (size < AP4_ATOM_HEADER_SIZE+8) return;
AP4_UI32 i;
stream.ReadUI32(i); m_DataType = (DataType)i;
stream.ReadUI32(i); m_DataLang = (DataLang)i;
// the stream for the data is a substream of this source
AP4_Position data_offset;
stream.Tell(data_offset);
AP4_Size data_size = size-AP4_ATOM_HEADER_SIZE-8;
m_Source = new AP4_SubStream(stream, data_offset, data_size);
}
/*----------------------------------------------------------------------
| AP4_DataAtom::~AP4_DataAtom
+---------------------------------------------------------------------*/
AP4_DataAtom::~AP4_DataAtom()
{
delete(m_Source);
}
/*----------------------------------------------------------------------
| AP4_DataAtom::GetValueType
+---------------------------------------------------------------------*/
AP4_MetaData::Value::Type
AP4_DataAtom::GetValueType()
{
switch (m_DataType) {
case DATA_TYPE_BINARY:
return AP4_MetaData::Value::TYPE_BINARY;
case DATA_TYPE_SIGNED_INT_BE:
switch (m_Size32-16) {
case 1: return AP4_MetaData::Value::TYPE_INT_08_BE;
case 2: return AP4_MetaData::Value::TYPE_INT_16_BE;
case 4: return AP4_MetaData::Value::TYPE_INT_32_BE;
default: return AP4_MetaData::Value::TYPE_BINARY;
}
break;
case DATA_TYPE_STRING_UTF_8:
return AP4_MetaData::Value::TYPE_STRING_UTF_8;
case DATA_TYPE_STRING_UTF_16:
return AP4_MetaData::Value::TYPE_STRING_UTF_16;
case DATA_TYPE_STRING_PASCAL:
return AP4_MetaData::Value::TYPE_STRING_PASCAL;
case DATA_TYPE_GIF:
return AP4_MetaData::Value::TYPE_GIF;
case DATA_TYPE_JPEG:
return AP4_MetaData::Value::TYPE_JPEG;
default:
return AP4_MetaData::Value::TYPE_BINARY;
}
// unreachable - return AP4_MetaData::Value::TYPE_BINARY;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI32(m_DataType);
stream.WriteUI32(m_DataLang);
if (m_Source) {
AP4_LargeSize size = 0;
m_Source->GetSize(size);
m_Source->Seek(0);
m_Source->CopyTo(stream, size);
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("type", m_DataType);
inspector.AddField("lang", m_DataLang);
if (m_DataType == DATA_TYPE_STRING_UTF_8) {
AP4_String* str;
if (AP4_SUCCEEDED(LoadString(str))) {
inspector.AddField("value", str->GetChars());
delete str;
}
} else if (m_DataType == DATA_TYPE_SIGNED_INT_BE) {
long value;
if (AP4_SUCCEEDED(LoadInteger(value))) {
inspector.AddField("value", value);
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::LoadString
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::LoadString(AP4_String*& string)
{
if (m_Source == NULL) {
string = new AP4_String();
return AP4_SUCCESS;
} else {
// create a string with enough capactiy for the data
AP4_LargeSize size = 0;
m_Source->GetSize(size);
if (size > AP4_DATA_ATOM_MAX_SIZE) return AP4_ERROR_OUT_OF_RANGE;
string = new AP4_String((AP4_Size)size);
// read from the start of the stream
m_Source->Seek(0);
AP4_Result result = m_Source->Read(string->UseChars(), (AP4_Size)size);
if (AP4_FAILED(result)) {
delete string;
string = NULL;
}
return result;
}
}
/*----------------------------------------------------------------------
| AP4_DataAtom::LoadBytes
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::LoadBytes(AP4_DataBuffer& bytes)
{
if (m_Source == NULL) {
bytes.SetDataSize(0);
return AP4_SUCCESS;
}
AP4_LargeSize size = 0;
m_Source->GetSize(size);
if (size > AP4_DATA_ATOM_MAX_SIZE) return AP4_ERROR_OUT_OF_RANGE;
bytes.SetDataSize((AP4_Size)size);
m_Source->Seek(0);
AP4_Result result = m_Source->Read(bytes.UseData(), (AP4_Size)size);
if (AP4_FAILED(result)) {
bytes.SetDataSize(0);
}
return result;
}
/*----------------------------------------------------------------------
| AP4_DataAtom::LoadInteger
+---------------------------------------------------------------------*/
AP4_Result
AP4_DataAtom::LoadInteger(long& value)
{
AP4_Result result = AP4_FAILURE;
value = 0;
if (m_Source == NULL) return AP4_SUCCESS;
AP4_LargeSize size = 0;
m_Source->GetSize(size);
if (size > 4) {
return AP4_ERROR_OUT_OF_RANGE;
}
unsigned char bytes[4];
m_Source->Seek(0);
m_Source->Read(bytes, (AP4_Size)size);
result = AP4_SUCCESS;
switch (size) {
case 1: value = bytes[0]; break;
case 2: value = AP4_BytesToInt16BE(bytes); break;
case 4: value = AP4_BytesToInt32BE(bytes); break;
default: value = 0; result = AP4_ERROR_INVALID_FORMAT; break;
}
return result;
}
/*----------------------------------------------------------------------
| AP4_MetaDataStringAtom::AP4_MetaDataStringAtom
+---------------------------------------------------------------------*/
AP4_MetaDataStringAtom::AP4_MetaDataStringAtom(Type type, const char* value) :
AP4_Atom(type, AP4_ATOM_HEADER_SIZE),
m_Reserved(0),
m_Value(value)
{
m_Size32 += 4+m_Value.GetLength();
}
/*----------------------------------------------------------------------
| AP4_MetaDataStringAtom::AP4_MetaDataStringAtom
+---------------------------------------------------------------------*/
AP4_MetaDataStringAtom::AP4_MetaDataStringAtom(Type type, AP4_UI32 size, AP4_ByteStream& stream) :
AP4_Atom(type, size),
m_Reserved(0),
m_Value((AP4_Size)(size-AP4_ATOM_HEADER_SIZE-4))
{
stream.ReadUI32(m_Reserved);
stream.Read(m_Value.UseChars(), m_Value.GetLength());
}
/*----------------------------------------------------------------------
| AP4_MetaDataStringAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaDataStringAtom::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI32(m_Reserved);
return stream.Write(m_Value.GetChars(), m_Value.GetLength());
}
/*----------------------------------------------------------------------
| AP4_MetaDataStringAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_MetaDataStringAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("value", m_Value.GetChars());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::Create
+---------------------------------------------------------------------*/
AP4_3GppLocalizedStringAtom*
AP4_3GppLocalizedStringAtom::Create(Type type, AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI08 version;
AP4_UI32 flags;
if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
if (version != 0) return NULL;
return new AP4_3GppLocalizedStringAtom(type, size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom
+---------------------------------------------------------------------*/
AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom(Type type,
const char* language,
const char* value) :
AP4_Atom(type, AP4_FULL_ATOM_HEADER_SIZE+2, 0, 0),
m_Value(value)
{
m_Language[0] = language[0];
m_Language[1] = language[1];
m_Language[2] = language[2];
m_Language[3] = language[3];
m_Size32 += m_Value.GetLength()+1;
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom
+---------------------------------------------------------------------*/
AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom(Type type,
AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(type, size, version, flags)
{
// read the language code
AP4_UI16 packed_language;
stream.ReadUI16(packed_language);
m_Language[0] = 0x60+((packed_language>>10)&0x1F);
m_Language[1] = 0x60+((packed_language>> 5)&0x1F);
m_Language[2] = 0x60+((packed_language )&0x1F);
m_Language[3] = '\0';
// read the value (should be a NULL-terminated string, but we'll
// allow for strings that are not terminated)
if (size > AP4_FULL_ATOM_HEADER_SIZE+2) {
AP4_UI32 value_size = size-(AP4_FULL_ATOM_HEADER_SIZE+2);
char* value = new char[value_size];
stream.Read(value, value_size);
m_Value.Assign(value, value_size);
delete[] value;
}
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_3GppLocalizedStringAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_UI16 packed_language = ((m_Language[0]-0x60)<<10) |
((m_Language[1]-0x60)<< 5) |
((m_Language[2]-0x60));
stream.WriteUI16(packed_language);
AP4_Size payload_size = (AP4_UI32)GetSize()-GetHeaderSize();
if (payload_size < 2) return AP4_ERROR_INVALID_FORMAT;
AP4_Size value_size = m_Value.GetLength()+1;
if (value_size > payload_size-2) {
value_size = payload_size-2;
}
stream.Write(m_Value.GetChars(), value_size);
for (unsigned int i=value_size; i<payload_size-2; i++) {
stream.WriteUI08(0);
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_3GppLocalizedStringAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("language", GetLanguage());
inspector.AddField("value", m_Value.GetChars());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::Create
+---------------------------------------------------------------------*/
AP4_DcfStringAtom*
AP4_DcfStringAtom::Create(Type type, AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI08 version;
AP4_UI32 flags;
if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
if (version != 0) return NULL;
return new AP4_DcfStringAtom(type, size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::AP4_DcfStringAtom
+---------------------------------------------------------------------*/
AP4_DcfStringAtom::AP4_DcfStringAtom(Type type, const char* value) :
AP4_Atom(type, AP4_FULL_ATOM_HEADER_SIZE, 0, 0),
m_Value(value)
{
m_Size32 += m_Value.GetLength();
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::AP4_DcfStringAtom
+---------------------------------------------------------------------*/
AP4_DcfStringAtom::AP4_DcfStringAtom(Type type,
AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(type, size, version, flags)
{
if (size > AP4_FULL_ATOM_HEADER_SIZE) {
AP4_UI32 value_size = size-(AP4_FULL_ATOM_HEADER_SIZE);
char* value = new char[value_size];
stream.Read(value, value_size);
m_Value.Assign(value, value_size);
delete[] value;
}
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DcfStringAtom::WriteFields(AP4_ByteStream& stream)
{
if (m_Value.GetLength()) stream.Write(m_Value.GetChars(), m_Value.GetLength());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DcfStringAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("value", m_Value.GetChars());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::Create
+---------------------------------------------------------------------*/
AP4_DcfdAtom*
AP4_DcfdAtom::Create(AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI08 version;
AP4_UI32 flags;
if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
if (version != 0) return NULL;
if (size != AP4_FULL_ATOM_HEADER_SIZE+4) return NULL;
return new AP4_DcfdAtom(version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::AP4_DcfdAtom
+---------------------------------------------------------------------*/
AP4_DcfdAtom::AP4_DcfdAtom(AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_DCFD, AP4_FULL_ATOM_HEADER_SIZE+4, version, flags),
m_Duration(0)
{
stream.ReadUI32(m_Duration);
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::AP4_DcfdAtom
+---------------------------------------------------------------------*/
AP4_DcfdAtom::AP4_DcfdAtom(AP4_UI32 duration) :
AP4_Atom(AP4_ATOM_TYPE_DCFD, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0),
m_Duration(duration)
{
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DcfdAtom::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI32(m_Duration);
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DcfdAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_DcfdAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("duration", m_Duration);
return AP4_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_2810_0 |
crossvul-cpp_data_good_2609_1 | /*****************************************************************
|
| AP4 - avcC Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4AvccAtom.h"
#include "Ap4AtomFactory.h"
#include "Ap4Utils.h"
#include "Ap4Types.h"
/*----------------------------------------------------------------------
| dynamic cast support
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AvccAtom)
/*----------------------------------------------------------------------
| AP4_AvccAtom::GetProfileName
+---------------------------------------------------------------------*/
const char*
AP4_AvccAtom::GetProfileName(AP4_UI08 profile)
{
switch (profile) {
case AP4_AVC_PROFILE_BASELINE: return "Baseline";
case AP4_AVC_PROFILE_MAIN: return "Main";
case AP4_AVC_PROFILE_EXTENDED: return "Extended";
case AP4_AVC_PROFILE_HIGH: return "High";
case AP4_AVC_PROFILE_HIGH_10: return "High 10";
case AP4_AVC_PROFILE_HIGH_422: return "High 4:2:2";
case AP4_AVC_PROFILE_HIGH_444: return "High 4:4:4";
}
return NULL;
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::Create
+---------------------------------------------------------------------*/
AP4_AvccAtom*
AP4_AvccAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
// read the raw bytes in a buffer
unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
AP4_DataBuffer payload_data(payload_size);
AP4_Result result = stream.Read(payload_data.UseData(), payload_size);
if (AP4_FAILED(result)) return NULL;
// check the version
const AP4_UI08* payload = payload_data.GetData();
if (payload[0] != 1) {
return NULL;
}
// check the size
if (payload_size < 6) return NULL;
unsigned int num_seq_params = payload[5]&31;
unsigned int cursor = 6;
for (unsigned int i=0; i<num_seq_params; i++) {
if (cursor+2 > payload_size) return NULL;
cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);
if (cursor > payload_size) return NULL;
}
unsigned int num_pic_params = payload[cursor++];
if (cursor > payload_size) return NULL;
for (unsigned int i=0; i<num_pic_params; i++) {
if (cursor+2 > payload_size) return NULL;
cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);
if (cursor > payload_size) return NULL;
}
return new AP4_AvccAtom(size, payload);
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::AP4_AvccAtom
+---------------------------------------------------------------------*/
AP4_AvccAtom::AP4_AvccAtom() :
AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE),
m_ConfigurationVersion(1),
m_Profile(0),
m_Level(0),
m_ProfileCompatibility(0),
m_NaluLengthSize(0)
{
UpdateRawBytes();
m_Size32 += m_RawBytes.GetDataSize();
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::AP4_AvccAtom
+---------------------------------------------------------------------*/
AP4_AvccAtom::AP4_AvccAtom(const AP4_AvccAtom& other) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, other.m_Size32),
m_ConfigurationVersion(other.m_ConfigurationVersion),
m_Profile(other.m_Profile),
m_Level(other.m_Level),
m_ProfileCompatibility(other.m_ProfileCompatibility),
m_NaluLengthSize(other.m_NaluLengthSize),
m_RawBytes(other.m_RawBytes)
{
// deep copy of the parameters
unsigned int i = 0;
for (i=0; i<other.m_SequenceParameters.ItemCount(); i++) {
m_SequenceParameters.Append(other.m_SequenceParameters[i]);
}
for (i=0; i<other.m_PictureParameters.ItemCount(); i++) {
m_PictureParameters.Append(other.m_PictureParameters[i]);
}
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::AP4_AvccAtom
+---------------------------------------------------------------------*/
AP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, size)
{
// make a copy of our configuration bytes
unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
m_RawBytes.SetData(payload, payload_size);
// parse the payload
m_ConfigurationVersion = payload[0];
m_Profile = payload[1];
m_ProfileCompatibility = payload[2];
m_Level = payload[3];
m_NaluLengthSize = 1+(payload[4]&3);
AP4_UI08 num_seq_params = payload[5]&31;
m_SequenceParameters.EnsureCapacity(num_seq_params);
unsigned int cursor = 6;
for (unsigned int i=0; i<num_seq_params; i++) {
m_SequenceParameters.Append(AP4_DataBuffer());
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
m_SequenceParameters[i].SetData(&payload[cursor]+2, param_length);
cursor += 2+param_length;
}
AP4_UI08 num_pic_params = payload[cursor++];
m_PictureParameters.EnsureCapacity(num_pic_params);
for (unsigned int i=0; i<num_pic_params; i++) {
m_PictureParameters.Append(AP4_DataBuffer());
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
m_PictureParameters[i].SetData(&payload[cursor]+2, param_length);
cursor += 2+param_length;
}
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::AP4_AvccAtom
+---------------------------------------------------------------------*/
AP4_AvccAtom::AP4_AvccAtom(AP4_UI08 profile,
AP4_UI08 level,
AP4_UI08 profile_compatibility,
AP4_UI08 length_size,
const AP4_Array<AP4_DataBuffer>& sequence_parameters,
const AP4_Array<AP4_DataBuffer>& picture_parameters) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE),
m_ConfigurationVersion(1),
m_Profile(profile),
m_Level(level),
m_ProfileCompatibility(profile_compatibility),
m_NaluLengthSize(length_size)
{
// deep copy of the parameters
unsigned int i = 0;
for (i=0; i<sequence_parameters.ItemCount(); i++) {
m_SequenceParameters.Append(sequence_parameters[i]);
}
for (i=0; i<picture_parameters.ItemCount(); i++) {
m_PictureParameters.Append(picture_parameters[i]);
}
// compute the raw bytes
UpdateRawBytes();
// update the size
m_Size32 += m_RawBytes.GetDataSize();
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::UpdateRawBytes
+---------------------------------------------------------------------*/
void
AP4_AvccAtom::UpdateRawBytes()
{
// compute the payload size
unsigned int payload_size = 6;
for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
payload_size += 2+m_SequenceParameters[i].GetDataSize();
}
++payload_size;
for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {
payload_size += 2+m_PictureParameters[i].GetDataSize();
}
m_RawBytes.SetDataSize(payload_size);
AP4_UI08* payload = m_RawBytes.UseData();
payload[0] = m_ConfigurationVersion;
payload[1] = m_Profile;
payload[2] = m_ProfileCompatibility;
payload[3] = m_Level;
payload[4] = 0xFC | (m_NaluLengthSize-1);
payload[5] = 0xE0 | (AP4_UI08)m_SequenceParameters.ItemCount();
unsigned int cursor = 6;
for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
AP4_UI16 param_length = (AP4_UI16)m_SequenceParameters[i].GetDataSize();
AP4_BytesFromUInt16BE(&payload[cursor], param_length);
cursor += 2;
AP4_CopyMemory(&payload[cursor], m_SequenceParameters[i].GetData(), param_length);
cursor += param_length;
}
payload[cursor++] = (AP4_UI08)m_PictureParameters.ItemCount();
for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {
AP4_UI16 param_length = (AP4_UI16)m_PictureParameters[i].GetDataSize();
AP4_BytesFromUInt16BE(&payload[cursor], param_length);
cursor += 2;
AP4_CopyMemory(&payload[cursor], m_PictureParameters[i].GetData(), param_length);
cursor += param_length;
}
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_AvccAtom::WriteFields(AP4_ByteStream& stream)
{
return stream.Write(m_RawBytes.GetData(), m_RawBytes.GetDataSize());
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("Configuration Version", m_ConfigurationVersion);
const char* profile_name = GetProfileName(m_Profile);
if (profile_name) {
inspector.AddField("Profile", profile_name);
} else {
inspector.AddField("Profile", m_Profile);
}
inspector.AddField("Profile Compatibility", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX);
inspector.AddField("Level", m_Level);
inspector.AddField("NALU Length Size", m_NaluLengthSize);
for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
inspector.AddField("Sequence Parameter", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize());
}
for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {
inspector.AddField("Picture Parameter", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize());
}
return AP4_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_2609_1 |
crossvul-cpp_data_bad_4037_0 | /*
* Copyright (C) 2004-2020 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Query.h>
using std::set;
using std::map;
using std::vector;
#define CALLMOD(MOD, CLIENT, USER, NETWORK, FUNC) \
{ \
CModule* pModule = nullptr; \
if (NETWORK && (pModule = (NETWORK)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
pModule->SetClient(CLIENT); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(NETWORK)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = (USER)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(USER)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = CZNC::Get().GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
CUser* pOldUser = pModule->GetUser(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->SetUser(USER); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
pModule->SetUser(pOldUser); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
CZNC::Get().GetModules().UnloadModule(MOD); \
} \
} \
} else { \
PutStatus(t_f("No such module {1}")(MOD)); \
} \
}
CClient::~CClient() {
if (m_spAuth) {
CClientAuth* pAuth = (CClientAuth*)&(*m_spAuth);
pAuth->Invalidate();
}
if (m_pUser != nullptr) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CClient::SendRequiredPasswordNotice() {
PutClient(":irc.znc.in 464 " + GetNick() + " :Password required");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"You need to send your password. "
"Configure your client to send a server password.");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"To connect now, you can use /quote PASS <username>:<password>, "
"or /quote PASS <username>/<network>:<password> to connect to a "
"specific network.");
}
void CClient::ReadLine(const CString& sData) {
CLanguageScope user_lang(GetUser() ? GetUser()->GetLanguage() : "");
CString sLine = sData;
sLine.Replace("\n", "");
sLine.Replace("\r", "");
DEBUG("(" << GetFullName() << ") CLI -> ZNC ["
<< CDebug::Filter(sLine) << "]");
bool bReturn = false;
if (IsAttached()) {
NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRaw(this, sLine), &bReturn);
}
if (bReturn) return;
CMessage Message(sLine);
Message.SetClient(this);
if (IsAttached()) {
NETWORKMODULECALL(OnUserRawMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRawMessage(Message), &bReturn);
}
if (bReturn) return;
CString sCommand = Message.GetCommand();
if (!IsAttached()) {
// The following commands happen before authentication with ZNC
if (sCommand.Equals("PASS")) {
m_bGotPass = true;
CString sAuthLine = Message.GetParam(0);
ParsePass(sAuthLine);
AuthUser();
// Don't forward this msg. ZNC has already registered us.
return;
} else if (sCommand.Equals("NICK")) {
CString sNick = Message.GetParam(0);
m_sNick = sNick;
m_bGotNick = true;
AuthUser();
// Don't forward this msg. ZNC will handle nick changes until auth
// is complete
return;
} else if (sCommand.Equals("USER")) {
CString sAuthLine = Message.GetParam(0);
if (m_sUser.empty() && !sAuthLine.empty()) {
ParseUser(sAuthLine);
}
m_bGotUser = true;
if (m_bGotPass) {
AuthUser();
} else if (!m_bInCap) {
SendRequiredPasswordNotice();
}
// Don't forward this msg. ZNC has already registered us.
return;
}
}
if (Message.GetType() == CMessage::Type::Capability) {
HandleCap(Message);
// Don't let the client talk to the server directly about CAP,
// we don't want anything enabled that ZNC does not support.
return;
}
if (!m_pUser) {
// Only CAP, NICK, USER and PASS are allowed before login
return;
}
switch (Message.GetType()) {
case CMessage::Type::Action:
bReturn = OnActionMessage(Message);
break;
case CMessage::Type::CTCP:
bReturn = OnCTCPMessage(Message);
break;
case CMessage::Type::Join:
bReturn = OnJoinMessage(Message);
break;
case CMessage::Type::Mode:
bReturn = OnModeMessage(Message);
break;
case CMessage::Type::Notice:
bReturn = OnNoticeMessage(Message);
break;
case CMessage::Type::Part:
bReturn = OnPartMessage(Message);
break;
case CMessage::Type::Ping:
bReturn = OnPingMessage(Message);
break;
case CMessage::Type::Pong:
bReturn = OnPongMessage(Message);
break;
case CMessage::Type::Quit:
bReturn = OnQuitMessage(Message);
break;
case CMessage::Type::Text:
bReturn = OnTextMessage(Message);
break;
case CMessage::Type::Topic:
bReturn = OnTopicMessage(Message);
break;
default:
bReturn = OnOtherMessage(Message);
break;
}
if (bReturn) return;
PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags));
}
void CClient::SetNick(const CString& s) { m_sNick = s; }
void CClient::SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect,
bool bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientDisconnected(this);
if (bDisconnect) {
ClearServerDependentCaps();
// Tell the client they are no longer in these channels.
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (const CChan* pChan : vChans) {
if (!(pChan->IsDetached())) {
PutClient(":" + m_pNetwork->GetIRCNick().GetNickMask() +
" PART " + pChan->GetName());
}
}
}
} else if (m_pUser) {
m_pUser->UserDisconnected(this);
}
m_pNetwork = pNetwork;
if (bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientConnected(this);
} else if (m_pUser) {
m_pUser->UserConnected(this);
}
}
}
const vector<CClient*>& CClient::GetClients() const {
if (m_pNetwork) {
return m_pNetwork->GetClients();
}
return m_pUser->GetUserClients();
}
const CIRCSock* CClient::GetIRCSock() const {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
CIRCSock* CClient::GetIRCSock() {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
void CClient::StatusCTCP(const CString& sLine) {
CString sCommand = sLine.Token(0);
if (sCommand.Equals("PING")) {
PutStatusNotice("\001PING " + sLine.Token(1, true) + "\001");
} else if (sCommand.Equals("VERSION")) {
PutStatusNotice("\001VERSION " + CZNC::GetTag() + "\001");
}
}
bool CClient::SendMotd() {
const VCString& vsMotd = CZNC::Get().GetMotd();
if (!vsMotd.size()) {
return false;
}
for (const CString& sLine : vsMotd) {
if (m_pNetwork) {
PutStatusNotice(m_pNetwork->ExpandString(sLine));
} else {
PutStatusNotice(m_pUser->ExpandString(sLine));
}
}
return true;
}
void CClient::AuthUser() {
if (!m_bGotNick || !m_bGotUser || !m_bGotPass || m_bInCap || IsAttached())
return;
m_spAuth = std::make_shared<CClientAuth>(this, m_sUser, m_sPass);
CZNC::Get().AuthUser(m_spAuth);
}
CClientAuth::CClientAuth(CClient* pClient, const CString& sUsername,
const CString& sPassword)
: CAuthBase(sUsername, sPassword, pClient), m_pClient(pClient) {}
void CClientAuth::RefusedLogin(const CString& sReason) {
if (m_pClient) {
m_pClient->RefuseLogin(sReason);
}
}
CString CAuthBase::GetRemoteIP() const {
if (m_pSock) return m_pSock->GetRemoteIP();
return "";
}
void CAuthBase::Invalidate() { m_pSock = nullptr; }
void CAuthBase::AcceptLogin(CUser& User) {
if (m_pSock) {
AcceptedLogin(User);
Invalidate();
}
}
void CAuthBase::RefuseLogin(const CString& sReason) {
if (!m_pSock) return;
CUser* pUser = CZNC::Get().FindUser(GetUsername());
// If the username is valid, notify that user that someone tried to
// login. Use sReason because there are other reasons than "wrong
// password" for a login to be rejected (e.g. fail2ban).
if (pUser) {
pUser->PutStatusNotice(t_f(
"A client from {1} attempted to login as you, but was rejected: "
"{2}")(GetRemoteIP(), sReason));
}
GLOBALMODULECALL(OnFailedLogin(GetUsername(), GetRemoteIP()), NOTHING);
RefusedLogin(sReason);
Invalidate();
}
void CClient::RefuseLogin(const CString& sReason) {
PutStatus("Bad username and/or password.");
PutClient(":irc.znc.in 464 " + GetNick() + " :" + sReason);
Close(Csock::CLT_AFTERWRITE);
}
void CClientAuth::AcceptedLogin(CUser& User) {
if (m_pClient) {
m_pClient->AcceptLogin(User);
}
}
void CClient::AcceptLogin(CUser& User) {
m_sPass = "";
m_pUser = &User;
// Set our proper timeout and set back our proper timeout mode
// (constructor set a different timeout and mode)
SetTimeout(User.GetNoTrafficTimeout(), TMO_READ);
SetSockName("USR::" + m_pUser->GetUsername());
SetEncoding(m_pUser->GetClientEncoding());
if (!m_sNetwork.empty()) {
m_pNetwork = m_pUser->FindNetwork(m_sNetwork);
if (!m_pNetwork) {
PutStatus(t_f("Network {1} doesn't exist.")(m_sNetwork));
}
} else if (!m_pUser->GetNetworks().empty()) {
// If a user didn't supply a network, and they have a network called
// "default" then automatically use this network.
m_pNetwork = m_pUser->FindNetwork("default");
// If no "default" network, try "user" network. It's for compatibility
// with early network stuff in ZNC, which converted old configs to
// "user" network.
if (!m_pNetwork) m_pNetwork = m_pUser->FindNetwork("user");
// Otherwise, just try any network of the user.
if (!m_pNetwork) m_pNetwork = *m_pUser->GetNetworks().begin();
if (m_pNetwork && m_pUser->GetNetworks().size() > 1) {
PutStatusNotice(
t_s("You have several networks configured, but no network was "
"specified for the connection."));
PutStatusNotice(
t_f("Selecting network {1}. To see list of all configured "
"networks, use /znc ListNetworks")(m_pNetwork->GetName()));
PutStatusNotice(t_f(
"If you want to choose another network, use /znc JumpNetwork "
"<network>, or connect to ZNC with username {1}/<network> "
"(instead of just {1})")(m_pUser->GetUsername()));
}
} else {
PutStatusNotice(
t_s("You have no networks configured. Use /znc AddNetwork "
"<network> to add one."));
}
SetNetwork(m_pNetwork, false);
SendMotd();
NETWORKMODULECALL(OnClientLogin(), m_pUser, m_pNetwork, this, NOTHING);
}
void CClient::Timeout() { PutClient("ERROR :" + t_s("Closing link: Timeout")); }
void CClient::Connected() { DEBUG(GetSockName() << " == Connected();"); }
void CClient::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
}
void CClient::Disconnected() {
DEBUG(GetSockName() << " == Disconnected()");
CIRCNetwork* pNetwork = m_pNetwork;
SetNetwork(nullptr, false, false);
if (m_pUser) {
NETWORKMODULECALL(OnClientDisconnect(), m_pUser, pNetwork, this,
NOTHING);
}
}
void CClient::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
if (IsAttached()) {
PutClient("ERROR :" + t_s("Closing link: Too long raw line"));
}
Close();
}
void CClient::BouncedOff() {
PutStatusNotice(
t_s("You are being disconnected because another user just "
"authenticated as you."));
Close(Csock::CLT_AFTERWRITE);
}
void CClient::PutIRC(const CString& sLine) {
if (m_pNetwork) {
m_pNetwork->PutIRC(sLine);
}
}
CString CClient::GetFullName() const {
if (!m_pUser) return GetRemoteIP();
CString sFullName = m_pUser->GetUsername();
if (!m_sIdentifier.empty()) sFullName += "@" + m_sIdentifier;
if (m_pNetwork) sFullName += "/" + m_pNetwork->GetName();
return sFullName;
}
void CClient::PutClient(const CString& sLine) {
PutClient(CMessage(sLine));
}
bool CClient::PutClient(const CMessage& Message) {
if (!m_bAwayNotify && Message.GetType() == CMessage::Type::Away) {
return false;
} else if (!m_bAccountNotify &&
Message.GetType() == CMessage::Type::Account) {
return false;
}
CMessage Msg(Message);
const CIRCSock* pIRCSock = GetIRCSock();
if (pIRCSock) {
if (Msg.GetType() == CMessage::Type::Numeric) {
unsigned int uCode = Msg.As<CNumericMessage>().GetCode();
if (uCode == 352) { // RPL_WHOREPLY
if (!m_bNamesx && pIRCSock->HasNamesx()) {
// The server has NAMESX, but the client doesn't, so we need
// to remove extra prefixes
CString sNick = Msg.GetParam(6);
if (sNick.size() > 1 && pIRCSock->IsPermChar(sNick[1])) {
CString sNewNick = sNick;
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNewNick = sNick[0] + sNick.substr(pos);
}
Msg.SetParam(6, sNewNick);
}
}
} else if (uCode == 353) { // RPL_NAMES
if ((!m_bNamesx && pIRCSock->HasNamesx()) ||
(!m_bUHNames && pIRCSock->HasUHNames())) {
// The server has either UHNAMES or NAMESX, but the client
// is missing either or both
CString sNicks = Msg.GetParam(3);
VCString vsNicks;
sNicks.Split(" ", vsNicks, false);
for (CString& sNick : vsNicks) {
if (sNick.empty()) break;
if (!m_bNamesx && pIRCSock->HasNamesx() &&
pIRCSock->IsPermChar(sNick[0])) {
// The server has NAMESX, but the client doesn't, so
// we just use the first perm char
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNick = sNick[0] + sNick.substr(pos);
}
}
if (!m_bUHNames && pIRCSock->HasUHNames()) {
// The server has UHNAMES, but the client doesn't,
// so we strip away ident and host
sNick = sNick.Token(0, false, "!");
}
}
Msg.SetParam(
3, CString(" ").Join(vsNicks.begin(), vsNicks.end()));
}
}
} else if (Msg.GetType() == CMessage::Type::Join) {
if (!m_bExtendedJoin && pIRCSock->HasExtendedJoin()) {
Msg.SetParams({Msg.As<CJoinMessage>().GetTarget()});
}
}
}
MCString mssTags;
for (const auto& it : Msg.GetTags()) {
if (IsTagEnabled(it.first)) {
mssTags[it.first] = it.second;
}
}
if (HasServerTime()) {
// If the server didn't set the time tag, manually set it
mssTags.emplace("time", CUtils::FormatServerTime(Msg.GetTime()));
}
Msg.SetTags(mssTags);
Msg.SetClient(this);
Msg.SetNetwork(m_pNetwork);
bool bReturn = false;
NETWORKMODULECALL(OnSendToClientMessage(Msg), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
return PutClientRaw(Msg.ToString());
}
bool CClient::PutClientRaw(const CString& sLine) {
CString sCopy = sLine;
bool bReturn = false;
NETWORKMODULECALL(OnSendToClient(sCopy, *this), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
DEBUG("(" << GetFullName() << ") ZNC -> CLI ["
<< CDebug::Filter(sCopy) << "]");
Write(sCopy + "\r\n");
return true;
}
void CClient::PutStatusNotice(const CString& sLine) {
PutModNotice("status", sLine);
}
unsigned int CClient::PutStatus(const CTable& table) {
unsigned int idx = 0;
CString sLine;
while (table.GetLine(idx++, sLine)) PutStatus(sLine);
return idx - 1;
}
void CClient::PutStatus(const CString& sLine) { PutModule("status", sLine); }
void CClient::PutModNotice(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in NOTICE " << GetNick() << " :" << sLine
<< "]");
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) + "!znc@znc.in NOTICE " +
GetNick() + " :" + sLine + "\r\n");
}
void CClient::PutModule(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " << GetNick() << " :" << sLine
<< "]");
VCString vsLines;
sLine.Split("\n", vsLines);
for (const CString& s : vsLines) {
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " + GetNick() + " :" + s + "\r\n");
}
}
CString CClient::GetNick(bool bAllowIRCNick) const {
CString sRet;
const CIRCSock* pSock = GetIRCSock();
if (bAllowIRCNick && pSock && pSock->IsAuthed()) {
sRet = pSock->GetNick();
}
return (sRet.empty()) ? m_sNick : sRet;
}
CString CClient::GetNickMask() const {
if (GetIRCSock() && GetIRCSock()->IsAuthed()) {
return GetIRCSock()->GetNickMask();
}
CString sHost =
m_pNetwork ? m_pNetwork->GetBindHost() : m_pUser->GetBindHost();
if (sHost.empty()) {
sHost = "irc.znc.in";
}
return GetNick() + "!" +
(m_pNetwork ? m_pNetwork->GetIdent() : m_pUser->GetIdent()) + "@" +
sHost;
}
bool CClient::IsValidIdentifier(const CString& sIdentifier) {
// ^[-\w]+$
if (sIdentifier.empty()) {
return false;
}
const char* p = sIdentifier.c_str();
while (*p) {
if (*p != '_' && *p != '-' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
void CClient::RespondCap(const CString& sResponse) {
PutClient(":irc.znc.in CAP " + GetNick() + " " + sResponse);
}
void CClient::HandleCap(const CMessage& Message) {
CString sSubCmd = Message.GetParam(0);
if (sSubCmd.Equals("LS")) {
SCString ssOfferCaps;
for (const auto& it : m_mCoreCaps) {
bool bServerDependent = std::get<0>(it.second);
if (!bServerDependent ||
m_ssServerDependentCaps.count(it.first) > 0)
ssOfferCaps.insert(it.first);
}
GLOBALMODULECALL(OnClientCapLs(this, ssOfferCaps), NOTHING);
CString sRes =
CString(" ").Join(ssOfferCaps.begin(), ssOfferCaps.end());
RespondCap("LS :" + sRes);
m_bInCap = true;
if (Message.GetParam(1).ToInt() >= 302) {
m_bCapNotify = true;
}
} else if (sSubCmd.Equals("END")) {
m_bInCap = false;
if (!IsAttached()) {
if (!m_pUser && m_bGotUser && !m_bGotPass) {
SendRequiredPasswordNotice();
} else {
AuthUser();
}
}
} else if (sSubCmd.Equals("REQ")) {
VCString vsTokens;
Message.GetParam(1).Split(" ", vsTokens, false);
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
bool bAccepted = false;
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
bAccepted = !bServerDependent ||
m_ssServerDependentCaps.count(sCap) > 0;
}
GLOBALMODULECALL(IsClientCapSupported(this, sCap, bVal),
&bAccepted);
if (!bAccepted) {
// Some unsupported capability is requested
RespondCap("NAK :" + Message.GetParam(1));
return;
}
}
// All is fine, we support what was requested
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
auto handler_it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != handler_it) {
const auto& handler = std::get<1>(handler_it->second);
handler(bVal);
}
GLOBALMODULECALL(OnClientCapRequest(this, sCap, bVal), NOTHING);
if (bVal) {
m_ssAcceptedCaps.insert(sCap);
} else {
m_ssAcceptedCaps.erase(sCap);
}
}
RespondCap("ACK :" + Message.GetParam(1));
} else if (sSubCmd.Equals("LIST")) {
CString sList =
CString(" ").Join(m_ssAcceptedCaps.begin(), m_ssAcceptedCaps.end());
RespondCap("LIST :" + sList);
} else {
PutClient(":irc.znc.in 410 " + GetNick() + " " + sSubCmd +
" :Invalid CAP subcommand");
}
}
void CClient::ParsePass(const CString& sAuthLine) {
// [user[@identifier][/network]:]password
const size_t uColon = sAuthLine.find(":");
if (uColon != CString::npos) {
m_sPass = sAuthLine.substr(uColon + 1);
ParseUser(sAuthLine.substr(0, uColon));
} else {
m_sPass = sAuthLine;
}
}
void CClient::ParseUser(const CString& sAuthLine) {
// user[@identifier][/network]
const size_t uSlash = sAuthLine.rfind("/");
if (uSlash != CString::npos) {
m_sNetwork = sAuthLine.substr(uSlash + 1);
ParseIdentifier(sAuthLine.substr(0, uSlash));
} else {
ParseIdentifier(sAuthLine);
}
}
void CClient::ParseIdentifier(const CString& sAuthLine) {
// user[@identifier]
const size_t uAt = sAuthLine.rfind("@");
if (uAt != CString::npos) {
const CString sId = sAuthLine.substr(uAt + 1);
if (IsValidIdentifier(sId)) {
m_sIdentifier = sId;
m_sUser = sAuthLine.substr(0, uAt);
} else {
m_sUser = sAuthLine;
}
} else {
m_sUser = sAuthLine;
}
}
void CClient::SetTagSupport(const CString& sTag, bool bState) {
if (bState) {
m_ssSupportedTags.insert(sTag);
} else {
m_ssSupportedTags.erase(sTag);
}
}
void CClient::NotifyServerDependentCaps(const SCString& ssCaps) {
for (const CString& sCap : ssCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
if (bServerDependent) {
m_ssServerDependentCaps.insert(sCap);
}
}
}
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " NEW :" + sCaps);
}
}
void CClient::ClearServerDependentCaps() {
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " DEL :" + sCaps);
for (const CString& sCap : m_ssServerDependentCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
const auto& handler = std::get<1>(it->second);
handler(false);
}
}
}
m_ssServerDependentCaps.clear();
}
template <typename T>
void CClient::AddBuffer(const T& Message) {
const CString sTarget = Message.GetTarget();
T Format;
Format.Clone(Message);
Format.SetNick(CNick(_NAMEDFMT(GetNickMask())));
Format.SetTarget(_NAMEDFMT(sTarget));
Format.SetText("{text}");
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline()) {
pChan->AddBuffer(Format, Message.GetText());
}
} else if (Message.GetType() != CMessage::Type::Notice) {
if (!m_pUser->AutoClearQueryBuffer() || !m_pNetwork->IsUserOnline()) {
CQuery* pQuery = m_pNetwork->AddQuery(sTarget);
if (pQuery) {
pQuery->AddBuffer(Format, Message.GetText());
}
}
}
}
void CClient::EchoMessage(const CMessage& Message) {
CMessage EchoedMessage = Message;
for (CClient* pClient : GetClients()) {
if (pClient->HasEchoMessage() ||
(pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) ||
pClient->HasSelfMessage()))) {
EchoedMessage.SetNick(GetNickMask());
pClient->PutClient(EchoedMessage);
}
}
}
set<CChan*> CClient::MatchChans(const CString& sPatterns) const {
VCString vsPatterns;
sPatterns.Replace_n(",", " ")
.Split(" ", vsPatterns, false, "", "", true, true);
set<CChan*> sChans;
for (const CString& sPattern : vsPatterns) {
vector<CChan*> vChans = m_pNetwork->FindChans(sPattern);
sChans.insert(vChans.begin(), vChans.end());
}
return sChans;
}
unsigned int CClient::AttachChans(const std::set<CChan*>& sChans) {
unsigned int uAttached = 0;
for (CChan* pChan : sChans) {
if (!pChan->IsDetached()) continue;
uAttached++;
pChan->AttachUser();
}
return uAttached;
}
unsigned int CClient::DetachChans(const std::set<CChan*>& sChans) {
unsigned int uDetached = 0;
for (CChan* pChan : sChans) {
if (pChan->IsDetached()) continue;
uDetached++;
pChan->DetachUser();
}
return uDetached;
}
bool CClient::OnActionMessage(CActionMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserActionMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnCTCPMessage(CCTCPMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
if (Message.IsReply()) {
CString sCTCP = Message.GetText();
if (sCTCP.Token(0) == "VERSION") {
// There are 2 different scenarios:
//
// a) CTCP reply for VERSION is not set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC forwards CTCP VERSION to client
// 3. Client replies with something
// 4. ZNC adds itself to the reply
// 5. ZNC sends the modified reply to whoever asked
//
// b) CTCP reply for VERSION is set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC replies with the configured reply (or just drops it if
// empty), without forwarding anything to client
// 3. Client does not see any CTCP request, and does not reply
//
// So, if user doesn't want "via ZNC" in CTCP VERSION reply, they
// can set custom reply.
//
// See more bikeshedding at github issues #820 and #1012
Message.SetText(sCTCP + " via " + CZNC::GetTag(false));
}
}
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
if (Message.IsReply()) {
NETWORKMODULECALL(OnUserCTCPReplyMessage(Message), m_pUser,
m_pNetwork, this, &bContinue);
} else {
NETWORKMODULECALL(OnUserCTCPMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
}
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(t_f(
"Your CTCP to {1} got lost, you are not connected to IRC!")(
Message.GetTarget()));
continue;
}
if (m_pNetwork) {
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnJoinMessage(CJoinMessage& Message) {
CString sChans = Message.GetTarget();
CString sKeys = Message.GetKey();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
VCString vsKeys;
sKeys.Split(",", vsKeys, true);
sKeys.clear();
for (unsigned int a = 0; a < vsChans.size(); a++) {
Message.SetTarget(vsChans[a]);
Message.SetKey((a < vsKeys.size()) ? vsKeys[a] : "");
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(vsChans[a]));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserJoinMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
CString sChannel = Message.GetTarget();
CString sKey = Message.GetKey();
if (m_pNetwork) {
CChan* pChan = m_pNetwork->FindChan(sChannel);
if (pChan) {
if (pChan->IsDetached())
pChan->AttachUser(this);
else
pChan->JoinUser(sKey);
continue;
} else if (!sChannel.empty()) {
pChan = new CChan(sChannel, m_pNetwork, false);
if (m_pNetwork->AddChan(pChan)) {
pChan->SetKey(sKey);
}
}
}
if (!sChannel.empty()) {
sChans += (sChans.empty()) ? sChannel : CString("," + sChannel);
if (!vsKeys.empty()) {
sKeys += (sKeys.empty()) ? sKey : CString("," + sKey);
}
}
}
Message.SetTarget(sChans);
Message.SetKey(sKeys);
return sChans.empty();
}
bool CClient::OnModeMessage(CModeMessage& Message) {
CString sTarget = Message.GetTarget();
if (m_pNetwork && m_pNetwork->IsChan(sTarget) && !Message.HasModes()) {
// If we are on that channel and already received a
// /mode reply from the server, we can answer this
// request ourself.
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan && pChan->IsOn() && !pChan->GetModeString().empty()) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 324 " + GetNick() +
" " + sTarget + " " + pChan->GetModeString());
if (pChan->GetCreationDate() > 0) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 329 " +
GetNick() + " " + sTarget + " " +
CString(pChan->GetCreationDate()));
}
return true;
}
}
return false;
}
bool CClient::OnNoticeMessage(CNoticeMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
if (!sTarget.Equals("status")) {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModNotice(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserNoticeMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your notice to {1} got lost, you are not connected to "
"IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnPartMessage(CPartMessage& Message) {
CString sChans = Message.GetTarget();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
for (CString& sChan : vsChans) {
bool bContinue = false;
Message.SetTarget(sChan);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
NETWORKMODULECALL(OnUserPartMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
sChan = Message.GetTarget();
CChan* pChan = m_pNetwork ? m_pNetwork->FindChan(sChan) : nullptr;
if (pChan && !pChan->IsOn()) {
PutStatusNotice(t_f("Removing channel {1}")(sChan));
m_pNetwork->DelChan(sChan);
} else {
sChans += (sChans.empty()) ? sChan : CString("," + sChan);
}
}
if (sChans.empty()) {
return true;
}
Message.SetTarget(sChans);
return false;
}
bool CClient::OnPingMessage(CMessage& Message) {
// All PONGs are generated by ZNC. We will still forward this to
// the ircd, but all PONGs from irc will be blocked.
if (!Message.GetParams().empty())
PutClient(":irc.znc.in PONG irc.znc.in " + Message.GetParamsColon(0));
else
PutClient(":irc.znc.in PONG irc.znc.in");
return false;
}
bool CClient::OnPongMessage(CMessage& Message) {
// Block PONGs, we already responded to the pings
return true;
}
bool CClient::OnQuitMessage(CQuitMessage& Message) {
bool bReturn = false;
NETWORKMODULECALL(OnUserQuitMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
if (!bReturn) {
Close(Csock::CLT_AFTERWRITE); // Treat a client quit as a detach
}
// Don't forward this msg. We don't want the client getting us
// disconnected.
return true;
}
bool CClient::OnTextMessage(CTextMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
EchoMessage(Message);
if (sTarget.Equals("status")) {
CString sMsg = Message.GetText();
UserCommand(sMsg);
} else {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a PRIVMSG to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your message to {1} got lost, you are not connected "
"to IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnTopicMessage(CTopicMessage& Message) {
bool bReturn = false;
CString sChan = Message.GetTarget();
CString sTopic = Message.GetTopic();
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
if (!sTopic.empty()) {
NETWORKMODULECALL(OnUserTopicMessage(Message), m_pUser, m_pNetwork,
this, &bReturn);
} else {
NETWORKMODULECALL(OnUserTopicRequest(sChan), m_pUser, m_pNetwork, this,
&bReturn);
Message.SetTarget(sChan);
}
return bReturn;
}
bool CClient::OnOtherMessage(CMessage& Message) {
const CString& sCommand = Message.GetCommand();
if (sCommand.Equals("ZNC")) {
CString sTarget = Message.GetParam(0);
CString sModCommand;
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
sModCommand = Message.GetParamsColon(1);
} else {
sTarget = "status";
sModCommand = Message.GetParamsColon(0);
}
if (sTarget.Equals("status")) {
if (sModCommand.empty())
PutStatus(t_s("Hello. How may I help you?"));
else
UserCommand(sModCommand);
} else {
if (sModCommand.empty())
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
PutModule(t_s("Hello. How may I help you?")))
else
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(sModCommand))
}
return true;
} else if (sCommand.Equals("ATTACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /attach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uAttachedChans = AttachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Attached {1} channel", "Attached {1} channels",
uAttachedChans)(uAttachedChans));
return true;
} else if (sCommand.Equals("DETACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /detach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uDetached = DetachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Detached {1} channel", "Detached {1} channels",
uDetached)(uDetached));
return true;
} else if (sCommand.Equals("PROTOCTL")) {
for (const CString& sParam : Message.GetParams()) {
if (sParam == "NAMESX") {
m_bNamesx = true;
} else if (sParam == "UHNAMES") {
m_bUHNames = true;
}
}
return true; // If the server understands it, we already enabled namesx
// / uhnames
}
return false;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_4037_0 |
crossvul-cpp_data_good_2807_0 | /*****************************************************************
|
| AP4 - Atom Factory
|
| Copyright 2002-2012 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4Types.h"
#include "Ap4Utils.h"
#include "Ap4AtomFactory.h"
#include "Ap4SampleEntry.h"
#include "Ap4UuidAtom.h"
#include "Ap4IsmaCryp.h"
#include "Ap4UrlAtom.h"
#include "Ap4MoovAtom.h"
#include "Ap4MvhdAtom.h"
#include "Ap4MehdAtom.h"
#include "Ap4MfhdAtom.h"
#include "Ap4TfhdAtom.h"
#include "Ap4TrunAtom.h"
#include "Ap4TrakAtom.h"
#include "Ap4HdlrAtom.h"
#include "Ap4DrefAtom.h"
#include "Ap4TkhdAtom.h"
#include "Ap4TrexAtom.h"
#include "Ap4TfhdAtom.h"
#include "Ap4MdhdAtom.h"
#include "Ap4StsdAtom.h"
#include "Ap4StscAtom.h"
#include "Ap4StcoAtom.h"
#include "Ap4Co64Atom.h"
#include "Ap4StszAtom.h"
#include "Ap4Stz2Atom.h"
#include "Ap4IodsAtom.h"
#include "Ap4EsdsAtom.h"
#include "Ap4SttsAtom.h"
#include "Ap4CttsAtom.h"
#include "Ap4StssAtom.h"
#include "Ap4FtypAtom.h"
#include "Ap4VmhdAtom.h"
#include "Ap4SmhdAtom.h"
#include "Ap4NmhdAtom.h"
#include "Ap4SthdAtom.h"
#include "Ap4HmhdAtom.h"
#include "Ap4ElstAtom.h"
#include "Ap4SchmAtom.h"
#include "Ap4FrmaAtom.h"
#include "Ap4TimsAtom.h"
#include "Ap4RtpAtom.h"
#include "Ap4SdpAtom.h"
#include "Ap4IkmsAtom.h"
#include "Ap4IsfmAtom.h"
#include "Ap4IsltAtom.h"
#include "Ap4OdheAtom.h"
#include "Ap4OhdrAtom.h"
#include "Ap4OddaAtom.h"
#include "Ap4TrefTypeAtom.h"
#include "Ap4MetaData.h"
#include "Ap4IproAtom.h"
#include "Ap4OdafAtom.h"
#include "Ap4GrpiAtom.h"
#include "Ap4AvccAtom.h"
#include "Ap4HvccAtom.h"
#include "Ap4DvccAtom.h"
#include "Ap4Marlin.h"
#include "Ap48bdlAtom.h"
#include "Ap4Piff.h"
#include "Ap4TfraAtom.h"
#include "Ap4MfroAtom.h"
#include "Ap4TfdtAtom.h"
#include "Ap4TencAtom.h"
#include "Ap4SencAtom.h"
#include "Ap4SaioAtom.h"
#include "Ap4SaizAtom.h"
#include "Ap4PdinAtom.h"
#include "Ap4BlocAtom.h"
#include "Ap4AinfAtom.h"
#include "Ap4PsshAtom.h"
#include "Ap4Dec3Atom.h"
#include "Ap4SidxAtom.h"
#include "Ap4SbgpAtom.h"
#include "Ap4SgpdAtom.h"
/*----------------------------------------------------------------------
| AP4_AtomFactory::~AP4_AtomFactory
+---------------------------------------------------------------------*/
AP4_AtomFactory::~AP4_AtomFactory()
{
m_TypeHandlers.DeleteReferences();
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::AddTypeHandler
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::AddTypeHandler(TypeHandler* handler)
{
return m_TypeHandlers.Add(handler);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::RemoveTypeHandler
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::RemoveTypeHandler(TypeHandler* handler)
{
return m_TypeHandlers.Remove(handler);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_Atom*& atom)
{
AP4_LargeSize stream_size = 0;
AP4_Position stream_position = 0;
AP4_LargeSize bytes_available = (AP4_LargeSize)(-1);
if (AP4_SUCCEEDED(stream.GetSize(stream_size)) &&
stream_size != 0 &&
AP4_SUCCEEDED(stream.Tell(stream_position)) &&
stream_position <= stream_size) {
bytes_available = stream_size-stream_position;
}
return CreateAtomFromStream(stream, bytes_available, atom);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_LargeSize& bytes_available,
AP4_Atom*& atom)
{
AP4_Result result;
// NULL by default
atom = NULL;
// check that there are enough bytes for at least a header
if (bytes_available < 8) return AP4_ERROR_EOS;
// remember current stream offset
AP4_Position start;
stream.Tell(start);
// read atom size
AP4_UI32 size_32;
result = stream.ReadUI32(size_32);
if (AP4_FAILED(result)) {
stream.Seek(start);
return result;
}
AP4_UI64 size = size_32;
// read atom type
AP4_Atom::Type type;
result = stream.ReadUI32(type);
if (AP4_FAILED(result)) {
stream.Seek(start);
return result;
}
// handle special size values
bool atom_is_large = false;
bool force_64 = false;
if (size == 0) {
// atom extends to end of file
AP4_LargeSize stream_size = 0;
stream.GetSize(stream_size);
if (stream_size >= start) {
size = stream_size - start;
}
} else if (size == 1) {
// 64-bit size
atom_is_large = true;
if (bytes_available < 16) {
stream.Seek(start);
return AP4_ERROR_INVALID_FORMAT;
}
stream.ReadUI64(size);
if (size <= 0xFFFFFFFF) {
force_64 = true;
}
}
// check the size
if ((size > 0 && size < 8) || size > bytes_available) {
stream.Seek(start);
return AP4_ERROR_INVALID_FORMAT;
}
// create the atom
result = CreateAtomFromStream(stream, type, size_32, size, atom);
if (AP4_FAILED(result)) return result;
// if we failed to create an atom, use a generic version
if (atom == NULL) {
unsigned int payload_offset = 8;
if (atom_is_large) payload_offset += 8;
stream.Seek(start+payload_offset);
atom = new AP4_UnknownAtom(type, size, stream);
}
// special case: if the atom is poorly encoded and has a 64-bit
// size header but an actual size that fits on 32-bit, adjust the
// object to reflect that.
if (force_64) {
atom->SetSize32(1);
atom->SetSize64(size);
}
// adjust the available size
bytes_available -= size;
// skip to the end of the atom
result = stream.Seek(start+size);
if (AP4_FAILED(result)) {
delete atom;
atom = NULL;
return result;
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_UI32 type,
AP4_UI32 size_32,
AP4_UI64 size_64,
AP4_Atom*& atom)
{
bool atom_is_large = (size_32 == 1);
bool force_64 = (size_32==1 && ((size_64>>32) == 0));
// create the atom
if (GetContext() == AP4_ATOM_TYPE_STSD) {
// sample entry
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
switch (type) {
case AP4_ATOM_TYPE_MP4A:
atom = new AP4_Mp4aSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MP4V:
atom = new AP4_Mp4vSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MP4S:
atom = new AP4_Mp4sSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ENCA:
atom = new AP4_EncaSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ENCV:
atom = new AP4_EncvSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_DRMS:
atom = new AP4_DrmsSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_DRMI:
atom = new AP4_DrmiSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_AVC1:
case AP4_ATOM_TYPE_AVC2:
case AP4_ATOM_TYPE_AVC3:
case AP4_ATOM_TYPE_AVC4:
case AP4_ATOM_TYPE_DVAV:
case AP4_ATOM_TYPE_DVA1:
atom = new AP4_AvcSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_HEV1:
case AP4_ATOM_TYPE_HVC1:
case AP4_ATOM_TYPE_DVHE:
case AP4_ATOM_TYPE_DVH1:
atom = new AP4_HevcSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ALAC:
case AP4_ATOM_TYPE_AC_3:
case AP4_ATOM_TYPE_EC_3:
case AP4_ATOM_TYPE_DTSC:
case AP4_ATOM_TYPE_DTSH:
case AP4_ATOM_TYPE_DTSL:
case AP4_ATOM_TYPE_DTSE:
atom = new AP4_AudioSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_RTP_:
atom = new AP4_RtpHintSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_STPP:
atom = new AP4_SubtitleSampleEntry(type, size_32, stream, *this);
break;
default: {
// try all the external type handlers
AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
while (handler_item) {
TypeHandler* handler = handler_item->GetData();
if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
break;
}
handler_item = handler_item->GetNext();
}
// no custom handler, create a generic entry
if (atom == NULL) {
atom = new AP4_UnknownSampleEntry(type, (AP4_UI32)size_64, stream);
}
break;
}
}
} else {
// regular atom
switch (type) {
case AP4_ATOM_TYPE_MOOV:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MoovAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MVHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MvhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MEHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MehdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MFHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TRAK:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrakAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_TREX:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrexAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HDLR:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HdlrAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TKHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TkhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TRUN:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrunAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFRA:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfraAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MFRO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfroAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MDHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MdhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StsdAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_STSC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StscAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STCO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StcoAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_CO64:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_Co64Atom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSZ:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StszAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STZ2:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_Stz2Atom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STTS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SttsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_CTTS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_CttsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StssAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IODS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IodsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ESDS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_EsdsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_AVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_DVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_DvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HVCE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HvccAtom::Create(size_32, stream);
if (atom) {
atom->SetType(AP4_ATOM_TYPE_HVCE);
}
break;
case AP4_ATOM_TYPE_AVCE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AvccAtom::Create(size_32, stream);
if (atom) {
atom->SetType(AP4_ATOM_TYPE_AVCE);
}
break;
#if !defined(AP4_CONFIG_MINI_BUILD)
case AP4_ATOM_TYPE_UUID: {
AP4_UI08 uuid[16];
AP4_Result result = stream.Read(uuid, 16);
if (AP4_FAILED(result)) return result;
if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 16) == 0) {
atom = AP4_PiffTrackEncryptionAtom::Create((AP4_UI32)size_64, stream);
} else if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 16) == 0) {
atom = AP4_PiffSampleEncryptionAtom::Create((AP4_UI32)size_64, stream);
} else {
atom = new AP4_UnknownUuidAtom(size_64, uuid, stream);
}
break;
}
case AP4_ATOM_TYPE_8ID_:
atom = new AP4_NullTerminatedStringAtom(type, size_64, stream);
break;
case AP4_ATOM_TYPE_8BDL:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_8bdlAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_DREF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_DrefAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_URL:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_UrlAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ELST:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ElstAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_VMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_VmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_NMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_NmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SthdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_FRMA:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FrmaAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SCHM:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SchmAtom::Create(size_32, &m_ContextStack, stream);
break;
case AP4_ATOM_TYPE_FTYP:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FtypAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TIMS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TimsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SDP_:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SdpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IKMS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IkmsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ISFM:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsfmAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ISLT:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsltAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ODHE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdheAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_OHDR:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OhdrAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ODDA:
atom = AP4_OddaAtom::Create(size_64, stream);
break;
case AP4_ATOM_TYPE_ODAF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdafAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_GRPI:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_GrpiAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IPRO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IproAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_RTP_:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_RtpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFDT:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfdtAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TENC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TencAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SENC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SencAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SAIZ:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SaizAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SAIO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SaioAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_PDIN:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_PdinAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_BLOC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_BlocAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_AINF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AinfAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_PSSH:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_PsshAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SIDX:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SidxAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SBGP:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SbgpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SGPD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SgpdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MKID:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
if (GetContext() == AP4_ATOM_TYPE_MARL) {
atom = AP4_MkidAtom::Create(size_32, stream);
}
break;
case AP4_ATOM_TYPE_DEC3:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
if (GetContext() == AP4_ATOM_TYPE_EC_3 || GetContext() == AP4_ATOM_TYPE_ENCA) {
atom = AP4_Dec3Atom::Create(size_32, stream);
}
break;
// track ref types
case AP4_ATOM_TYPE_HINT:
case AP4_ATOM_TYPE_CDSC:
case AP4_ATOM_TYPE_SYNC:
case AP4_ATOM_TYPE_MPOD:
case AP4_ATOM_TYPE_DPND:
case AP4_ATOM_TYPE_IPIR:
case AP4_ATOM_TYPE_ALIS:
case AP4_ATOM_TYPE_CHAP:
if (GetContext() == AP4_ATOM_TYPE_TREF) {
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrefTypeAtom::Create(type, size_32, stream);
}
break;
#endif // AP4_CONFIG_MINI_BUILD
// container atoms
case AP4_ATOM_TYPE_MOOF:
case AP4_ATOM_TYPE_MVEX:
case AP4_ATOM_TYPE_TRAF:
case AP4_ATOM_TYPE_TREF:
case AP4_ATOM_TYPE_MFRA:
case AP4_ATOM_TYPE_HNTI:
case AP4_ATOM_TYPE_STBL:
case AP4_ATOM_TYPE_MDIA:
case AP4_ATOM_TYPE_DINF:
case AP4_ATOM_TYPE_MINF:
case AP4_ATOM_TYPE_SCHI:
case AP4_ATOM_TYPE_SINF:
case AP4_ATOM_TYPE_UDTA:
case AP4_ATOM_TYPE_ILST:
case AP4_ATOM_TYPE_EDTS:
case AP4_ATOM_TYPE_MDRI:
case AP4_ATOM_TYPE_WAVE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this);
break;
// containers, only at the top
case AP4_ATOM_TYPE_MARL:
if (GetContext() == 0) {
atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this);
}
break;
// full container atoms
case AP4_ATOM_TYPE_META:
case AP4_ATOM_TYPE_ODRM:
case AP4_ATOM_TYPE_ODKM:
atom = AP4_ContainerAtom::Create(type, size_64, true, force_64, stream, *this);
break;
case AP4_ATOM_TYPE_FREE:
case AP4_ATOM_TYPE_WIDE:
case AP4_ATOM_TYPE_MDAT:
// generic atoms
break;
default: {
// try all the external type handlers
AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
while (handler_item) {
TypeHandler* handler = handler_item->GetData();
if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
break;
}
handler_item = handler_item->GetNext();
}
break;
}
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomsFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
AP4_AtomParent& atoms)
{
AP4_LargeSize stream_size = 0;
AP4_Position stream_position = 0;
AP4_LargeSize bytes_available = (AP4_LargeSize)(-1);
if (AP4_SUCCEEDED(stream.GetSize(stream_size)) &&
stream_size != 0 &&
AP4_SUCCEEDED(stream.Tell(stream_position)) &&
stream_position <= stream_size) {
bytes_available = stream_size-stream_position;
}
return CreateAtomsFromStream(stream, bytes_available, atoms);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::CreateAtomsFromStream
+---------------------------------------------------------------------*/
AP4_Result
AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
AP4_LargeSize bytes_available,
AP4_AtomParent& atoms)
{
AP4_Result result;
do {
AP4_Atom* atom = NULL;
result = CreateAtomFromStream(stream, bytes_available, atom);
if (AP4_SUCCEEDED(result) && atom != NULL) {
atoms.AddChild(atom);
}
} while (AP4_SUCCEEDED(result));
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::PushContext
+---------------------------------------------------------------------*/
void
AP4_AtomFactory::PushContext(AP4_Atom::Type context)
{
m_ContextStack.Append(context);
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::PopContext
+---------------------------------------------------------------------*/
void
AP4_AtomFactory::PopContext()
{
m_ContextStack.RemoveLast();
}
/*----------------------------------------------------------------------
| AP4_AtomFactory::GetContext
+---------------------------------------------------------------------*/
AP4_Atom::Type
AP4_AtomFactory::GetContext(AP4_Ordinal depth)
{
AP4_Ordinal available = m_ContextStack.ItemCount();
if (depth >= available) return 0;
return m_ContextStack[available-depth-1];
}
/*----------------------------------------------------------------------
| AP4_DefaultAtomFactory::Instance
+---------------------------------------------------------------------*/
AP4_DefaultAtomFactory AP4_DefaultAtomFactory::Instance_;
/*----------------------------------------------------------------------
| AP4_DefaultAtomFactory::Instance
+---------------------------------------------------------------------*/
AP4_DefaultAtomFactory::AP4_DefaultAtomFactory()
{
Initialize();
}
/*----------------------------------------------------------------------
| AP4_DefaultAtomFactory::Initialize
+---------------------------------------------------------------------*/
AP4_Result
AP4_DefaultAtomFactory::Initialize()
{
// register built-in type handlers
AP4_Result result = AddTypeHandler(new AP4_MetaDataAtomTypeHandler(this));
if (AP4_SUCCEEDED(result)) m_Initialized = true;
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_2807_0 |
crossvul-cpp_data_good_4244_0 | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
//
// Add a preview image to an OpenEXR file.
//
//----------------------------------------------------------------------------
#include "makePreview.h"
#include <ImfInputFile.h>
#include <ImfOutputFile.h>
#include <ImfTiledOutputFile.h>
#include <ImfRgbaFile.h>
#include <ImfPreviewImage.h>
#include <ImfArray.h>
#include <ImathMath.h>
#include <ImathFun.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <OpenEXRConfig.h>
using namespace OPENEXR_IMF_NAMESPACE;
using namespace IMATH_NAMESPACE;
using namespace std;
namespace {
float
knee (float x, float f)
{
return log (x * f + 1) / f;
}
unsigned char
gamma (half h, float m)
{
//
// Conversion from half to unsigned char pixel data,
// with gamma correction. The conversion is the same
// as in the exrdisplay program's ImageView class,
// except with defog, kneeLow, and kneeHigh fixed
// at 0.0, 0.0, and 5.0 respectively.
//
float x = max (0.f, h * m);
if (x > 1)
x = 1 + knee (x - 1, 0.184874f);
return (unsigned char) (IMATH_NAMESPACE::clamp (Math<float>::pow (x, 0.4545f) * 84.66f,
0.f,
255.f));
}
void
generatePreview (const char inFileName[],
float exposure,
int previewWidth,
int &previewHeight,
Array2D <PreviewRgba> &previewPixels)
{
//
// Read the input file
//
RgbaInputFile in (inFileName);
Box2i dw = in.dataWindow();
float a = in.pixelAspectRatio();
int w = dw.max.x - dw.min.x + 1;
int h = dw.max.y - dw.min.y + 1;
Array2D <Rgba> pixels (h, w);
in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);
in.readPixels (dw.min.y, dw.max.y);
//
// Make a preview image
//
previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);
previewPixels.resizeErase (previewHeight, previewWidth);
float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1;
float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1;
float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));
for (int y = 0; y < previewHeight; ++y)
{
for (int x = 0; x < previewWidth; ++x)
{
PreviewRgba &preview = previewPixels[y][x];
const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];
preview.r = gamma (pixel.r, m);
preview.g = gamma (pixel.g, m);
preview.b = gamma (pixel.b, m);
preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);
}
}
}
} // namespace
void
makePreview (const char inFileName[],
const char outFileName[],
int previewWidth,
float exposure,
bool verbose)
{
if (verbose)
cout << "generating preview image" << endl;
Array2D <PreviewRgba> previewPixels;
int previewHeight;
generatePreview (inFileName,
exposure,
previewWidth,
previewHeight,
previewPixels);
InputFile in (inFileName);
Header header = in.header();
header.setPreviewImage
(PreviewImage (previewWidth, previewHeight, &previewPixels[0][0]));
if (verbose)
cout << "copying " << inFileName << " to " << outFileName << endl;
if (header.hasTileDescription())
{
TiledOutputFile out (outFileName, header);
out.copyPixels (in);
}
else
{
OutputFile out (outFileName, header);
out.copyPixels (in);
}
if (verbose)
cout << "done." << endl;
}
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_4244_0 |
crossvul-cpp_data_bad_656_2 | /* GRAPHITE2 LICENSING
Copyright 2010, SIL International
All rights reserved.
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 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
Lesser General Public License for more details.
You should also have received a copy of the GNU Lesser General Public
License along with this library in the file named "LICENSE".
If not, write to the Free Software Foundation, 51 Franklin Street,
Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
internet at http://www.fsf.org/licenses/lgpl.html.
Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or 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 "graphite2/Font.h"
#include "inc/Face.h"
#include "inc/FileFace.h"
#include "inc/GlyphCache.h"
#include "inc/CachedFace.h"
#include "inc/CmapCache.h"
#include "inc/Silf.h"
#include "inc/json.h"
using namespace graphite2;
#if !defined GRAPHITE2_NTRACING
extern json *global_log;
#endif
namespace
{
bool load_face(Face & face, unsigned int options)
{
#ifdef GRAPHITE2_TELEMETRY
telemetry::category _misc_cat(face.tele.misc);
#endif
Face::Table silf(face, Tag::Silf, 0x00050000);
if (silf) options &= ~gr_face_dumbRendering;
else if (!(options & gr_face_dumbRendering))
return false;
if (!face.readGlyphs(options))
return false;
if (silf)
{
if (!face.readFeatures() || !face.readGraphite(silf))
{
#if !defined GRAPHITE2_NTRACING
if (global_log)
{
*global_log << json::object
<< "type" << "fontload"
<< "failure" << face.error()
<< "context" << face.error_context()
<< json::close;
}
#endif
return false;
}
else
return true;
}
else
return options & gr_face_dumbRendering;
}
}
extern "C" {
gr_face* gr_make_face_with_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *ops, unsigned int faceOptions)
//the appFaceHandle must stay alive all the time when the gr_face is alive. When finished with the gr_face, call destroy_face
{
if (ops == 0) return 0;
Face *res = new Face(appFaceHandle, *ops);
if (res && load_face(*res, faceOptions))
return static_cast<gr_face *>(res);
delete res;
return 0;
}
gr_face* gr_make_face(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn tablefn, unsigned int faceOptions)
{
const gr_face_ops ops = {sizeof(gr_face_ops), tablefn, NULL};
return gr_make_face_with_ops(appFaceHandle, &ops, faceOptions);
}
#ifndef GRAPHITE2_NSEGCACHE
gr_face* gr_make_face_with_seg_cache_and_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *ops, unsigned int cacheSize, unsigned int faceOptions)
//the appFaceHandle must stay alive all the time when the GrFace is alive. When finished with the GrFace, call destroy_face
{
if (ops == 0) return 0;
CachedFace *res = new CachedFace(appFaceHandle, *ops);
if (res && load_face(*res, faceOptions)
&& res->setupCache(cacheSize))
return static_cast<gr_face *>(static_cast<Face *>(res));
delete res;
return 0;
}
gr_face* gr_make_face_with_seg_cache(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable, unsigned int cacheSize, unsigned int faceOptions)
{
const gr_face_ops ops = {sizeof(gr_face_ops), getTable, NULL};
return gr_make_face_with_seg_cache_and_ops(appFaceHandle, &ops, cacheSize, faceOptions);
}
#endif
gr_uint32 gr_str_to_tag(const char *str)
{
uint32 res = 0;
int i = strlen(str);
if (i > 4) i = 4;
while (--i >= 0)
res = (res >> 8) + (str[i] << 24);
return res;
}
void gr_tag_to_str(gr_uint32 tag, char *str)
{
int i = 4;
while (--i >= 0)
{
str[i] = tag & 0xFF;
tag >>= 8;
}
}
inline
uint32 zeropad(const uint32 x)
{
if (x == 0x20202020) return 0;
if ((x & 0x00FFFFFF) == 0x00202020) return x & 0xFF000000;
if ((x & 0x0000FFFF) == 0x00002020) return x & 0xFFFF0000;
if ((x & 0x000000FF) == 0x00000020) return x & 0xFFFFFF00;
return x;
}
gr_feature_val* gr_face_featureval_for_lang(const gr_face* pFace, gr_uint32 langname/*0 means clone default*/) //clones the features. if none for language, clones the default
{
assert(pFace);
langname = zeropad(langname);
return static_cast<gr_feature_val *>(pFace->theSill().cloneFeatures(langname));
}
const gr_feature_ref* gr_face_find_fref(const gr_face* pFace, gr_uint32 featId) //When finished with the FeatureRef, call destroy_FeatureRef
{
assert(pFace);
featId = zeropad(featId);
const FeatureRef* pRef = pFace->featureById(featId);
return static_cast<const gr_feature_ref*>(pRef);
}
unsigned short gr_face_n_fref(const gr_face* pFace)
{
assert(pFace);
return pFace->numFeatures();
}
const gr_feature_ref* gr_face_fref(const gr_face* pFace, gr_uint16 i) //When finished with the FeatureRef, call destroy_FeatureRef
{
assert(pFace);
const FeatureRef* pRef = pFace->feature(i);
return static_cast<const gr_feature_ref*>(pRef);
}
unsigned short gr_face_n_languages(const gr_face* pFace)
{
assert(pFace);
return pFace->theSill().numLanguages();
}
gr_uint32 gr_face_lang_by_index(const gr_face* pFace, gr_uint16 i)
{
assert(pFace);
return pFace->theSill().getLangName(i);
}
void gr_face_destroy(gr_face *face)
{
delete static_cast<Face*>(face);
}
gr_uint16 gr_face_name_lang_for_locale(gr_face *face, const char * locale)
{
if (face)
{
return face->languageForLocale(locale);
}
return 0;
}
unsigned short gr_face_n_glyphs(const gr_face* pFace)
{
return pFace->glyphs().numGlyphs();
}
const gr_faceinfo *gr_face_info(const gr_face *pFace, gr_uint32 script)
{
if (!pFace) return 0;
const Silf *silf = pFace->chooseSilf(script);
if (silf) return silf->silfInfo();
return 0;
}
int gr_face_is_char_supported(const gr_face* pFace, gr_uint32 usv, gr_uint32 script)
{
const Cmap & cmap = pFace->cmap();
gr_uint16 gid = cmap[usv];
if (!gid)
{
const Silf * silf = pFace->chooseSilf(script);
gid = silf->findPseudo(usv);
}
return (gid != 0);
}
#ifndef GRAPHITE2_NFILEFACE
gr_face* gr_make_file_face(const char *filename, unsigned int faceOptions)
{
FileFace* pFileFace = new FileFace(filename);
if (*pFileFace)
{
gr_face* pRes = gr_make_face_with_ops(pFileFace, &FileFace::ops, faceOptions);
if (pRes)
{
pRes->takeFileFace(pFileFace); //takes ownership
return pRes;
}
}
//error when loading
delete pFileFace;
return NULL;
}
#ifndef GRAPHITE2_NSEGCACHE
gr_face* gr_make_file_face_with_seg_cache(const char* filename, unsigned int segCacheMaxSize, unsigned int faceOptions) //returns NULL on failure. //TBD better error handling
//when finished with, call destroy_face
{
FileFace* pFileFace = new FileFace(filename);
if (*pFileFace)
{
gr_face * pRes = gr_make_face_with_seg_cache_and_ops(pFileFace, &FileFace::ops, segCacheMaxSize, faceOptions);
if (pRes)
{
pRes->takeFileFace(pFileFace); //takes ownership
return pRes;
}
}
//error when loading
delete pFileFace;
return NULL;
}
#endif
#endif //!GRAPHITE2_NFILEFACE
} // extern "C"
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/bad_656_2 |
crossvul-cpp_data_good_2609_2 | /*****************************************************************
|
| AP4 - File Processor
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL 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, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4Processor.h"
#include "Ap4AtomSampleTable.h"
#include "Ap4MovieFragment.h"
#include "Ap4FragmentSampleTable.h"
#include "Ap4TfhdAtom.h"
#include "Ap4AtomFactory.h"
#include "Ap4Movie.h"
#include "Ap4Array.h"
#include "Ap4Sample.h"
#include "Ap4TrakAtom.h"
#include "Ap4TfraAtom.h"
#include "Ap4TrunAtom.h"
#include "Ap4TrexAtom.h"
#include "Ap4TkhdAtom.h"
#include "Ap4SidxAtom.h"
#include "Ap4DataBuffer.h"
#include "Ap4Debug.h"
/*----------------------------------------------------------------------
| types
+---------------------------------------------------------------------*/
struct AP4_SampleLocator {
AP4_SampleLocator() :
m_TrakIndex(0),
m_SampleTable(NULL),
m_SampleIndex(0),
m_ChunkIndex(0) {}
AP4_Ordinal m_TrakIndex;
AP4_AtomSampleTable* m_SampleTable;
AP4_Ordinal m_SampleIndex;
AP4_Ordinal m_ChunkIndex;
AP4_Sample m_Sample;
};
struct AP4_SampleCursor {
AP4_SampleCursor() : m_EndReached(false) {}
AP4_SampleLocator m_Locator;
bool m_EndReached;
};
struct AP4_AtomLocator {
AP4_AtomLocator(AP4_Atom* atom, AP4_UI64 offset) :
m_Atom(atom),
m_Offset(offset) {}
AP4_Atom* m_Atom;
AP4_UI64 m_Offset;
};
/*----------------------------------------------------------------------
| AP4_DefaultFragmentHandler
+---------------------------------------------------------------------*/
class AP4_DefaultFragmentHandler: public AP4_Processor::FragmentHandler {
public:
AP4_DefaultFragmentHandler(AP4_Processor::TrackHandler* track_handler) :
m_TrackHandler(track_handler) {}
AP4_Result ProcessSample(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out);
private:
AP4_Processor::TrackHandler* m_TrackHandler;
};
/*----------------------------------------------------------------------
| AP4_DefaultFragmentHandler::ProcessSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_DefaultFragmentHandler::ProcessSample(AP4_DataBuffer& data_in, AP4_DataBuffer& data_out)
{
if (m_TrackHandler == NULL) {
data_out.SetData(data_in.GetData(), data_in.GetDataSize());
return AP4_SUCCESS;
}
return m_TrackHandler->ProcessSample(data_in, data_out);
}
/*----------------------------------------------------------------------
| FragmentMapEntry
+---------------------------------------------------------------------*/
typedef struct {
AP4_UI64 before;
AP4_UI64 after;
} FragmentMapEntry;
/*----------------------------------------------------------------------
| FindFragmentMapEntry
+---------------------------------------------------------------------*/
static const FragmentMapEntry*
FindFragmentMapEntry(AP4_Array<FragmentMapEntry>& fragment_map, AP4_UI64 fragment_offset) {
int first = 0;
int last = fragment_map.ItemCount();
while (first < last) {
int middle = (last+first)/2;
AP4_UI64 middle_value = fragment_map[middle].before;
if (fragment_offset < middle_value) {
last = middle;
} else if (fragment_offset > middle_value) {
first = middle+1;
} else {
return &fragment_map[middle];
}
}
return NULL;
}
/*----------------------------------------------------------------------
| AP4_Processor::ProcessFragments
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::ProcessFragments(AP4_MoovAtom* moov,
AP4_List<AP4_AtomLocator>& atoms,
AP4_ContainerAtom* mfra,
AP4_SidxAtom* sidx,
AP4_Position sidx_position,
AP4_ByteStream& input,
AP4_ByteStream& output)
{
unsigned int fragment_index = 0;
AP4_Array<FragmentMapEntry> fragment_map;
for (AP4_List<AP4_AtomLocator>::Item* item = atoms.FirstItem();
item;
item = item->GetNext(), ++fragment_index) {
AP4_AtomLocator* locator = item->GetData();
AP4_Atom* atom = locator->m_Atom;
AP4_UI64 atom_offset = locator->m_Offset;
AP4_UI64 mdat_payload_offset = atom_offset+atom->GetSize()+AP4_ATOM_HEADER_SIZE;
AP4_Sample sample;
AP4_DataBuffer sample_data_in;
AP4_DataBuffer sample_data_out;
AP4_Result result;
// if this is not a moof atom, just write it back and continue
if (atom->GetType() != AP4_ATOM_TYPE_MOOF) {
result = atom->Write(output);
if (AP4_FAILED(result)) return result;
continue;
}
// parse the moof
AP4_ContainerAtom* moof = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
AP4_MovieFragment* fragment = new AP4_MovieFragment(moof);
// process all the traf atoms
AP4_Array<AP4_Processor::FragmentHandler*> handlers;
AP4_Array<AP4_FragmentSampleTable*> sample_tables;
for (;AP4_Atom* child = moof->GetChild(AP4_ATOM_TYPE_TRAF, handlers.ItemCount());) {
AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, child);
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
// find the 'trak' for this track
AP4_TrakAtom* trak = NULL;
for (AP4_List<AP4_Atom>::Item* child_item = moov->GetChildren().FirstItem();
child_item;
child_item = child_item->GetNext()) {
AP4_Atom* child_atom = child_item->GetData();
if (child_atom->GetType() == AP4_ATOM_TYPE_TRAK) {
trak = AP4_DYNAMIC_CAST(AP4_TrakAtom, child_atom);
if (trak) {
AP4_TkhdAtom* tkhd = AP4_DYNAMIC_CAST(AP4_TkhdAtom, trak->GetChild(AP4_ATOM_TYPE_TKHD));
if (tkhd && tkhd->GetTrackId() == tfhd->GetTrackId()) {
break;
}
}
trak = NULL;
}
}
// find the 'trex' for this track
AP4_ContainerAtom* mvex = NULL;
AP4_TrexAtom* trex = NULL;
mvex = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->GetChild(AP4_ATOM_TYPE_MVEX));
if (mvex) {
for (AP4_List<AP4_Atom>::Item* child_item = mvex->GetChildren().FirstItem();
child_item;
child_item = child_item->GetNext()) {
AP4_Atom* child_atom = child_item->GetData();
if (child_atom->GetType() == AP4_ATOM_TYPE_TREX) {
trex = AP4_DYNAMIC_CAST(AP4_TrexAtom, child_atom);
if (trex && trex->GetTrackId() == tfhd->GetTrackId()) {
break;
}
trex = NULL;
}
}
}
// create the handler for this traf
AP4_Processor::FragmentHandler* handler = CreateFragmentHandler(trak, trex, traf, input, atom_offset);
if (handler) {
result = handler->ProcessFragment();
if (AP4_FAILED(result)) return result;
}
handlers.Append(handler);
// create a sample table object so we can read the sample data
AP4_FragmentSampleTable* sample_table = NULL;
result = fragment->CreateSampleTable(moov, tfhd->GetTrackId(), &input, atom_offset, mdat_payload_offset, 0, sample_table);
if (AP4_FAILED(result)) return result;
sample_tables.Append(sample_table);
// let the handler look at the samples before we process them
if (handler) result = handler->PrepareForSamples(sample_table);
if (AP4_FAILED(result)) return result;
}
// write the moof
AP4_UI64 moof_out_start = 0;
output.Tell(moof_out_start);
moof->Write(output);
// remember the location of this fragment
FragmentMapEntry map_entry = {atom_offset, moof_out_start};
fragment_map.Append(map_entry);
// write an mdat header
AP4_Position mdat_out_start;
AP4_UI64 mdat_size = AP4_ATOM_HEADER_SIZE;
output.Tell(mdat_out_start);
output.WriteUI32(0);
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
// process all track runs
for (unsigned int i=0; i<handlers.ItemCount(); i++) {
AP4_Processor::FragmentHandler* handler = handlers[i];
// get the track ID
AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moof->GetChild(AP4_ATOM_TYPE_TRAF, i));
if (traf == NULL) continue;
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
// compute the base data offset
AP4_UI64 base_data_offset;
if (tfhd->GetFlags() & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {
base_data_offset = mdat_out_start+AP4_ATOM_HEADER_SIZE;
} else {
base_data_offset = moof_out_start;
}
// build a list of all trun atoms
AP4_Array<AP4_TrunAtom*> truns;
for (AP4_List<AP4_Atom>::Item* child_item = traf->GetChildren().FirstItem();
child_item;
child_item = child_item->GetNext()) {
AP4_Atom* child_atom = child_item->GetData();
if (child_atom->GetType() == AP4_ATOM_TYPE_TRUN) {
AP4_TrunAtom* trun = AP4_DYNAMIC_CAST(AP4_TrunAtom, child_atom);
truns.Append(trun);
}
}
AP4_Ordinal trun_index = 0;
AP4_Ordinal trun_sample_index = 0;
AP4_TrunAtom* trun = truns[0];
trun->SetDataOffset((AP4_SI32)((mdat_out_start+mdat_size)-base_data_offset));
// write the mdat
for (unsigned int j=0; j<sample_tables[i]->GetSampleCount(); j++, trun_sample_index++) {
// advance the trun index if necessary
if (trun_sample_index >= trun->GetEntries().ItemCount()) {
trun = truns[++trun_index];
trun->SetDataOffset((AP4_SI32)((mdat_out_start+mdat_size)-base_data_offset));
trun_sample_index = 0;
}
// get the next sample
result = sample_tables[i]->GetSample(j, sample);
if (AP4_FAILED(result)) return result;
sample.ReadData(sample_data_in);
// process the sample data
if (handler) {
result = handler->ProcessSample(sample_data_in, sample_data_out);
if (AP4_FAILED(result)) return result;
// write the sample data
result = output.Write(sample_data_out.GetData(), sample_data_out.GetDataSize());
if (AP4_FAILED(result)) return result;
// update the mdat size
mdat_size += sample_data_out.GetDataSize();
// update the trun entry
trun->UseEntries()[trun_sample_index].sample_size = sample_data_out.GetDataSize();
} else {
// write the sample data (unmodified)
result = output.Write(sample_data_in.GetData(), sample_data_in.GetDataSize());
if (AP4_FAILED(result)) return result;
// update the mdat size
mdat_size += sample_data_in.GetDataSize();
}
}
if (handler) {
// update the tfhd header
if (tfhd->GetFlags() & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {
tfhd->SetBaseDataOffset(mdat_out_start+AP4_ATOM_HEADER_SIZE);
}
if (tfhd->GetFlags() & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) {
tfhd->SetDefaultSampleSize(trun->GetEntries()[0].sample_size);
}
// give the handler a chance to update the atoms
handler->FinishFragment();
}
}
// update the mdat header
AP4_Position mdat_out_end;
output.Tell(mdat_out_end);
#if defined(AP4_DEBUG)
AP4_ASSERT(mdat_out_end-mdat_out_start == mdat_size);
#endif
output.Seek(mdat_out_start);
output.WriteUI32((AP4_UI32)mdat_size);
output.Seek(mdat_out_end);
// update the moof if needed
output.Seek(moof_out_start);
moof->Write(output);
output.Seek(mdat_out_end);
// update the sidx if we have one
if (sidx && fragment_index < sidx->GetReferences().ItemCount()) {
if (fragment_index == 0) {
sidx->SetFirstOffset(moof_out_start-(sidx_position+sidx->GetSize()));
}
AP4_LargeSize fragment_size = mdat_out_end-moof_out_start;
AP4_SidxAtom::Reference& sidx_ref = sidx->UseReferences()[fragment_index];
sidx_ref.m_ReferencedSize = (AP4_UI32)fragment_size;
}
// cleanup
delete fragment;
for (unsigned int i=0; i<handlers.ItemCount(); i++) {
delete handlers[i];
}
for (unsigned int i=0; i<sample_tables.ItemCount(); i++) {
delete sample_tables[i];
}
}
// update the mfra if we have one
if (mfra) {
for (AP4_List<AP4_Atom>::Item* mfra_item = mfra->GetChildren().FirstItem();
mfra_item;
mfra_item = mfra_item->GetNext()) {
if (mfra_item->GetData()->GetType() != AP4_ATOM_TYPE_TFRA) continue;
AP4_TfraAtom* tfra = AP4_DYNAMIC_CAST(AP4_TfraAtom, mfra_item->GetData());
if (tfra == NULL) continue;
AP4_Array<AP4_TfraAtom::Entry>& entries = tfra->GetEntries();
AP4_Cardinal entry_count = entries.ItemCount();
for (unsigned int i=0; i<entry_count; i++) {
const FragmentMapEntry* found = FindFragmentMapEntry(fragment_map, entries[i].m_MoofOffset);
if (found) {
entries[i].m_MoofOffset = found->after;
}
}
}
}
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Processor::CreateFragmentHandler
+---------------------------------------------------------------------*/
AP4_Processor::FragmentHandler*
AP4_Processor::CreateFragmentHandler(AP4_TrakAtom* /* trak */,
AP4_TrexAtom* /* trex */,
AP4_ContainerAtom* traf,
AP4_ByteStream& /* moof_data */,
AP4_Position /* moof_offset */)
{
// find the matching track handler
for (unsigned int i=0; i<m_TrackIds.ItemCount(); i++) {
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
if (tfhd && m_TrackIds[i] == tfhd->GetTrackId()) {
return new AP4_DefaultFragmentHandler(m_TrackHandlers[i]);
}
}
return NULL;
}
/*----------------------------------------------------------------------
| AP4_Processor::Process
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Process(AP4_ByteStream& input,
AP4_ByteStream& output,
AP4_ByteStream* fragments,
ProgressListener* listener,
AP4_AtomFactory& atom_factory)
{
// read all atoms.
// keep all atoms except [mdat]
// keep a ref to [moov]
// put [moof] atoms in a separate list
AP4_AtomParent top_level;
AP4_MoovAtom* moov = NULL;
AP4_ContainerAtom* mfra = NULL;
AP4_SidxAtom* sidx = NULL;
AP4_List<AP4_AtomLocator> frags;
AP4_UI64 stream_offset = 0;
bool in_fragments = false;
unsigned int sidx_count = 0;
for (AP4_Atom* atom = NULL;
AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(input, atom));
input.Tell(stream_offset)) {
if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {
delete atom;
continue;
} else if (atom->GetType() == AP4_ATOM_TYPE_MOOV) {
moov = AP4_DYNAMIC_CAST(AP4_MoovAtom, atom);
if (fragments) break;
} else if (atom->GetType() == AP4_ATOM_TYPE_MFRA) {
mfra = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
continue;
} else if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {
// don't keep the index, it is likely to be invalidated, we will recompute it later
++sidx_count;
if (sidx == NULL) {
sidx = AP4_DYNAMIC_CAST(AP4_SidxAtom, atom);
} else {
delete atom;
continue;
}
} else if (atom->GetType() == AP4_ATOM_TYPE_SSIX) {
// don't keep the index, it is likely to be invalidated
delete atom;
continue;
} else if (!fragments && (in_fragments || atom->GetType() == AP4_ATOM_TYPE_MOOF)) {
in_fragments = true;
frags.Add(new AP4_AtomLocator(atom, stream_offset));
continue;
}
top_level.AddChild(atom);
}
// check that we have at most one sidx (we can't deal with multi-sidx streams here
if (sidx_count > 1) {
top_level.RemoveChild(sidx);
delete sidx;
sidx = NULL;
}
// if we have a fragments stream, get the fragment locators from there
if (fragments) {
stream_offset = 0;
for (AP4_Atom* atom = NULL;
AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(*fragments, atom));
fragments->Tell(stream_offset)) {
if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {
delete atom;
continue;
}
frags.Add(new AP4_AtomLocator(atom, stream_offset));
}
}
// initialize the processor
AP4_Result result = Initialize(top_level, input);
if (AP4_FAILED(result)) return result;
// process the tracks if we have a moov atom
AP4_Array<AP4_SampleLocator> locators;
AP4_Cardinal track_count = 0;
AP4_List<AP4_TrakAtom>* trak_atoms = NULL;
AP4_LargeSize mdat_payload_size = 0;
AP4_SampleCursor* cursors = NULL;
if (moov) {
// build an array of track sample locators
trak_atoms = &moov->GetTrakAtoms();
track_count = trak_atoms->ItemCount();
cursors = new AP4_SampleCursor[track_count];
m_TrackHandlers.SetItemCount(track_count);
m_TrackIds.SetItemCount(track_count);
for (AP4_Ordinal i=0; i<track_count; i++) {
m_TrackHandlers[i] = NULL;
m_TrackIds[i] = 0;
}
unsigned int index = 0;
for (AP4_List<AP4_TrakAtom>::Item* item = trak_atoms->FirstItem(); item; item=item->GetNext()) {
AP4_TrakAtom* trak = item->GetData();
// find the stsd atom
AP4_ContainerAtom* stbl = AP4_DYNAMIC_CAST(AP4_ContainerAtom, trak->FindChild("mdia/minf/stbl"));
if (stbl == NULL) continue;
// see if there's an external data source for this track
AP4_ByteStream* trak_data_stream = &input;
for (AP4_List<ExternalTrackData>::Item* ditem = m_ExternalTrackData.FirstItem(); ditem; ditem=ditem->GetNext()) {
ExternalTrackData* tdata = ditem->GetData();
if (tdata->m_TrackId == trak->GetId()) {
trak_data_stream = tdata->m_MediaData;
break;
}
}
// create the track handler
m_TrackHandlers[index] = CreateTrackHandler(trak);
m_TrackIds[index] = trak->GetId();
cursors[index].m_Locator.m_TrakIndex = index;
cursors[index].m_Locator.m_SampleTable = new AP4_AtomSampleTable(stbl, *trak_data_stream);
cursors[index].m_Locator.m_SampleIndex = 0;
cursors[index].m_Locator.m_ChunkIndex = 0;
if (cursors[index].m_Locator.m_SampleTable->GetSampleCount()) {
cursors[index].m_Locator.m_SampleTable->GetSample(0, cursors[index].m_Locator.m_Sample);
} else {
cursors[index].m_EndReached = true;
}
index++;
}
// figure out the layout of the chunks
for (;;) {
// see which is the next sample to write
AP4_UI64 min_offset = (AP4_UI64)(-1);
int cursor = -1;
for (unsigned int i=0; i<track_count; i++) {
if (!cursors[i].m_EndReached &&
cursors[i].m_Locator.m_SampleTable &&
cursors[i].m_Locator.m_Sample.GetOffset() <= min_offset) {
min_offset = cursors[i].m_Locator.m_Sample.GetOffset();
cursor = i;
}
}
// stop if all cursors are exhausted
if (cursor == -1) break;
// append this locator to the layout list
AP4_SampleLocator& locator = cursors[cursor].m_Locator;
locators.Append(locator);
// move the cursor to the next sample
locator.m_SampleIndex++;
if (locator.m_SampleIndex == locator.m_SampleTable->GetSampleCount()) {
// mark this track as completed
cursors[cursor].m_EndReached = true;
} else {
// get the next sample info
locator.m_SampleTable->GetSample(locator.m_SampleIndex, locator.m_Sample);
AP4_Ordinal skip, sdesc;
locator.m_SampleTable->GetChunkForSample(locator.m_SampleIndex,
locator.m_ChunkIndex,
skip, sdesc);
}
}
// update the stbl atoms and compute the mdat size
int current_track = -1;
int current_chunk = -1;
AP4_Position current_chunk_offset = 0;
AP4_Size current_chunk_size = 0;
for (AP4_Ordinal i=0; i<locators.ItemCount(); i++) {
AP4_SampleLocator& locator = locators[i];
if ((int)locator.m_TrakIndex != current_track ||
(int)locator.m_ChunkIndex != current_chunk) {
// start a new chunk for this track
current_chunk_offset += current_chunk_size;
current_chunk_size = 0;
current_track = locator.m_TrakIndex;
current_chunk = locator.m_ChunkIndex;
locator.m_SampleTable->SetChunkOffset(locator.m_ChunkIndex, current_chunk_offset);
}
AP4_Size sample_size;
TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];
if (handler) {
sample_size = handler->GetProcessedSampleSize(locator.m_Sample);
locator.m_SampleTable->SetSampleSize(locator.m_SampleIndex, sample_size);
} else {
sample_size = locator.m_Sample.GetSize();
}
current_chunk_size += sample_size;
mdat_payload_size += sample_size;
}
// process the tracks (ex: sample descriptions processing)
for (AP4_Ordinal i=0; i<track_count; i++) {
TrackHandler* handler = m_TrackHandlers[i];
if (handler) handler->ProcessTrack();
}
}
// finalize the processor
Finalize(top_level);
if (!fragments) {
// calculate the size of all atoms combined
AP4_UI64 atoms_size = 0;
top_level.GetChildren().Apply(AP4_AtomSizeAdder(atoms_size));
// see if we need a 64-bit or 32-bit mdat
AP4_Size mdat_header_size = AP4_ATOM_HEADER_SIZE;
if (mdat_payload_size+mdat_header_size > 0xFFFFFFFF) {
// we need a 64-bit size
mdat_header_size += 8;
}
// adjust the chunk offsets
for (AP4_Ordinal i=0; i<track_count; i++) {
AP4_TrakAtom* trak;
trak_atoms->Get(i, trak);
trak->AdjustChunkOffsets(atoms_size+mdat_header_size);
}
// write all atoms
top_level.GetChildren().Apply(AP4_AtomListWriter(output));
// write mdat header
if (mdat_payload_size) {
if (mdat_header_size == AP4_ATOM_HEADER_SIZE) {
// 32-bit size
output.WriteUI32((AP4_UI32)(mdat_header_size+mdat_payload_size));
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
} else {
// 64-bit size
output.WriteUI32(1);
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
output.WriteUI64(mdat_header_size+mdat_payload_size);
}
}
}
// write the samples
if (moov) {
if (!fragments) {
#if defined(AP4_DEBUG)
AP4_Position before;
output.Tell(before);
#endif
AP4_Sample sample;
AP4_DataBuffer data_in;
AP4_DataBuffer data_out;
for (unsigned int i=0; i<locators.ItemCount(); i++) {
AP4_SampleLocator& locator = locators[i];
locator.m_Sample.ReadData(data_in);
TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];
if (handler) {
result = handler->ProcessSample(data_in, data_out);
if (AP4_FAILED(result)) return result;
output.Write(data_out.GetData(), data_out.GetDataSize());
} else {
output.Write(data_in.GetData(), data_in.GetDataSize());
}
// notify the progress listener
if (listener) {
listener->OnProgress(i+1, locators.ItemCount());
}
}
#if defined(AP4_DEBUG)
AP4_Position after;
output.Tell(after);
AP4_ASSERT(after-before == mdat_payload_size);
#endif
}
// find the position of the sidx atom
AP4_Position sidx_position = 0;
if (sidx) {
for (AP4_List<AP4_Atom>::Item* item = top_level.GetChildren().FirstItem();
item;
item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {
break;
}
sidx_position += atom->GetSize();
}
}
// process the fragments, if any
result = ProcessFragments(moov, frags, mfra, sidx, sidx_position, fragments?*fragments:input, output);
if (AP4_FAILED(result)) return result;
// update and re-write the sidx if we have one
if (sidx && sidx_position) {
AP4_Position where = 0;
output.Tell(where);
output.Seek(sidx_position);
result = sidx->Write(output);
if (AP4_FAILED(result)) return result;
output.Seek(where);
}
if (!fragments) {
// write the mfra atom at the end if we have one
if (mfra) {
mfra->Write(output);
}
}
// cleanup
for (AP4_Ordinal i=0; i<track_count; i++) {
delete cursors[i].m_Locator.m_SampleTable;
delete m_TrackHandlers[i];
}
m_TrackHandlers.Clear();
delete[] cursors;
}
// cleanup
frags.DeleteReferences();
delete mfra;
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Processor::Process
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Process(AP4_ByteStream& input,
AP4_ByteStream& output,
ProgressListener* listener,
AP4_AtomFactory& atom_factory)
{
return Process(input, output, NULL, listener, atom_factory);
}
/*----------------------------------------------------------------------
| AP4_Processor::Process
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Process(AP4_ByteStream& fragments,
AP4_ByteStream& output,
AP4_ByteStream& init,
ProgressListener* listener,
AP4_AtomFactory& atom_factory)
{
return Process(init, output, &fragments, listener, atom_factory);
}
/*----------------------------------------------------------------------
| AP4_Processor:Initialize
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Initialize(AP4_AtomParent& /* top_level */,
AP4_ByteStream& /* stream */,
ProgressListener* /* listener */)
{
// default implementation: do nothing
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Processor:Finalize
+---------------------------------------------------------------------*/
AP4_Result
AP4_Processor::Finalize(AP4_AtomParent& /* top_level */,
ProgressListener* /* listener */ )
{
// default implementation: do nothing
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Processor::TrackHandler Dynamic Cast Anchor
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR_S(AP4_Processor::TrackHandler, TrackHandler)
| ./CrossVul/dataset_final_sorted/CWE-476/cpp/good_2609_2 |
crossvul-cpp_data_good_3959_0 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2001 Jean-Fredric Clere, Nikolas Zimmermann, Georg Acher
* Mark Cave-Ayland, Carlo E Prelz, Dick Streefland
* Copyright (c) 2002, 2003 Tuukka Toivonen
* Copyright (c) 2008 Erik Andrén
*
* P/N 861037: Sensor HDCS1000 ASIC STV0600
* P/N 861050-0010: Sensor HDCS1000 ASIC STV0600
* P/N 861050-0020: Sensor Photobit PB100 ASIC STV0600-1 - QuickCam Express
* P/N 861055: Sensor ST VV6410 ASIC STV0610 - LEGO cam
* P/N 861075-0040: Sensor HDCS1000 ASIC
* P/N 961179-0700: Sensor ST VV6410 ASIC STV0602 - Dexxa WebCam USB
* P/N 861040-0000: Sensor ST VV6410 ASIC STV0610 - QuickCam Web
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/input.h>
#include "stv06xx_sensor.h"
MODULE_AUTHOR("Erik Andrén");
MODULE_DESCRIPTION("STV06XX USB Camera Driver");
MODULE_LICENSE("GPL");
static bool dump_bridge;
static bool dump_sensor;
int stv06xx_write_bridge(struct sd *sd, u16 address, u16 i2c_data)
{
int err;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
u8 len = (i2c_data > 0xff) ? 2 : 1;
buf[0] = i2c_data & 0xff;
buf[1] = (i2c_data >> 8) & 0xff;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, address, 0, buf, len,
STV06XX_URB_MSG_TIMEOUT);
gspca_dbg(gspca_dev, D_CONF, "Written 0x%x to address 0x%x, status: %d\n",
i2c_data, address, err);
return (err < 0) ? err : 0;
}
int stv06xx_read_bridge(struct sd *sd, u16 address, u8 *i2c_data)
{
int err;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
err = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
0x04, 0xc0, address, 0, buf, 1,
STV06XX_URB_MSG_TIMEOUT);
*i2c_data = buf[0];
gspca_dbg(gspca_dev, D_CONF, "Reading 0x%x from address 0x%x, status %d\n",
*i2c_data, address, err);
return (err < 0) ? err : 0;
}
/* Wraps the normal write sensor bytes / words functions for writing a
single value */
int stv06xx_write_sensor(struct sd *sd, u8 address, u16 value)
{
if (sd->sensor->i2c_len == 2) {
u16 data[2] = { address, value };
return stv06xx_write_sensor_words(sd, data, 1);
} else {
u8 data[2] = { address, value };
return stv06xx_write_sensor_bytes(sd, data, 1);
}
}
static int stv06xx_write_sensor_finish(struct sd *sd)
{
int err = 0;
if (sd->bridge == BRIDGE_STV610) {
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
buf[0] = 0;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, 0x1704, 0, buf, 1,
STV06XX_URB_MSG_TIMEOUT);
}
return (err < 0) ? err : 0;
}
int stv06xx_write_sensor_bytes(struct sd *sd, const u8 *data, u8 len)
{
int err, i, j;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
gspca_dbg(gspca_dev, D_CONF, "I2C: Command buffer contains %d entries\n",
len);
for (i = 0; i < len;) {
/* Build the command buffer */
memset(buf, 0, I2C_BUFFER_LENGTH);
for (j = 0; j < I2C_MAX_BYTES && i < len; j++, i++) {
buf[j] = data[2*i];
buf[0x10 + j] = data[2*i+1];
gspca_dbg(gspca_dev, D_CONF, "I2C: Writing 0x%02x to reg 0x%02x\n",
data[2*i+1], data[2*i]);
}
buf[0x20] = sd->sensor->i2c_addr;
buf[0x21] = j - 1; /* Number of commands to send - 1 */
buf[0x22] = I2C_WRITE_CMD;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, 0x0400, 0, buf,
I2C_BUFFER_LENGTH,
STV06XX_URB_MSG_TIMEOUT);
if (err < 0)
return err;
}
return stv06xx_write_sensor_finish(sd);
}
int stv06xx_write_sensor_words(struct sd *sd, const u16 *data, u8 len)
{
int err, i, j;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
gspca_dbg(gspca_dev, D_CONF, "I2C: Command buffer contains %d entries\n",
len);
for (i = 0; i < len;) {
/* Build the command buffer */
memset(buf, 0, I2C_BUFFER_LENGTH);
for (j = 0; j < I2C_MAX_WORDS && i < len; j++, i++) {
buf[j] = data[2*i];
buf[0x10 + j * 2] = data[2*i+1];
buf[0x10 + j * 2 + 1] = data[2*i+1] >> 8;
gspca_dbg(gspca_dev, D_CONF, "I2C: Writing 0x%04x to reg 0x%02x\n",
data[2*i+1], data[2*i]);
}
buf[0x20] = sd->sensor->i2c_addr;
buf[0x21] = j - 1; /* Number of commands to send - 1 */
buf[0x22] = I2C_WRITE_CMD;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, 0x0400, 0, buf,
I2C_BUFFER_LENGTH,
STV06XX_URB_MSG_TIMEOUT);
if (err < 0)
return err;
}
return stv06xx_write_sensor_finish(sd);
}
int stv06xx_read_sensor(struct sd *sd, const u8 address, u16 *value)
{
int err;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
err = stv06xx_write_bridge(sd, STV_I2C_FLUSH, sd->sensor->i2c_flush);
if (err < 0)
return err;
/* Clear mem */
memset(buf, 0, I2C_BUFFER_LENGTH);
buf[0] = address;
buf[0x20] = sd->sensor->i2c_addr;
buf[0x21] = 0;
/* Read I2C register */
buf[0x22] = I2C_READ_CMD;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, 0x1400, 0, buf, I2C_BUFFER_LENGTH,
STV06XX_URB_MSG_TIMEOUT);
if (err < 0) {
pr_err("I2C: Read error writing address: %d\n", err);
return err;
}
err = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
0x04, 0xc0, 0x1410, 0, buf, sd->sensor->i2c_len,
STV06XX_URB_MSG_TIMEOUT);
if (sd->sensor->i2c_len == 2)
*value = buf[0] | (buf[1] << 8);
else
*value = buf[0];
gspca_dbg(gspca_dev, D_CONF, "I2C: Read 0x%x from address 0x%x, status: %d\n",
*value, address, err);
return (err < 0) ? err : 0;
}
/* Dumps all bridge registers */
static void stv06xx_dump_bridge(struct sd *sd)
{
int i;
u8 data, buf;
pr_info("Dumping all stv06xx bridge registers\n");
for (i = 0x1400; i < 0x160f; i++) {
stv06xx_read_bridge(sd, i, &data);
pr_info("Read 0x%x from address 0x%x\n", data, i);
}
pr_info("Testing stv06xx bridge registers for writability\n");
for (i = 0x1400; i < 0x160f; i++) {
stv06xx_read_bridge(sd, i, &data);
buf = data;
stv06xx_write_bridge(sd, i, 0xff);
stv06xx_read_bridge(sd, i, &data);
if (data == 0xff)
pr_info("Register 0x%x is read/write\n", i);
else if (data != buf)
pr_info("Register 0x%x is read/write, but only partially\n",
i);
else
pr_info("Register 0x%x is read-only\n", i);
stv06xx_write_bridge(sd, i, buf);
}
}
/* this function is called at probe and resume time */
static int stv06xx_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int err;
gspca_dbg(gspca_dev, D_PROBE, "Initializing camera\n");
/* Let the usb init settle for a bit
before performing the initialization */
msleep(250);
err = sd->sensor->init(sd);
if (dump_sensor && sd->sensor->dump)
sd->sensor->dump(sd);
return (err < 0) ? err : 0;
}
/* this function is called at probe time */
static int stv06xx_init_controls(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dbg(gspca_dev, D_PROBE, "Initializing controls\n");
gspca_dev->vdev.ctrl_handler = &gspca_dev->ctrl_handler;
return sd->sensor->init_controls(sd);
}
/* Start the camera */
static int stv06xx_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
struct usb_host_interface *alt;
struct usb_interface *intf;
int err, packet_size;
intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);
alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);
if (!alt) {
gspca_err(gspca_dev, "Couldn't get altsetting\n");
return -EIO;
}
if (alt->desc.bNumEndpoints < 1)
return -ENODEV;
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
err = stv06xx_write_bridge(sd, STV_ISO_SIZE_L, packet_size);
if (err < 0)
return err;
/* Prepare the sensor for start */
err = sd->sensor->start(sd);
if (err < 0)
goto out;
/* Start isochronous streaming */
err = stv06xx_write_bridge(sd, STV_ISO_ENABLE, 1);
out:
if (err < 0)
gspca_dbg(gspca_dev, D_STREAM, "Starting stream failed\n");
else
gspca_dbg(gspca_dev, D_STREAM, "Started streaming\n");
return (err < 0) ? err : 0;
}
static int stv06xx_isoc_init(struct gspca_dev *gspca_dev)
{
struct usb_interface_cache *intfc;
struct usb_host_interface *alt;
struct sd *sd = (struct sd *) gspca_dev;
intfc = gspca_dev->dev->actconfig->intf_cache[0];
if (intfc->num_altsetting < 2)
return -ENODEV;
alt = &intfc->altsetting[1];
if (alt->desc.bNumEndpoints < 1)
return -ENODEV;
/* Start isoc bandwidth "negotiation" at max isoc bandwidth */
alt->endpoint[0].desc.wMaxPacketSize =
cpu_to_le16(sd->sensor->max_packet_size[gspca_dev->curr_mode]);
return 0;
}
static int stv06xx_isoc_nego(struct gspca_dev *gspca_dev)
{
int ret, packet_size, min_packet_size;
struct usb_host_interface *alt;
struct sd *sd = (struct sd *) gspca_dev;
/*
* Existence of altsetting and endpoint was verified in
* stv06xx_isoc_init()
*/
alt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
min_packet_size = sd->sensor->min_packet_size[gspca_dev->curr_mode];
if (packet_size <= min_packet_size)
return -EIO;
packet_size -= 100;
if (packet_size < min_packet_size)
packet_size = min_packet_size;
alt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(packet_size);
ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 1);
if (ret < 0)
gspca_err(gspca_dev, "set alt 1 err %d\n", ret);
return ret;
}
static void stv06xx_stopN(struct gspca_dev *gspca_dev)
{
int err;
struct sd *sd = (struct sd *) gspca_dev;
/* stop ISO-streaming */
err = stv06xx_write_bridge(sd, STV_ISO_ENABLE, 0);
if (err < 0)
goto out;
err = sd->sensor->stop(sd);
out:
if (err < 0)
gspca_dbg(gspca_dev, D_STREAM, "Failed to stop stream\n");
else
gspca_dbg(gspca_dev, D_STREAM, "Stopped streaming\n");
}
/*
* Analyse an USB packet of the data stream and store it appropriately.
* Each packet contains an integral number of chunks. Each chunk has
* 2-bytes identification, followed by 2-bytes that describe the chunk
* length. Known/guessed chunk identifications are:
* 8001/8005/C001/C005 - Begin new frame
* 8002/8006/C002/C006 - End frame
* 0200/4200 - Contains actual image data, bayer or compressed
* 0005 - 11 bytes of unknown data
* 0100 - 2 bytes of unknown data
* The 0005 and 0100 chunks seem to appear only in compressed stream.
*/
static void stv06xx_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* isoc packet */
int len) /* iso packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dbg(gspca_dev, D_PACK, "Packet of length %d arrived\n", len);
/* A packet may contain several frames
loop until the whole packet is reached */
while (len) {
int id, chunk_len;
if (len < 4) {
gspca_dbg(gspca_dev, D_PACK, "Packet is smaller than 4 bytes\n");
return;
}
/* Capture the id */
id = (data[0] << 8) | data[1];
/* Capture the chunk length */
chunk_len = (data[2] << 8) | data[3];
gspca_dbg(gspca_dev, D_PACK, "Chunk id: %x, length: %d\n",
id, chunk_len);
data += 4;
len -= 4;
if (len < chunk_len) {
gspca_err(gspca_dev, "URB packet length is smaller than the specified chunk length\n");
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
}
/* First byte seem to be 02=data 2nd byte is unknown??? */
if (sd->bridge == BRIDGE_ST6422 && (id & 0xff00) == 0x0200)
goto frame_data;
switch (id) {
case 0x0200:
case 0x4200:
frame_data:
gspca_dbg(gspca_dev, D_PACK, "Frame data packet detected\n");
if (sd->to_skip) {
int skip = (sd->to_skip < chunk_len) ?
sd->to_skip : chunk_len;
data += skip;
len -= skip;
chunk_len -= skip;
sd->to_skip -= skip;
}
gspca_frame_add(gspca_dev, INTER_PACKET,
data, chunk_len);
break;
case 0x8001:
case 0x8005:
case 0xc001:
case 0xc005:
gspca_dbg(gspca_dev, D_PACK, "Starting new frame\n");
/* Create a new frame, chunk length should be zero */
gspca_frame_add(gspca_dev, FIRST_PACKET,
NULL, 0);
if (sd->bridge == BRIDGE_ST6422)
sd->to_skip = gspca_dev->pixfmt.width * 4;
if (chunk_len)
gspca_err(gspca_dev, "Chunk length is non-zero on a SOF\n");
break;
case 0x8002:
case 0x8006:
case 0xc002:
gspca_dbg(gspca_dev, D_PACK, "End of frame detected\n");
/* Complete the last frame (if any) */
gspca_frame_add(gspca_dev, LAST_PACKET,
NULL, 0);
if (chunk_len)
gspca_err(gspca_dev, "Chunk length is non-zero on a EOF\n");
break;
case 0x0005:
gspca_dbg(gspca_dev, D_PACK, "Chunk 0x005 detected\n");
/* Unknown chunk with 11 bytes of data,
occurs just before end of each frame
in compressed mode */
break;
case 0x0100:
gspca_dbg(gspca_dev, D_PACK, "Chunk 0x0100 detected\n");
/* Unknown chunk with 2 bytes of data,
occurs 2-3 times per USB interrupt */
break;
case 0x42ff:
gspca_dbg(gspca_dev, D_PACK, "Chunk 0x42ff detected\n");
/* Special chunk seen sometimes on the ST6422 */
break;
default:
gspca_dbg(gspca_dev, D_PACK, "Unknown chunk 0x%04x detected\n",
id);
/* Unknown chunk */
}
data += chunk_len;
len -= chunk_len;
}
}
#if IS_ENABLED(CONFIG_INPUT)
static int sd_int_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* interrupt packet data */
int len) /* interrupt packet length */
{
int ret = -EINVAL;
if (len == 1 && (data[0] == 0x80 || data[0] == 0x10)) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 1);
input_sync(gspca_dev->input_dev);
ret = 0;
}
if (len == 1 && (data[0] == 0x88 || data[0] == 0x11)) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
ret = 0;
}
return ret;
}
#endif
static int stv06xx_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id);
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.config = stv06xx_config,
.init = stv06xx_init,
.init_controls = stv06xx_init_controls,
.start = stv06xx_start,
.stopN = stv06xx_stopN,
.pkt_scan = stv06xx_pkt_scan,
.isoc_init = stv06xx_isoc_init,
.isoc_nego = stv06xx_isoc_nego,
#if IS_ENABLED(CONFIG_INPUT)
.int_pkt_scan = sd_int_pkt_scan,
#endif
};
/* This function is called at probe time */
static int stv06xx_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dbg(gspca_dev, D_PROBE, "Configuring camera\n");
sd->bridge = id->driver_info;
gspca_dev->sd_desc = &sd_desc;
if (dump_bridge)
stv06xx_dump_bridge(sd);
sd->sensor = &stv06xx_sensor_st6422;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = &stv06xx_sensor_vv6410;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = &stv06xx_sensor_hdcs1x00;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = &stv06xx_sensor_hdcs1020;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = &stv06xx_sensor_pb0100;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = NULL;
return -ENODEV;
}
/* -- module initialisation -- */
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x046d, 0x0840), .driver_info = BRIDGE_STV600 }, /* QuickCam Express */
{USB_DEVICE(0x046d, 0x0850), .driver_info = BRIDGE_STV610 }, /* LEGO cam / QuickCam Web */
{USB_DEVICE(0x046d, 0x0870), .driver_info = BRIDGE_STV602 }, /* Dexxa WebCam USB */
{USB_DEVICE(0x046D, 0x08F0), .driver_info = BRIDGE_ST6422 }, /* QuickCam Messenger */
{USB_DEVICE(0x046D, 0x08F5), .driver_info = BRIDGE_ST6422 }, /* QuickCam Communicate */
{USB_DEVICE(0x046D, 0x08F6), .driver_info = BRIDGE_ST6422 }, /* QuickCam Messenger (new) */
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd),
THIS_MODULE);
}
static void sd_disconnect(struct usb_interface *intf)
{
struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
struct sd *sd = (struct sd *) gspca_dev;
void *priv = sd->sensor_priv;
gspca_dbg(gspca_dev, D_PROBE, "Disconnecting the stv06xx device\n");
sd->sensor = NULL;
gspca_disconnect(intf);
kfree(priv);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = sd_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
module_param(dump_bridge, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(dump_bridge, "Dumps all usb bridge registers at startup");
module_param(dump_sensor, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(dump_sensor, "Dumps all sensor registers at startup");
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3959_0 |
crossvul-cpp_data_good_5108_0 | /* packet-u3v.c
* Routines for AIA USB3 Vision (TM) Protocol dissection
* Copyright 2016, AIA (www.visiononline.org)
*
* USB3 Vision (TM): USB3 Vision a standard developed under the sponsorship of
* the AIA for the benefit of the machine vision industry.
* U3V stands for USB3 Vision (TM) Protocol.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 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/proto_data.h>
#include <epan/dissectors/packet-usb.h>
/*
U3V descriptor constants
*/
#define DESCRIPTOR_TYPE_U3V_INTERFACE 0x24
#define DESCRIPTOR_SUBTYPE_U3V_DEVICE_INFO 0x01
/*
Bootstrap registers addresses
*/
#define U3V_ABRM_GENCP_VERSION 0x00000000
#define U3V_ABRM_MANUFACTURER_NAME 0x00000004
#define U3V_ABRM_MODEL_NAME 0x00000044
#define U3V_ABRM_FAMILY_NAME 0x00000084
#define U3V_ABRM_DEVICE_VERSION 0x000000C4
#define U3V_ABRM_MANUFACTURER_INFO 0x00000104
#define U3V_ABRM_SERIAL_NUMBER 0x00000144
#define U3V_ABRM_USER_DEFINED_NAME 0x00000184
#define U3V_ABRM_DEVICE_CAPABILITY 0x000001C4
#define U3V_ABRM_MAXIMUM_DEVICE_RESPONSE_TIME 0x000001CC
#define U3V_ABRM_MANIFEST_TABLE_ADDRESS 0x000001D0
#define U3V_ABRM_SBRM_ADDRESS 0x000001D8
#define U3V_ABRM_DEVICE_CONFIGURATION 0x000001E0
#define U3V_ABRM_HEARTBEAT_TIMEOUT 0x000001E8
#define U3V_ABRM_MESSAGE_CHANNEL_CHANNEL_ID 0x000001EC
#define U3V_ABRM_TIMESTAMP 0x000001F0
#define U3V_ABRM_TIMESTAMP_LATCH 0x000001F8
#define U3V_ABRM_TIMESTAMP_INCREMENT 0x000001FC
#define U3V_ABRM_ACCESS_PRIVILEGE 0x00000204
#define U3V_ABRM_PROTOCOL_ENDIANESS 0x00000208
#define U3V_ABRM_IMPLEMENTATION_ENDIANESS 0x0000020C
#define U3V_SBRM_U3V_VERSION 0x00000000
#define U3V_SBRM_U3VCP_CAPABILITY_REGISTER 0x00000004
#define U3V_SBRM_U3VCP_CONFIGURATION_REGISTER 0x0000000C
#define U3V_SBRM_MAXIMUM_COMMAND_TRANSFER_LENGTH 0x00000014
#define U3V_SBRM_MAXIMUM_ACKNOWLEDGE_TRANSFER_LENGTH 0x00000018
#define U3V_SBRM_NUMBER_OF_STREAM_CHANNELS 0x0000001C
#define U3V_SBRM_SIRM_ADDRESS 0x00000020
#define U3V_SBRM_SIRM_LENGTH 0x00000028
#define U3V_SBRM_EIRM_ADDRESS 0x0000002C
#define U3V_SBRM_EIRM_LENGTH 0x00000034
#define U3V_SBRM_IIDC2_ADDRESS 0x00000038
#define U3V_SBRM_CURRENT_SPEED 0x00000040
#define U3V_SIRM_SI_INFO 0x00000000
#define U3V_SIRM_SI_CONTROL 0x00000004
#define U3V_SIRM_SI_REQUIRED_PAYLOAD_SIZE 0x00000008
#define U3V_SIRM_SI_REQUIRED_LEADER_SIZE 0x00000010
#define U3V_SIRM_SI_REQUIRED_TRAILER_SIZE 0x00000014
#define U3V_SIRM_SI_MAXIMUM_LEADER_SIZE 0x00000018
#define U3V_SIRM_SI_PAYLOAD_TRANSFER_SIZE 0x0000001C
#define U3V_SIRM_SI_PAYLOAD_TRANSFER_COUNT 0x00000020
#define U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER1_SIZE 0x00000024
#define U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER2_SIZE 0x00000028
#define U3V_SIRM_SI_MAXIMUM_TRAILER_SIZE 0x0000002C
#define U3V_EIRM_EI_CONTROL 0x00000000
#define U3V_EIRM_MAXIMUM_EVENT_TRANSFER_LENGTH 0x00000004
#define U3V_EIRM_EVENT_TEST_CONTROL 0x00000008
/*
Command and acknowledge IDs
*/
#define U3V_READMEM_CMD 0x0800
#define U3V_READMEM_ACK 0x0801
#define U3V_WRITEMEM_CMD 0x0802
#define U3V_WRITEMEM_ACK 0x0803
#define U3V_PENDING_ACK 0x0805
#define U3V_EVENT_CMD 0x0C00
#define U3V_EVENT_ACK 0x0C01
/*
Status codes
*/
#define U3V_STATUS_GENCP_SUCCESS 0x0000
#define U3V_STATUS_GENCP_NOT_IMPLEMENTED 0x8001
#define U3V_STATUS_GENCP_INVALID_PARAMETER 0x8002
#define U3V_STATUS_GENCP_INVALID_ADDRESS 0x8003
#define U3V_STATUS_GENCP_WRITE_PROTECT 0x8004
#define U3V_STATUS_GENCP_BAD_ALIGNMENT 0x8005
#define U3V_STATUS_GENCP_ACCESS_DENIED 0x8006
#define U3V_STATUS_GENCP_BUSY 0x8007
/* 0x8008 - 0x800A have been used in GEV 1.x but are now deprecated. The GenCP specification did NOT recycle these values! */
#define U3V_STATUS_GENCP_MSG_TIMEOUT 0x800B
/* 0x800C - 0x800D are used in GEV only. The GenCP specification did NOT recycle these values! */
#define U3V_STATUS_GENCP_INVALID_HEADER 0x800E
#define U3V_STATUS_GENCP_WRONG_CONFIG 0x800F
#define U3V_STATUS_GENCP_ERROR 0x8FFF
#define U3V_STATUS_RESEND_NOT_SUPPORTED 0xA001
#define U3V_STATUS_DSI_ENDPOINT_HALTED 0xA002
#define U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED 0xA003
#define U3V_STATUS_SI_REGISTERS_INCONSISTENT 0xA004
#define U3V_STATUS_DATA_DISCARDED 0xA100
/*
Prefix
*/
#define U3V_CONTROL_PREFIX 0x43563355
#define U3V_EVENT_PREFIX 0x45563355
#define U3V_STREAM_LEADER_PREFIX 0x4C563355
#define U3V_STREAM_TRAILER_PREFIX 0x54563355
/*
Event IDs
*/
#define U3V_EVENT_TESTEVENT 0x4FFF
/*
* Pixel Format IDs
*/
#define PFNC_U3V_MONO1P 0x01010037
#define PFNC_U3V_CONFIDENCE1P 0x010100C5
#define PFNC_U3V_MONO2P 0x01020038
#define PFNC_U3V_MONO4P 0x01040039
#define PFNC_U3V_MONO8 0x01080001
#define PFNC_U3V_MONO8S 0x01080002
#define PFNC_U3V_BAYERGR8 0x01080008
#define PFNC_U3V_BAYERRG8 0x01080009
#define PFNC_U3V_BAYERGB8 0x0108000A
#define PFNC_U3V_BAYERBG8 0x0108000B
#define PFNC_U3V_SCF1WBWG8 0x01080067
#define PFNC_U3V_SCF1WGWB8 0x0108006E
#define PFNC_U3V_SCF1WGWR8 0x01080075
#define PFNC_U3V_SCF1WRWG8 0x0108007C
#define PFNC_U3V_COORD3D_A8 0x010800AF
#define PFNC_U3V_COORD3D_B8 0x010800B0
#define PFNC_U3V_COORD3D_C8 0x010800B1
#define PFNC_U3V_CONFIDENCE1 0x010800C4
#define PFNC_U3V_CONFIDENCE8 0x010800C6
#define PFNC_U3V_R8 0x010800C9
#define PFNC_U3V_G8 0x010800CD
#define PFNC_U3V_B8 0x010800D1
#define PFNC_U3V_MONO10P 0x010A0046
#define PFNC_U3V_BAYERBG10P 0x010A0052
#define PFNC_U3V_BAYERGB10P 0x010A0054
#define PFNC_U3V_BAYERGR10P 0x010A0056
#define PFNC_U3V_BAYERRG10P 0x010A0058
#define PFNC_U3V_SCF1WBWG10P 0x010A0069
#define PFNC_U3V_SCF1WGWB10P 0x010A0070
#define PFNC_U3V_SCF1WGWR10P 0x010A0077
#define PFNC_U3V_SCF1WRWG10P 0x010A007E
#define PFNC_U3V_R10 0x010A00CA
#define PFNC_U3V_G10 0x010A00CE
#define PFNC_U3V_B10 0x010A00D2
#define PFNC_U3V_COORD3D_A10P 0x010A00D5
#define PFNC_U3V_COORD3D_B10P 0x010A00D6
#define PFNC_U3V_COORD3D_C10P 0x010A00D7
#define PFNC_U3V_MONO10PACKED 0x010C0004
#define PFNC_U3V_MONO12PACKED 0x010C0006
#define PFNC_U3V_BAYERGR10PACKED 0x010C0026
#define PFNC_U3V_BAYERRG10PACKED 0x010C0027
#define PFNC_U3V_BAYERGB10PACKED 0x010C0028
#define PFNC_U3V_BAYERBG10PACKED 0x010C0029
#define PFNC_U3V_BAYERGR12PACKED 0x010C002A
#define PFNC_U3V_BAYERRG12PACKED 0x010C002B
#define PFNC_U3V_BAYERGB12PACKED 0x010C002C
#define PFNC_U3V_BAYERBG12PACKED 0x010C002D
#define PFNC_U3V_MONO12P 0x010C0047
#define PFNC_U3V_BAYERBG12P 0x010C0053
#define PFNC_U3V_BAYERGB12P 0x010C0055
#define PFNC_U3V_BAYERGR12P 0x010C0057
#define PFNC_U3V_BAYERRG12P 0x010C0059
#define PFNC_U3V_SCF1WBWG12P 0x010C006B
#define PFNC_U3V_SCF1WGWB12P 0x010C0072
#define PFNC_U3V_SCF1WGWR12P 0x010C0079
#define PFNC_U3V_SCF1WRWG12P 0x010C0080
#define PFNC_U3V_R12 0x010C00CB
#define PFNC_U3V_G12 0x010C00CF
#define PFNC_U3V_B12 0x010C00D3
#define PFNC_U3V_COORD3D_A12P 0x010C00D8
#define PFNC_U3V_COORD3D_B12P 0x010C00D9
#define PFNC_U3V_COORD3D_C12P 0x010C00DA
#define PFNC_U3V_MONO10 0x01100003
#define PFNC_U3V_MONO12 0x01100005
#define PFNC_U3V_MONO16 0x01100007
#define PFNC_U3V_BAYERGR10 0x0110000C
#define PFNC_U3V_BAYERRG10 0x0110000D
#define PFNC_U3V_BAYERGB10 0x0110000E
#define PFNC_U3V_BAYERBG10 0x0110000F
#define PFNC_U3V_BAYERGR12 0x01100010
#define PFNC_U3V_BAYERRG12 0x01100011
#define PFNC_U3V_BAYERGB12 0x01100012
#define PFNC_U3V_BAYERBG12 0x01100013
#define PFNC_U3V_MONO14 0x01100025
#define PFNC_U3V_BAYERGR16 0x0110002E
#define PFNC_U3V_BAYERRG16 0x0110002F
#define PFNC_U3V_BAYERGB16 0x01100030
#define PFNC_U3V_BAYERBG16 0x01100031
#define PFNC_U3V_SCF1WBWG10 0x01100068
#define PFNC_U3V_SCF1WBWG12 0x0110006A
#define PFNC_U3V_SCF1WBWG14 0x0110006C
#define PFNC_U3V_SCF1WBWG16 0x0110006D
#define PFNC_U3V_SCF1WGWB10 0x0110006F
#define PFNC_U3V_SCF1WGWB12 0x01100071
#define PFNC_U3V_SCF1WGWB14 0x01100073
#define PFNC_U3V_SCF1WGWB16 0x01100074
#define PFNC_U3V_SCF1WGWR10 0x01100076
#define PFNC_U3V_SCF1WGWR12 0x01100078
#define PFNC_U3V_SCF1WGWR14 0x0110007A
#define PFNC_U3V_SCF1WGWR16 0x0110007B
#define PFNC_U3V_SCF1WRWG10 0x0110007D
#define PFNC_U3V_SCF1WRWG12 0x0110007F
#define PFNC_U3V_SCF1WRWG14 0x01100081
#define PFNC_U3V_SCF1WRWG16 0x01100082
#define PFNC_U3V_COORD3D_A16 0x011000B6
#define PFNC_U3V_COORD3D_B16 0x011000B7
#define PFNC_U3V_COORD3D_C16 0x011000B8
#define PFNC_U3V_CONFIDENCE16 0x011000C7
#define PFNC_U3V_R16 0x011000CC
#define PFNC_U3V_G16 0x011000D0
#define PFNC_U3V_B16 0x011000D4
#define PFNC_U3V_COORD3D_A32F 0x012000BD
#define PFNC_U3V_COORD3D_B32F 0x012000BE
#define PFNC_U3V_COORD3D_C32F 0x012000BF
#define PFNC_U3V_CONFIDENCE32F 0x012000C8
#define PFNC_U3V_YUV411_8_UYYVYY 0x020C001E
#define PFNC_U3V_YCBCR411_8_CBYYCRYY 0x020C003C
#define PFNC_U3V_YCBCR601_411_8_CBYYCRYY 0x020C003F
#define PFNC_U3V_YCBCR709_411_8_CBYYCRYY 0x020C0042
#define PFNC_U3V_YCBCR411_8 0x020C005A
#define PFNC_U3V_YUV422_8_UYVY 0x0210001F
#define PFNC_U3V_YUV422_8 0x02100032
#define PFNC_U3V_RGB565P 0x02100035
#define PFNC_U3V_BGR565P 0x02100036
#define PFNC_U3V_YCBCR422_8 0x0210003B
#define PFNC_U3V_YCBCR601_422_8 0x0210003E
#define PFNC_U3V_YCBCR709_422_8 0x02100041
#define PFNC_U3V_YCBCR422_8_CBYCRY 0x02100043
#define PFNC_U3V_YCBCR601_422_8_CBYCRY 0x02100044
#define PFNC_U3V_YCBCR709_422_8_CBYCRY 0x02100045
#define PFNC_U3V_BICOLORRGBG8 0x021000A5
#define PFNC_U3V_BICOLORBGRG8 0x021000A6
#define PFNC_U3V_COORD3D_AC8 0x021000B4
#define PFNC_U3V_COORD3D_AC8_PLANAR 0x021000B5
#define PFNC_U3V_YCBCR422_10P 0x02140087
#define PFNC_U3V_YCBCR601_422_10P 0x0214008E
#define PFNC_U3V_YCBCR709_422_10P 0x02140096
#define PFNC_U3V_YCBCR422_10P_CBYCRY 0x0214009A
#define PFNC_U3V_YCBCR601_422_10P_CBYCRY 0x0214009E
#define PFNC_U3V_YCBCR709_422_10P_CBYCRY 0x021400A2
#define PFNC_U3V_BICOLORRGBG10P 0x021400A8
#define PFNC_U3V_BICOLORBGRG10P 0x021400AA
#define PFNC_U3V_COORD3D_AC10P 0x021400F0
#define PFNC_U3V_COORD3D_AC10P_PLANAR 0x021400F1
#define PFNC_U3V_RGB8 0x02180014
#define PFNC_U3V_BGR8 0x02180015
#define PFNC_U3V_YUV8_UYV 0x02180020
#define PFNC_U3V_RGB8_PLANAR 0x02180021
#define PFNC_U3V_YCBCR8_CBYCR 0x0218003A
#define PFNC_U3V_YCBCR601_8_CBYCR 0x0218003D
#define PFNC_U3V_YCBCR709_8_CBYCR 0x02180040
#define PFNC_U3V_YCBCR8 0x0218005B
#define PFNC_U3V_YCBCR422_12P 0x02180088
#define PFNC_U3V_YCBCR601_422_12P 0x02180090
#define PFNC_U3V_YCBCR709_422_12P 0x02180098
#define PFNC_U3V_YCBCR422_12P_CBYCRY 0x0218009C
#define PFNC_U3V_YCBCR601_422_12P_CBYCRY 0x021800A0
#define PFNC_U3V_YCBCR709_422_12P_CBYCRY 0x021800A4
#define PFNC_U3V_BICOLORRGBG12P 0x021800AC
#define PFNC_U3V_BICOLORBGRG12P 0x021800AE
#define PFNC_U3V_COORD3D_ABC8 0x021800B2
#define PFNC_U3V_COORD3D_ABC8_PLANAR 0x021800B3
#define PFNC_U3V_COORD3D_AC12P 0x021800F2
#define PFNC_U3V_COORD3D_AC12P_PLANAR 0x021800F3
#define PFNC_U3V_BGR10P 0x021E0048
#define PFNC_U3V_RGB10P 0x021E005C
#define PFNC_U3V_YCBCR10P_CBYCR 0x021E0084
#define PFNC_U3V_YCBCR601_10P_CBYCR 0x021E008A
#define PFNC_U3V_YCBCR709_10P_CBYCR 0x021E0092
#define PFNC_U3V_COORD3D_ABC10P 0x021E00DB
#define PFNC_U3V_COORD3D_ABC10P_PLANAR 0x021E00DC
#define PFNC_U3V_RGBA8 0x02200016
#define PFNC_U3V_BGRA8 0x02200017
#define PFNC_U3V_RGB10V1PACKED 0x0220001C
#define PFNC_U3V_RGB10P32 0x0220001D
#define PFNC_U3V_YCBCR422_10 0x02200065
#define PFNC_U3V_YCBCR422_12 0x02200066
#define PFNC_U3V_YCBCR601_422_10 0x0220008D
#define PFNC_U3V_YCBCR601_422_12 0x0220008F
#define PFNC_U3V_YCBCR709_422_10 0x02200095
#define PFNC_U3V_YCBCR709_422_12 0x02200097
#define PFNC_U3V_YCBCR422_10_CBYCRY 0x02200099
#define PFNC_U3V_YCBCR422_12_CBYCRY 0x0220009B
#define PFNC_U3V_YCBCR601_422_10_CBYCRY 0x0220009D
#define PFNC_U3V_YCBCR601_422_12_CBYCRY 0x0220009F
#define PFNC_U3V_YCBCR709_422_10_CBYCRY 0x022000A1
#define PFNC_U3V_YCBCR709_422_12_CBYCRY 0x022000A3
#define PFNC_U3V_BICOLORRGBG10 0x022000A7
#define PFNC_U3V_BICOLORBGRG10 0x022000A9
#define PFNC_U3V_BICOLORRGBG12 0x022000AB
#define PFNC_U3V_BICOLORBGRG12 0x022000AD
#define PFNC_U3V_COORD3D_AC16 0x022000BB
#define PFNC_U3V_COORD3D_AC16_PLANAR 0x022000BC
#define PFNC_U3V_RGB12V1PACKED 0x02240034
#define PFNC_U3V_BGR12P 0x02240049
#define PFNC_U3V_RGB12P 0x0224005D
#define PFNC_U3V_YCBCR12P_CBYCR 0x02240086
#define PFNC_U3V_YCBCR601_12P_CBYCR 0x0224008C
#define PFNC_U3V_YCBCR709_12P_CBYCR 0x02240094
#define PFNC_U3V_COORD3D_ABC12P 0x022400DE
#define PFNC_U3V_COORD3D_ABC12P_PLANAR 0x022400DF
#define PFNC_U3V_BGRA10P 0x0228004D
#define PFNC_U3V_RGBA10P 0x02280060
#define PFNC_U3V_RGB10 0x02300018
#define PFNC_U3V_BGR10 0x02300019
#define PFNC_U3V_RGB12 0x0230001A
#define PFNC_U3V_BGR12 0x0230001B
#define PFNC_U3V_RGB10_PLANAR 0x02300022
#define PFNC_U3V_RGB12_PLANAR 0x02300023
#define PFNC_U3V_RGB16_PLANAR 0x02300024
#define PFNC_U3V_RGB16 0x02300033
#define PFNC_U3V_BGR14 0x0230004A
#define PFNC_U3V_BGR16 0x0230004B
#define PFNC_U3V_BGRA12P 0x0230004F
#define PFNC_U3V_RGB14 0x0230005E
#define PFNC_U3V_RGBA12P 0x02300062
#define PFNC_U3V_YCBCR10_CBYCR 0x02300083
#define PFNC_U3V_YCBCR12_CBYCR 0x02300085
#define PFNC_U3V_YCBCR601_10_CBYCR 0x02300089
#define PFNC_U3V_YCBCR601_12_CBYCR 0x0230008B
#define PFNC_U3V_YCBCR709_10_CBYCR 0x02300091
#define PFNC_U3V_YCBCR709_12_CBYCR 0x02300093
#define PFNC_U3V_COORD3D_ABC16 0x023000B9
#define PFNC_U3V_COORD3D_ABC16_PLANAR 0x023000BA
#define PFNC_U3V_BGRA10 0x0240004C
#define PFNC_U3V_BGRA12 0x0240004E
#define PFNC_U3V_BGRA14 0x02400050
#define PFNC_U3V_BGRA16 0x02400051
#define PFNC_U3V_RGBA10 0x0240005F
#define PFNC_U3V_RGBA12 0x02400061
#define PFNC_U3V_RGBA14 0x02400063
#define PFNC_U3V_RGBA16 0x02400064
#define PFNC_U3V_COORD3D_AC32F 0x024000C2
#define PFNC_U3V_COORD3D_AC32F_PLANAR 0x024000C3
#define PFNC_U3V_COORD3D_ABC32F 0x026000C0
#define PFNC_U3V_COORD3D_ABC32F_PLANAR 0x026000C1
/*
Payload Types
*/
#define U3V_STREAM_PAYLOAD_IMAGE 0x0001
#define U3V_STREAM_PAYLOAD_IMAGE_EXT_CHUNK 0x4001
#define U3V_STREAM_PAYLOAD_CHUNK 0x4000
void proto_register_u3v(void);
void proto_reg_handoff_u3v(void);
/* Define the u3v protocol */
static int proto_u3v = -1;
/* GenCP transaction tracking
* the protocol only allows strict sequential
* communication.
*
* we track the current cmd/ack/pend_ack information
* in a struct that is created per GenCP communication
*
* in each request/response packet we add pointers
* to this information, that allow navigation between packets
* and dissection of addresses
*/
typedef struct _gencp_transaction_t {
guint32 cmd_frame;
guint32 ack_frame;
nstime_t cmd_time;
/* list of pending acknowledges */
wmem_array_t *pend_ack_frame_list;
/* current requested address */
guint64 address;
/* current requested count read/write */
guint32 count;
} gencp_transaction_t;
typedef struct _u3v_conv_info_t {
guint64 abrm_addr;
guint64 sbrm_addr;
guint64 sirm_addr;
guint64 eirm_addr;
guint64 iidc2_addr;
guint64 manifest_addr;
guint32 ep_stream;
gencp_transaction_t *trans_info;
} u3v_conv_info_t;
/*
\brief IDs used for bootstrap dissection
*/
static int hf_u3v_gencp_prefix = -1;
static int hf_u3v_flag = -1;
static int hf_u3v_acknowledge_required_flag = -1;
static int hf_u3v_command_id = -1;
static int hf_u3v_length = -1;
static int hf_u3v_request_id = -1;
static int hf_u3v_status = -1;
static int hf_u3v_address = -1;
static int hf_u3v_count = -1;
static int hf_u3v_eventcmd_id = -1;
static int hf_u3v_eventcmd_error_id = -1;
static int hf_u3v_eventcmd_device_specific_id = -1;
static int hf_u3v_eventcmd_timestamp = -1;
static int hf_u3v_eventcmd_data = -1;
static int hf_u3v_time_to_completion = -1;
static int hf_u3v_payloaddata = -1;
static int hf_u3v_reserved = -1;
static int hf_u3v_bootstrap_GenCP_Version = -1;
static int hf_u3v_bootstrap_Manufacturer_Name = -1;
static int hf_u3v_bootstrap_Model_Name = -1;
static int hf_u3v_bootstrap_Family_Name = -1;
static int hf_u3v_bootstrap_Device_Version = -1;
static int hf_u3v_bootstrap_Manufacturer_Info = -1;
static int hf_u3v_bootstrap_Serial_Number = -1;
static int hf_u3v_bootstrap_User_Defined_Name = -1;
static int hf_u3v_bootstrap_Device_Capability = -1;
static int hf_u3v_bootstrap_Maximum_Device_Response_Time = -1;
static int hf_u3v_bootstrap_Manifest_Table_Address = -1;
static int hf_u3v_bootstrap_SBRM_Address = -1;
static int hf_u3v_bootstrap_Device_Configuration = -1;
static int hf_u3v_bootstrap_Heartbeat_Timeout = -1;
static int hf_u3v_bootstrap_Message_Channel_channel_id = -1;
static int hf_u3v_bootstrap_Timestamp = -1;
static int hf_u3v_bootstrap_Timestamp_Latch = -1;
static int hf_u3v_bootstrap_Timestamp_Increment = -1;
static int hf_u3v_bootstrap_Access_Privilege = -1;
static int hf_u3v_bootstrap_Protocol_Endianess = -1;
static int hf_u3v_bootstrap_Implementation_Endianess = -1;
static int hf_u3v_bootstrap_U3V_Version = -1;
static int hf_u3v_bootstrap_U3VCP_Capability_Register = -1;
static int hf_u3v_bootstrap_U3VCP_Configuration_Register = -1;
static int hf_u3v_bootstrap_Maximum_Command_Transfer_Length = -1;
static int hf_u3v_bootstrap_Maximum_Acknowledge_Transfer_Length = -1;
static int hf_u3v_bootstrap_Number_of_Stream_Channels = -1;
static int hf_u3v_bootstrap_SIRM_Address = -1;
static int hf_u3v_bootstrap_SIRM_Length = -1;
static int hf_u3v_bootstrap_EIRM_Address = -1;
static int hf_u3v_bootstrap_EIRM_Length = -1;
static int hf_u3v_bootstrap_IIDC2_Address = -1;
static int hf_u3v_bootstrap_Current_Speed = -1;
static int hf_u3v_bootstrap_SI_Info = -1;
static int hf_u3v_bootstrap_SI_Control = -1;
static int hf_u3v_bootstrap_SI_Required_Payload_Size = -1;
static int hf_u3v_bootstrap_SI_Required_Leader_Size = -1;
static int hf_u3v_bootstrap_SI_Required_Trailer_Size = -1;
static int hf_u3v_bootstrap_SI_Maximum_Leader_Size = -1;
static int hf_u3v_bootstrap_SI_Payload_Transfer_Size = -1;
static int hf_u3v_bootstrap_SI_Payload_Transfer_Count = -1;
static int hf_u3v_bootstrap_SI_Payload_Final_Transfer1_Size = -1;
static int hf_u3v_bootstrap_SI_Payload_Final_Transfer2_Size = -1;
static int hf_u3v_bootstrap_SI_Maximum_Trailer_Size = -1;
static int hf_u3v_bootstrap_EI_Control = -1;
static int hf_u3v_bootstrap_Maximum_Event_Transfer_Length = -1;
static int hf_u3v_bootstrap_Event_Test_Control = -1;
static int hf_u3v_custom_memory_addr = -1;
static int hf_u3v_custom_memory_data = -1;
static int hf_u3v_scd_readmem_cmd = -1;
static int hf_u3v_scd_writemem_cmd = -1;
static int hf_u3v_scd_event_cmd = -1;
static int hf_u3v_scd_ack_readmem_ack = -1;
static int hf_u3v_scd_writemem_ack = -1;
static int hf_u3v_ccd_pending_ack = -1;
static int hf_u3v_stream_leader = -1;
static int hf_u3v_stream_trailer = -1;
static int hf_u3v_stream_payload = -1;
static int hf_u3v_ccd_cmd = -1;
static int hf_u3v_ccd_ack = -1;
static int hf_u3v_device_info_descriptor = -1;
/* stream elements */
static int hf_u3v_stream_reserved = -1;
static int hf_u3v_stream_leader_size = -1;
static int hf_u3v_stream_prefix = -1;
static int hf_u3v_stream_trailer_size = -1;
static int hf_u3v_stream_block_id = -1;
static int hf_u3v_stream_payload_type = -1;
static int hf_u3v_stream_status = -1;
static int hf_u3v_stream_valid_payload_size = -1;
static int hf_u3v_stream_timestamp = -1;
static int hf_u3v_stream_pixel_format = -1;
static int hf_u3v_stream_size_x = -1;
static int hf_u3v_stream_size_y = -1;
static int hf_u3v_stream_offset_x = -1;
static int hf_u3v_stream_offset_y = -1;
static int hf_u3v_stream_padding_x = -1;
static int hf_u3v_stream_chunk_layout_id = -1;
static int hf_u3v_stream_data = -1;
/* U3V device info descriptor */
static int hf_u3v_device_info_descriptor_bLength = -1;
static int hf_u3v_device_info_descriptor_bDescriptorType = -1;
static int hf_u3v_device_info_descriptor_bDescriptorSubtype = -1;
static int hf_u3v_device_info_descriptor_bGenCPVersion = -1;
static int hf_u3v_device_info_descriptor_bGenCPVersion_minor = -1;
static int hf_u3v_device_info_descriptor_bGenCPVersion_major = -1;
static int hf_u3v_device_info_descriptor_bU3VVersion = -1;
static int hf_u3v_device_info_descriptor_bU3VVersion_minor = -1;
static int hf_u3v_device_info_descriptor_bU3VVersion_major = -1;
static int hf_u3v_device_info_descriptor_iDeviceGUID = -1;
static int hf_u3v_device_info_descriptor_iVendorName = -1;
static int hf_u3v_device_info_descriptor_iModelName = -1;
static int hf_u3v_device_info_descriptor_iFamilyName = -1;
static int hf_u3v_device_info_descriptor_iDeviceVersion = -1;
static int hf_u3v_device_info_descriptor_iManufacturerInfo = -1;
static int hf_u3v_device_info_descriptor_iSerialNumber = -1;
static int hf_u3v_device_info_descriptor_iUserDefinedName = -1;
static int hf_u3v_device_info_descriptor_bmSpeedSupport = -1;
static int hf_u3v_device_info_descriptor_bmSpeedSupport_low_speed = -1;
static int hf_u3v_device_info_descriptor_bmSpeedSupport_full_speed = -1;
static int hf_u3v_device_info_descriptor_bmSpeedSupport_high_speed = -1;
static int hf_u3v_device_info_descriptor_bmSpeedSupport_super_speed = -1;
static int hf_u3v_device_info_descriptor_bmSpeedSupport_reserved = -1;
/*Define the tree for u3v*/
static int ett_u3v = -1;
static int ett_u3v_cmd = -1;
static int ett_u3v_flags = -1;
static int ett_u3v_ack = -1;
static int ett_u3v_payload_cmd = -1;
static int ett_u3v_payload_ack = -1;
static int ett_u3v_payload_cmd_subtree = -1;
static int ett_u3v_payload_ack_subtree = -1;
static int ett_u3v_bootstrap_fields = -1;
static int ett_u3v_stream_leader = -1;
static int ett_u3v_stream_trailer = -1;
static int ett_u3v_stream_payload = -1;
static int ett_u3v_device_info_descriptor = -1;
static int ett_u3v_device_info_descriptor_speed_support = -1;
static int ett_u3v_device_info_descriptor_gencp_version = -1;
static int ett_u3v_device_info_descriptor_u3v_version = -1;
static const value_string command_names[] =
{
{ U3V_READMEM_CMD, "READMEM_CMD" },
{ U3V_WRITEMEM_CMD, "WRITEMEM_CMD" },
{ U3V_EVENT_CMD, "EVENT_CMD" },
{ U3V_READMEM_ACK, "READMEM_ACK" },
{ U3V_WRITEMEM_ACK, "WRITEMEM_ACK" },
{ U3V_PENDING_ACK, "PENDING_ACK" },
{ U3V_EVENT_ACK, "EVENT_ACK" },
{ 0, NULL }
};
static const value_string event_id_names[] =
{
{ U3V_EVENT_TESTEVENT, "U3V_EVENT_TESTEVENT" },
{ 0, NULL }
};
static const value_string status_names[] =
{
{ U3V_STATUS_GENCP_SUCCESS, "U3V_STATUS_GENCP_SUCCESS" },
{ U3V_STATUS_GENCP_NOT_IMPLEMENTED, "U3V_STATUS_GENCP_NOT_IMPLEMENTED" },
{ U3V_STATUS_GENCP_INVALID_PARAMETER, "U3V_STATUS_GENCP_INVALID_PARAMETER" },
{ U3V_STATUS_GENCP_INVALID_ADDRESS, "U3V_STATUS_GENCP_INVALID_ADDRESS" },
{ U3V_STATUS_GENCP_WRITE_PROTECT, "U3V_STATUS_GENCP_WRITE_PROTECT" },
{ U3V_STATUS_GENCP_BAD_ALIGNMENT, "U3V_STATUS_GENCP_BAD_ALIGNMENT" },
{ U3V_STATUS_GENCP_ACCESS_DENIED, "U3V_STATUS_GENCP_ACCESS_DENIED" },
{ U3V_STATUS_GENCP_BUSY, "U3V_STATUS_GENCP_BUSY" },
{ U3V_STATUS_GENCP_WRONG_CONFIG, "U3V_STATUS_GENCP_WRONG_CONFIG" },
{ U3V_STATUS_RESEND_NOT_SUPPORTED, "U3V_STATUS_RESEND_NOT_SUPPORTED" },
{ U3V_STATUS_DSI_ENDPOINT_HALTED, "U3V_STATUS_DSI_ENDPOINT_HALTED" },
{ U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED, "U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED" },
{ U3V_STATUS_SI_REGISTERS_INCONSISTENT, "U3V_STATUS_SI_REGISTERS_INCONSISTENT" },
{ U3V_STATUS_DATA_DISCARDED, "U3V_STATUS_DATA_DISCARDED" },
{ 0, NULL }
};
static const value_string status_names_short[] =
{
{ U3V_STATUS_GENCP_SUCCESS, "" },
{ U3V_STATUS_GENCP_NOT_IMPLEMENTED, "U3V_STATUS_GENCP_NOT_IMPLEMENTED" },
{ U3V_STATUS_GENCP_INVALID_PARAMETER, "U3V_STATUS_GENCP_INVALID_PARAMETER" },
{ U3V_STATUS_GENCP_INVALID_ADDRESS, "U3V_STATUS_GENCP_INVALID_ADDRESS" },
{ U3V_STATUS_GENCP_WRITE_PROTECT, "U3V_STATUS_GENCP_WRITE_PROTECT" },
{ U3V_STATUS_GENCP_BAD_ALIGNMENT, "U3V_STATUS_GENCP_BAD_ALIGNMENT" },
{ U3V_STATUS_GENCP_ACCESS_DENIED, "U3V_STATUS_GENCP_ACCESS_DENIED" },
{ U3V_STATUS_GENCP_BUSY, "U3V_STATUS_GENCP_BUSY" },
{ U3V_STATUS_GENCP_WRONG_CONFIG, "U3V_STATUS_GENCP_WRONG_CONFIG" },
{ U3V_STATUS_RESEND_NOT_SUPPORTED, "U3V_STATUS_RESEND_NOT_SUPPORTED" },
{ U3V_STATUS_DSI_ENDPOINT_HALTED, "U3V_STATUS_DSI_ENDPOINT_HALTED" },
{ U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED, "U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED" },
{ U3V_STATUS_SI_REGISTERS_INCONSISTENT, "U3V_STATUS_SI_REGISTERS_INCONSISTENT" },
{ U3V_STATUS_DATA_DISCARDED, "U3V_STATUS_DATA_DISCARDED" },
{ 0, NULL }
};
/*
\brief Register name to address mappings
*/
static const value_string bootstrap_register_names_abrm[] =
{
{ U3V_ABRM_GENCP_VERSION, "[GenCP_Version]" },
{ U3V_ABRM_MANUFACTURER_NAME, "[Manufacturer_Name]" },
{ U3V_ABRM_MODEL_NAME, "[Model_Name]" },
{ U3V_ABRM_FAMILY_NAME, "[Family_Name]" },
{ U3V_ABRM_DEVICE_VERSION, "[Device_Version]" },
{ U3V_ABRM_MANUFACTURER_INFO, "[Manufacturer_Info]" },
{ U3V_ABRM_SERIAL_NUMBER, "[Serial_Number]" },
{ U3V_ABRM_USER_DEFINED_NAME, "[User_Defined_Name]" },
{ U3V_ABRM_DEVICE_CAPABILITY, "[Device_Capability]" },
{ U3V_ABRM_MAXIMUM_DEVICE_RESPONSE_TIME, "[Maximum_Device_Response_Time]" },
{ U3V_ABRM_MANIFEST_TABLE_ADDRESS, "[Manifest_Table_Address]" },
{ U3V_ABRM_SBRM_ADDRESS, "[SBRM_Address]" },
{ U3V_ABRM_DEVICE_CONFIGURATION, "[Device_Configuration]" },
{ U3V_ABRM_HEARTBEAT_TIMEOUT, "[Heartbeat_Timeout]" },
{ U3V_ABRM_MESSAGE_CHANNEL_CHANNEL_ID, "[Message_Channel_channel_id]" },
{ U3V_ABRM_TIMESTAMP, "[Timestamp]" },
{ U3V_ABRM_TIMESTAMP_LATCH, "[Timestamp_Latch]" },
{ U3V_ABRM_TIMESTAMP_INCREMENT, "[Timestamp_Increment]" },
{ U3V_ABRM_ACCESS_PRIVILEGE, "[Access_Privilege]" },
{ U3V_ABRM_PROTOCOL_ENDIANESS, "[Protocol_Endianess]" },
{ U3V_ABRM_IMPLEMENTATION_ENDIANESS, "[Implementation_Endianess]" },
{ 0, NULL }
};
static const value_string bootstrap_register_names_sbrm[] =
{
{ U3V_SBRM_U3V_VERSION, "[U3V_Version]" },
{ U3V_SBRM_U3VCP_CAPABILITY_REGISTER, "[U3VCP_Capability_Register]" },
{ U3V_SBRM_U3VCP_CONFIGURATION_REGISTER, "[U3VCP_Configuration_Register]" },
{ U3V_SBRM_MAXIMUM_COMMAND_TRANSFER_LENGTH, "[Maximum_Command_Transfer_Length]" },
{ U3V_SBRM_MAXIMUM_ACKNOWLEDGE_TRANSFER_LENGTH, "[Maximum_Acknowledge_Transfer_Length]" },
{ U3V_SBRM_NUMBER_OF_STREAM_CHANNELS, "[Number_of_Stream_Channels]" },
{ U3V_SBRM_SIRM_ADDRESS, "[SIRM_Address]" },
{ U3V_SBRM_SIRM_LENGTH, "[SIRM_Length]" },
{ U3V_SBRM_EIRM_ADDRESS, "[EIRM_Address]" },
{ U3V_SBRM_EIRM_LENGTH, "[EIRM_Length]" },
{ U3V_SBRM_IIDC2_ADDRESS, "[IIDC2_Address]" },
{ U3V_SBRM_CURRENT_SPEED, "[Current_Speed]" },
{ 0, NULL }
};
static const value_string bootstrap_register_names_sirm[] =
{
{ U3V_SIRM_SI_INFO, "[SI_Info]" },
{ U3V_SIRM_SI_CONTROL, "[SI_Control]" },
{ U3V_SIRM_SI_REQUIRED_PAYLOAD_SIZE, "[SI_Required_Payload_Size]" },
{ U3V_SIRM_SI_REQUIRED_LEADER_SIZE, "[SI_Required_Leader_Size]" },
{ U3V_SIRM_SI_REQUIRED_TRAILER_SIZE, "[SI_Required_Trailer_Size]" },
{ U3V_SIRM_SI_MAXIMUM_LEADER_SIZE, "[SI_Maximum_Leader_Size]" },
{ U3V_SIRM_SI_PAYLOAD_TRANSFER_SIZE, "[SI_Payload_Transfer_Size]" },
{ U3V_SIRM_SI_PAYLOAD_TRANSFER_COUNT, "[SI_Payload_Transfer_Count]" },
{ U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER1_SIZE, "[SI_Payload_Final_Transfer1_Size]" },
{ U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER2_SIZE, "[SI_Payload_Final_Transfer2_Size]" },
{ U3V_SIRM_SI_MAXIMUM_TRAILER_SIZE, "[SI_Maximum_Trailer_Size]" },
{ 0, NULL }
};
static const value_string bootstrap_register_names_eirm[] =
{
{ U3V_EIRM_EI_CONTROL, "[EI_Control]" },
{ U3V_EIRM_MAXIMUM_EVENT_TRANSFER_LENGTH, "[Maximum_Event_Transfer_Length]" },
{ U3V_EIRM_EVENT_TEST_CONTROL, "[Event_Test_Control]" },
{ 0, NULL }
};
static const value_string pixel_format_names[] =
{
{ PFNC_U3V_MONO1P, "Mono1p" },
{ PFNC_U3V_CONFIDENCE1P, "CONFIDENCE1p" },
{ PFNC_U3V_MONO2P, "Mono2p" },
{ PFNC_U3V_MONO4P, "Mono4p" },
{ PFNC_U3V_MONO8, "Mono8" },
{ PFNC_U3V_MONO8S, "Mono8s" },
{ PFNC_U3V_BAYERGR8, "BayerGR8" },
{ PFNC_U3V_BAYERRG8, "BayerRG8" },
{ PFNC_U3V_BAYERGB8, "BayerGB8" },
{ PFNC_U3V_BAYERBG8, "BayerBG8" },
{ PFNC_U3V_SCF1WBWG8, "SCF1WBWG8" },
{ PFNC_U3V_SCF1WGWB8, "SCF1WGWB8" },
{ PFNC_U3V_SCF1WGWR8, "SCF1WGWR8" },
{ PFNC_U3V_SCF1WRWG8, "SCF1WRWG8" },
{ PFNC_U3V_COORD3D_A8, "Coord3D_A8" },
{ PFNC_U3V_COORD3D_B8, "Coord3D_B8" },
{ PFNC_U3V_COORD3D_C8, "Coord3D_C8" },
{ PFNC_U3V_CONFIDENCE1, "CONFIDENCE1" },
{ PFNC_U3V_CONFIDENCE8, "CONFIDENCE8" },
{ PFNC_U3V_R8, "R8" },
{ PFNC_U3V_G8, "G8" },
{ PFNC_U3V_B8, "B8" },
{ PFNC_U3V_MONO10P, "Mono10p" },
{ PFNC_U3V_BAYERBG10P, "BayerBG10p" },
{ PFNC_U3V_BAYERGB10P, "BayerGB10p" },
{ PFNC_U3V_BAYERGR10P, "BayerGR10p" },
{ PFNC_U3V_BAYERRG10P, "BayerRG10p" },
{ PFNC_U3V_SCF1WBWG10P, "SCF1WBWG10p" },
{ PFNC_U3V_SCF1WGWB10P, "SCF1WGWB10p" },
{ PFNC_U3V_SCF1WGWR10P, "SCF1WGWR10p" },
{ PFNC_U3V_SCF1WRWG10P, "SCF1WRWG10p" },
{ PFNC_U3V_R10, "R10" },
{ PFNC_U3V_G10, "G10" },
{ PFNC_U3V_B10, "B10" },
{ PFNC_U3V_COORD3D_A10P, "Coord3D_A10p" },
{ PFNC_U3V_COORD3D_B10P, "Coord3D_B10p" },
{ PFNC_U3V_COORD3D_C10P, "Coord3D_C10p" },
{ PFNC_U3V_MONO10PACKED, "Mono10Packed" },
{ PFNC_U3V_MONO12PACKED, "Mono12Packed" },
{ PFNC_U3V_BAYERGR10PACKED, "BayerGR10Packed" },
{ PFNC_U3V_BAYERRG10PACKED, "BayerRG10Packed" },
{ PFNC_U3V_BAYERGB10PACKED, "BayerGB10Packed" },
{ PFNC_U3V_BAYERBG10PACKED, "BayerBG10Packed" },
{ PFNC_U3V_BAYERGR12PACKED, "BayerGR12Packed" },
{ PFNC_U3V_BAYERRG12PACKED, "BayerRG12Packed" },
{ PFNC_U3V_BAYERGB12PACKED, "BayerGB12Packed" },
{ PFNC_U3V_BAYERBG12PACKED, "BayerBG12Packed" },
{ PFNC_U3V_MONO12P, "Mono12p" },
{ PFNC_U3V_BAYERBG12P, "BayerBG12p" },
{ PFNC_U3V_BAYERGB12P, "BayerGB12p" },
{ PFNC_U3V_BAYERGR12P, "BayerGR12p" },
{ PFNC_U3V_BAYERRG12P, "BayerRG12p" },
{ PFNC_U3V_SCF1WBWG12P, "SCF1WBWG12p" },
{ PFNC_U3V_SCF1WGWB12P, "SCF1WGWB12p" },
{ PFNC_U3V_SCF1WGWR12P, "SCF1WGWR12p" },
{ PFNC_U3V_SCF1WRWG12P, "SCF1WRWG12p" },
{ PFNC_U3V_R12, "R12" },
{ PFNC_U3V_G12, "G12" },
{ PFNC_U3V_B12, "B12" },
{ PFNC_U3V_COORD3D_A12P, "Coord3D_A12p" },
{ PFNC_U3V_COORD3D_B12P, "Coord3D_B12p" },
{ PFNC_U3V_COORD3D_C12P, "Coord3D_C12p" },
{ PFNC_U3V_MONO10, "Mono10" },
{ PFNC_U3V_MONO12, "Mono12" },
{ PFNC_U3V_MONO16, "Mono16" },
{ PFNC_U3V_BAYERGR10, "BayerGR10" },
{ PFNC_U3V_BAYERRG10, "BayerRG10" },
{ PFNC_U3V_BAYERGB10, "BayerGB10" },
{ PFNC_U3V_BAYERBG10, "BayerBG10" },
{ PFNC_U3V_BAYERGR12, "BayerGR12" },
{ PFNC_U3V_BAYERRG12, "BayerRG12" },
{ PFNC_U3V_BAYERGB12, "BayerGB12" },
{ PFNC_U3V_BAYERBG12, "BayerBG12" },
{ PFNC_U3V_MONO14, "Mono14" },
{ PFNC_U3V_BAYERGR16, "BayerGR16" },
{ PFNC_U3V_BAYERRG16, "BayerRG16" },
{ PFNC_U3V_BAYERGB16, "BayerGB16" },
{ PFNC_U3V_BAYERBG16, "BayerBG16" },
{ PFNC_U3V_SCF1WBWG10, "SCF1WBWG10" },
{ PFNC_U3V_SCF1WBWG12, "SCF1WBWG12" },
{ PFNC_U3V_SCF1WBWG14, "SCF1WBWG14" },
{ PFNC_U3V_SCF1WBWG16, "SCF1WBWG16" },
{ PFNC_U3V_SCF1WGWB10, "SCF1WGWB10" },
{ PFNC_U3V_SCF1WGWB12, "SCF1WGWB12" },
{ PFNC_U3V_SCF1WGWB14, "SCF1WGWB14" },
{ PFNC_U3V_SCF1WGWB16, "SCF1WGWB16" },
{ PFNC_U3V_SCF1WGWR10, "SCF1WGWR10" },
{ PFNC_U3V_SCF1WGWR12, "SCF1WGWR12" },
{ PFNC_U3V_SCF1WGWR14, "SCF1WGWR14" },
{ PFNC_U3V_SCF1WGWR16, "SCF1WGWR16" },
{ PFNC_U3V_SCF1WRWG10, "SCF1WRWG10" },
{ PFNC_U3V_SCF1WRWG12, "SCF1WRWG12" },
{ PFNC_U3V_SCF1WRWG14, "SCF1WRWG14" },
{ PFNC_U3V_SCF1WRWG16, "SCF1WRWG16" },
{ PFNC_U3V_COORD3D_A16, "Coord3D_A16" },
{ PFNC_U3V_COORD3D_B16, "Coord3D_B16" },
{ PFNC_U3V_COORD3D_C16, "Coord3D_C16" },
{ PFNC_U3V_CONFIDENCE16, "CONFIDENCE16" },
{ PFNC_U3V_R16, "R16" },
{ PFNC_U3V_G16, "G16" },
{ PFNC_U3V_B16, "B16" },
{ PFNC_U3V_COORD3D_A32F, "Coord3D_A32F" },
{ PFNC_U3V_COORD3D_B32F, "Coord3D_B32F" },
{ PFNC_U3V_COORD3D_C32F, "Coord3D_C32F" },
{ PFNC_U3V_CONFIDENCE32F, "CONFIDENCE32F" },
{ PFNC_U3V_YUV411_8_UYYVYY, "YUV411_8_UYYVYY" },
{ PFNC_U3V_YCBCR411_8_CBYYCRYY, "YCbCr411_8_CBYYCRYY" },
{ PFNC_U3V_YCBCR601_411_8_CBYYCRYY, "YCbCr601_411_8_CBYYCRYY" },
{ PFNC_U3V_YCBCR709_411_8_CBYYCRYY, "YCbCr709_411_8_CBYYCRYY" },
{ PFNC_U3V_YCBCR411_8, "YCbCr411_8" },
{ PFNC_U3V_YUV422_8_UYVY, "YUV422_8_UYVY" },
{ PFNC_U3V_YUV422_8, "YUV422_8" },
{ PFNC_U3V_RGB565P, "RGB565p" },
{ PFNC_U3V_BGR565P, "BGR565p" },
{ PFNC_U3V_YCBCR422_8, "YCbCr422_8" },
{ PFNC_U3V_YCBCR601_422_8, "YCbCr601_422_8" },
{ PFNC_U3V_YCBCR709_422_8, "YCbCr709_422_8" },
{ PFNC_U3V_YCBCR422_8_CBYCRY, "YCbCr422_8_CBYCRY" },
{ PFNC_U3V_YCBCR601_422_8_CBYCRY, "YCbCr601_422_8_CBYCRY" },
{ PFNC_U3V_YCBCR709_422_8_CBYCRY, "YCbCr709_422_8_CBYCRY" },
{ PFNC_U3V_BICOLORRGBG8, "BICOLORRGBG8" },
{ PFNC_U3V_BICOLORBGRG8, "BICOLORBGRG8" },
{ PFNC_U3V_COORD3D_AC8, "Coord3D_AC8" },
{ PFNC_U3V_COORD3D_AC8_PLANAR, "Coord3D_AC8_Planar" },
{ PFNC_U3V_YCBCR422_10P, "YCbCr422_10p" },
{ PFNC_U3V_YCBCR601_422_10P, "YCbCr601_422_10p" },
{ PFNC_U3V_YCBCR709_422_10P, "YCbCr709_422_10p" },
{ PFNC_U3V_YCBCR422_10P_CBYCRY, "YCbCr422_10P_CBYCRY" },
{ PFNC_U3V_YCBCR601_422_10P_CBYCRY, "YCbCr601_422_10P_CBYCRY" },
{ PFNC_U3V_YCBCR709_422_10P_CBYCRY, "YCbCr709_422_10P_CBYCRY" },
{ PFNC_U3V_BICOLORRGBG10P, "BICOLORRGBG10p" },
{ PFNC_U3V_BICOLORBGRG10P, "BICOLORBGRG10p" },
{ PFNC_U3V_COORD3D_AC10P, "Coord3D_AC10p" },
{ PFNC_U3V_COORD3D_AC10P_PLANAR, "Coord3D_AC10P_Planar" },
{ PFNC_U3V_RGB8, "RGB8" },
{ PFNC_U3V_BGR8, "BGR8" },
{ PFNC_U3V_YUV8_UYV, "YUV8_UYV" },
{ PFNC_U3V_RGB8_PLANAR, "RGB8_Planar" },
{ PFNC_U3V_YCBCR8_CBYCR, "YCbCr8_CBYCR" },
{ PFNC_U3V_YCBCR601_8_CBYCR, "YCbCr601_8_CBYCR" },
{ PFNC_U3V_YCBCR709_8_CBYCR, "YCbCr709_8_CBYCR" },
{ PFNC_U3V_YCBCR8, "YCbCr8" },
{ PFNC_U3V_YCBCR422_12P, "YCbCr422_12p" },
{ PFNC_U3V_YCBCR601_422_12P, "YCbCr601_422_12p" },
{ PFNC_U3V_YCBCR709_422_12P, "YCbCr709_422_12p" },
{ PFNC_U3V_YCBCR422_12P_CBYCRY, "YCbCr422_12P_CBYCRY" },
{ PFNC_U3V_YCBCR601_422_12P_CBYCRY, "YCbCr601_422_12P_CBYCRY" },
{ PFNC_U3V_YCBCR709_422_12P_CBYCRY, "YCbCr709_422_12P_CBYCRY" },
{ PFNC_U3V_BICOLORRGBG12P, "BICOLORRGBG12p" },
{ PFNC_U3V_BICOLORBGRG12P, "BICOLORBGRG12p" },
{ PFNC_U3V_COORD3D_ABC8, "Coord3D_ABC8" },
{ PFNC_U3V_COORD3D_ABC8_PLANAR, "Coord3D_ABC8_Planar" },
{ PFNC_U3V_COORD3D_AC12P, "Coord3D_AC12p" },
{ PFNC_U3V_COORD3D_AC12P_PLANAR, "Coord3D_AC12P_Planar" },
{ PFNC_U3V_BGR10P, "BGR10p" },
{ PFNC_U3V_RGB10P, "RGB10p" },
{ PFNC_U3V_YCBCR10P_CBYCR, "YCbCr10P_CBYCR" },
{ PFNC_U3V_YCBCR601_10P_CBYCR, "YCbCr601_10P_CBYCR" },
{ PFNC_U3V_YCBCR709_10P_CBYCR, "YCbCr709_10P_CBYCR" },
{ PFNC_U3V_COORD3D_ABC10P, "Coord3D_ABC10p" },
{ PFNC_U3V_COORD3D_ABC10P_PLANAR, "Coord3D_ABC10P_Planar" },
{ PFNC_U3V_RGBA8, "RGBA8" },
{ PFNC_U3V_BGRA8, "BGRA8" },
{ PFNC_U3V_RGB10V1PACKED, "RGB10V1Packed" },
{ PFNC_U3V_RGB10P32, "RGB10P32" },
{ PFNC_U3V_YCBCR422_10, "YCbCr422_10" },
{ PFNC_U3V_YCBCR422_12, "YCbCr422_12" },
{ PFNC_U3V_YCBCR601_422_10, "YCbCr601_422_10" },
{ PFNC_U3V_YCBCR601_422_12, "YCbCr601_422_12" },
{ PFNC_U3V_YCBCR709_422_10, "YCbCr709_422_10" },
{ PFNC_U3V_YCBCR709_422_12, "YCbCr709_422_12" },
{ PFNC_U3V_YCBCR422_10_CBYCRY, "YCbCr422_10_CBYCRY" },
{ PFNC_U3V_YCBCR422_12_CBYCRY, "YCbCr422_12_CBYCRY" },
{ PFNC_U3V_YCBCR601_422_10_CBYCRY, "YCbCr601_422_10_CBYCRY" },
{ PFNC_U3V_YCBCR601_422_12_CBYCRY, "YCbCr601_422_12_CBYCRY" },
{ PFNC_U3V_YCBCR709_422_10_CBYCRY, "YCbCr709_422_10_CBYCRY" },
{ PFNC_U3V_YCBCR709_422_12_CBYCRY, "YCbCr709_422_12_CBYCRY" },
{ PFNC_U3V_BICOLORRGBG10, "BICOLORRGBG10" },
{ PFNC_U3V_BICOLORBGRG10, "BICOLORBGRG10" },
{ PFNC_U3V_BICOLORRGBG12, "BICOLORRGBG12" },
{ PFNC_U3V_BICOLORBGRG12, "BICOLORBGRG12" },
{ PFNC_U3V_COORD3D_AC16, "Coord3D_AC16" },
{ PFNC_U3V_COORD3D_AC16_PLANAR, "Coord3D_AC16_Planar" },
{ PFNC_U3V_RGB12V1PACKED, "RGB12V1Packed" },
{ PFNC_U3V_BGR12P, "BGR12p" },
{ PFNC_U3V_RGB12P, "RGB12p" },
{ PFNC_U3V_YCBCR12P_CBYCR, "YCbCr12P_CBYCR" },
{ PFNC_U3V_YCBCR601_12P_CBYCR, "YCbCr601_12P_CBYCR" },
{ PFNC_U3V_YCBCR709_12P_CBYCR, "YCbCr709_12P_CBYCR" },
{ PFNC_U3V_COORD3D_ABC12P, "Coord3D_ABC12p" },
{ PFNC_U3V_COORD3D_ABC12P_PLANAR, "Coord3D_ABC12P_Planar" },
{ PFNC_U3V_BGRA10P, "BGRA10p" },
{ PFNC_U3V_RGBA10P, "RGBA10p" },
{ PFNC_U3V_RGB10, "RGB10" },
{ PFNC_U3V_BGR10, "BGR10" },
{ PFNC_U3V_RGB12, "RGB12" },
{ PFNC_U3V_BGR12, "BGR12" },
{ PFNC_U3V_RGB10_PLANAR, "RGB10_Planar" },
{ PFNC_U3V_RGB12_PLANAR, "RGB12_Planar" },
{ PFNC_U3V_RGB16_PLANAR, "RGB16_Planar" },
{ PFNC_U3V_RGB16, "RGB16" },
{ PFNC_U3V_BGR14, "BGR14" },
{ PFNC_U3V_BGR16, "BGR16" },
{ PFNC_U3V_BGRA12P, "BGRA12p" },
{ PFNC_U3V_RGB14, "RGB14" },
{ PFNC_U3V_RGBA12P, "RGBA12p" },
{ PFNC_U3V_YCBCR10_CBYCR, "YCbCr10_CBYCR" },
{ PFNC_U3V_YCBCR12_CBYCR, "YCbCr12_CBYCR" },
{ PFNC_U3V_YCBCR601_10_CBYCR, "YCbCr601_10_CBYCR" },
{ PFNC_U3V_YCBCR601_12_CBYCR, "YCbCr601_12_CBYCR" },
{ PFNC_U3V_YCBCR709_10_CBYCR, "YCbCr709_10_CBYCR" },
{ PFNC_U3V_YCBCR709_12_CBYCR, "YCbCr709_12_CBYCR" },
{ PFNC_U3V_COORD3D_ABC16, "Coord3D_ABC16" },
{ PFNC_U3V_COORD3D_ABC16_PLANAR, "Coord3D_ABC16_Planar" },
{ PFNC_U3V_BGRA10, "BGRA10" },
{ PFNC_U3V_BGRA12, "BGRA12" },
{ PFNC_U3V_BGRA14, "BGRA14" },
{ PFNC_U3V_BGRA16, "BGRA16" },
{ PFNC_U3V_RGBA10, "RGBA10" },
{ PFNC_U3V_RGBA12, "RGBA12" },
{ PFNC_U3V_RGBA14, "RGBA14" },
{ PFNC_U3V_RGBA16, "RGBA16" },
{ PFNC_U3V_COORD3D_AC32F, "Coord3D_AC32F" },
{ PFNC_U3V_COORD3D_AC32F_PLANAR, "Coord3D_AC32F_Planar" },
{ PFNC_U3V_COORD3D_ABC32F, "Coord3D_ABC32F" },
{ PFNC_U3V_COORD3D_ABC32F_PLANAR, "Coord3D_ABC32F_Planar" },
{ 0, NULL }
};
static value_string_ext pixel_format_names_ext = VALUE_STRING_EXT_INIT(pixel_format_names);
static const value_string payload_type_names[] =
{
{ U3V_STREAM_PAYLOAD_IMAGE, "Image" },
{ U3V_STREAM_PAYLOAD_IMAGE_EXT_CHUNK, "Image Extended Chunk" },
{ U3V_STREAM_PAYLOAD_CHUNK, "Chunk" },
{ 0, NULL }
};
static const value_string u3v_descriptor_subtypes[] =
{
{ DESCRIPTOR_SUBTYPE_U3V_DEVICE_INFO, "U3V DEVICE INFO" },
{ 0, NULL }
};
static const int *speed_support_fields[] = {
&hf_u3v_device_info_descriptor_bmSpeedSupport_low_speed,
&hf_u3v_device_info_descriptor_bmSpeedSupport_full_speed,
&hf_u3v_device_info_descriptor_bmSpeedSupport_high_speed,
&hf_u3v_device_info_descriptor_bmSpeedSupport_super_speed,
&hf_u3v_device_info_descriptor_bmSpeedSupport_reserved,
NULL
};
/*
\brief Returns a register name based on its address
*/
static const gchar*
get_register_name_from_address(guint64 addr, gboolean* is_custom_register, u3v_conv_info_t * u3v_conv_info)
{
const gchar* address_string = NULL;
guint32 offset_address;
if (is_custom_register != NULL) {
*is_custom_register = FALSE;
}
/* check if this is the access to one of the base address registers */
if ( addr < 0x10000 ) {
offset_address = (guint32)addr;
address_string = try_val_to_str(offset_address, bootstrap_register_names_abrm);
}
if ( u3v_conv_info && u3v_conv_info->sbrm_addr != 0 && (addr >= u3v_conv_info->sbrm_addr)) {
offset_address = (guint32)( addr - u3v_conv_info->sbrm_addr);
address_string = try_val_to_str(offset_address, bootstrap_register_names_sbrm);
}
if ( u3v_conv_info && u3v_conv_info->sirm_addr != 0 && (addr >= u3v_conv_info->sirm_addr)) {
offset_address = (guint32)( addr - u3v_conv_info->sirm_addr);
address_string = try_val_to_str(offset_address, bootstrap_register_names_sirm);
}
if ( u3v_conv_info && u3v_conv_info->eirm_addr != 0 && (addr >= u3v_conv_info->eirm_addr)) {
offset_address = (guint32)( addr - u3v_conv_info->eirm_addr);
address_string = try_val_to_str(offset_address, bootstrap_register_names_eirm);
}
if (!address_string) {
address_string = wmem_strdup_printf(wmem_packet_scope(), "[Addr:0x%016" G_GINT64_MODIFIER "X]", addr);
if (is_custom_register != NULL) {
*is_custom_register = TRUE;
}
}
return address_string;
}
/*
\brief Returns true if a register (identified by its address) is a known bootstrap register
*/
static int
is_known_bootstrap_register(guint64 addr, u3v_conv_info_t * u3v_conv_info)
{
const gchar* address_string = NULL;
guint32 offset_address;
/* check if this is the access to one of the base address registers */
if ( addr < 0x10000 ) {
offset_address = (guint32)addr;
address_string = try_val_to_str(offset_address, bootstrap_register_names_abrm);
}
if ( u3v_conv_info->sbrm_addr != 0 && (addr >= u3v_conv_info->sbrm_addr)) {
offset_address = (guint32)( addr - u3v_conv_info->sbrm_addr);
address_string = try_val_to_str(offset_address, bootstrap_register_names_sbrm);
}
if ( u3v_conv_info->sirm_addr != 0 && (addr >= u3v_conv_info->sirm_addr)) {
offset_address = (guint32)( addr - u3v_conv_info->sirm_addr);
address_string = try_val_to_str(offset_address, bootstrap_register_names_sirm);
}
if ( u3v_conv_info->eirm_addr != 0 && (addr >= u3v_conv_info->eirm_addr)) {
offset_address = (guint32)( addr - u3v_conv_info->eirm_addr);
address_string = try_val_to_str(offset_address, bootstrap_register_names_eirm);
}
return address_string != NULL;
}
/*
\brief Identify Base Address Pointer
*/
static void
dissect_u3v_register_bases(guint64 addr, tvbuff_t *tvb, gint offset, u3v_conv_info_t * u3v_conv_info)
{
if ( addr < 0x10000 ) {
switch (addr) {
case U3V_ABRM_SBRM_ADDRESS:
u3v_conv_info->sbrm_addr = tvb_get_letoh64(tvb, offset);
break;
case U3V_ABRM_MANIFEST_TABLE_ADDRESS:
u3v_conv_info->manifest_addr = tvb_get_letoh64(tvb, offset);
break;
}
}
if ( u3v_conv_info->sbrm_addr != 0 && (addr >= u3v_conv_info->sbrm_addr)) {
addr -= u3v_conv_info->sbrm_addr;
switch(addr) {
case U3V_SBRM_SIRM_ADDRESS:
u3v_conv_info->sirm_addr = tvb_get_letoh64(tvb, offset);
break;
case U3V_SBRM_EIRM_ADDRESS:
u3v_conv_info->eirm_addr = tvb_get_letoh64(tvb, offset);
break;
case U3V_SBRM_IIDC2_ADDRESS:
u3v_conv_info->iidc2_addr = tvb_get_letoh64(tvb, offset);
break;
}
}
}
/*
\brief Attempt to dissect a bootstrap register
*/
static int
dissect_u3v_register(guint64 addr, proto_tree *branch, tvbuff_t *tvb, gint offset, gint length, u3v_conv_info_t * u3v_conv_info)
{
gint isABRM = FALSE, isSBRM = FALSE, isSIRM = FALSE,isEIRM = FALSE;
/* check if this is the access to one of the base address registers */
if ( addr < 0x10000 ) {
isABRM = TRUE;
switch (addr) {
case U3V_ABRM_GENCP_VERSION:
proto_tree_add_item(branch, hf_u3v_bootstrap_GenCP_Version, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_MANUFACTURER_NAME:
if ( length <= 64 ) {
proto_tree_add_item(branch, hf_u3v_bootstrap_Manufacturer_Name, tvb, offset, length, ENC_ASCII|ENC_NA);
}
break;
case U3V_ABRM_MODEL_NAME:
if ( length <= 64 ) {
proto_tree_add_item(branch, hf_u3v_bootstrap_Model_Name, tvb, offset, length, ENC_ASCII|ENC_NA);
}
break;
case U3V_ABRM_FAMILY_NAME:
if ( length <= 64 ) {
proto_tree_add_item(branch, hf_u3v_bootstrap_Family_Name, tvb, offset, length, ENC_ASCII|ENC_NA);
}
break;
case U3V_ABRM_DEVICE_VERSION:
if ( length <= 64 ) {
proto_tree_add_item(branch, hf_u3v_bootstrap_Device_Version, tvb, offset, length, ENC_ASCII|ENC_NA);
}
break;
case U3V_ABRM_MANUFACTURER_INFO:
if ( length <= 64 ) {
proto_tree_add_item(branch, hf_u3v_bootstrap_Manufacturer_Info, tvb, offset, length, ENC_ASCII|ENC_NA);
}
break;
case U3V_ABRM_SERIAL_NUMBER:
if ( length <= 64 ) {
proto_tree_add_item(branch, hf_u3v_bootstrap_Serial_Number, tvb, offset, length, ENC_ASCII|ENC_NA);
}
break;
case U3V_ABRM_USER_DEFINED_NAME:
if ( length <= 64 ) {
proto_tree_add_item(branch, hf_u3v_bootstrap_User_Defined_Name, tvb, offset, length, ENC_ASCII|ENC_NA);
}
break;
case U3V_ABRM_DEVICE_CAPABILITY:
proto_tree_add_item(branch, hf_u3v_bootstrap_Device_Capability, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_MAXIMUM_DEVICE_RESPONSE_TIME:
proto_tree_add_item(branch, hf_u3v_bootstrap_Maximum_Device_Response_Time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_MANIFEST_TABLE_ADDRESS:
proto_tree_add_item(branch, hf_u3v_bootstrap_Manifest_Table_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_SBRM_ADDRESS:
proto_tree_add_item(branch, hf_u3v_bootstrap_SBRM_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_DEVICE_CONFIGURATION:
proto_tree_add_item(branch, hf_u3v_bootstrap_Device_Configuration, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_HEARTBEAT_TIMEOUT:
proto_tree_add_item(branch, hf_u3v_bootstrap_Heartbeat_Timeout, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_MESSAGE_CHANNEL_CHANNEL_ID:
proto_tree_add_item(branch, hf_u3v_bootstrap_Message_Channel_channel_id, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_TIMESTAMP:
proto_tree_add_item(branch, hf_u3v_bootstrap_Timestamp, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_TIMESTAMP_LATCH:
proto_tree_add_item(branch, hf_u3v_bootstrap_Timestamp_Latch, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_TIMESTAMP_INCREMENT:
proto_tree_add_item(branch, hf_u3v_bootstrap_Timestamp_Increment, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_ACCESS_PRIVILEGE:
proto_tree_add_item(branch, hf_u3v_bootstrap_Access_Privilege, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_PROTOCOL_ENDIANESS:
proto_tree_add_item(branch, hf_u3v_bootstrap_Protocol_Endianess, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_ABRM_IMPLEMENTATION_ENDIANESS:
proto_tree_add_item(branch, hf_u3v_bootstrap_Implementation_Endianess, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
default:
isABRM = FALSE;
break;
}
}
if ( u3v_conv_info->sbrm_addr != 0 && (addr >= u3v_conv_info->sbrm_addr)) {
guint64 map_offset = addr - u3v_conv_info->sbrm_addr;
isSBRM = TRUE;
switch(map_offset) {
case U3V_SBRM_U3V_VERSION:
proto_tree_add_item(branch, hf_u3v_bootstrap_U3V_Version, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_U3VCP_CAPABILITY_REGISTER:
proto_tree_add_item(branch, hf_u3v_bootstrap_U3VCP_Capability_Register, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_U3VCP_CONFIGURATION_REGISTER:
proto_tree_add_item(branch, hf_u3v_bootstrap_U3VCP_Configuration_Register, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_MAXIMUM_COMMAND_TRANSFER_LENGTH:
proto_tree_add_item(branch, hf_u3v_bootstrap_Maximum_Command_Transfer_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_MAXIMUM_ACKNOWLEDGE_TRANSFER_LENGTH:
proto_tree_add_item(branch, hf_u3v_bootstrap_Maximum_Acknowledge_Transfer_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_NUMBER_OF_STREAM_CHANNELS:
proto_tree_add_item(branch, hf_u3v_bootstrap_Number_of_Stream_Channels, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_SIRM_ADDRESS:
proto_tree_add_item(branch, hf_u3v_bootstrap_SIRM_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_SIRM_LENGTH:
proto_tree_add_item(branch, hf_u3v_bootstrap_SIRM_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_EIRM_ADDRESS:
proto_tree_add_item(branch, hf_u3v_bootstrap_EIRM_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_EIRM_LENGTH:
proto_tree_add_item(branch, hf_u3v_bootstrap_EIRM_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_IIDC2_ADDRESS:
proto_tree_add_item(branch, hf_u3v_bootstrap_IIDC2_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_SBRM_CURRENT_SPEED:
proto_tree_add_item(branch, hf_u3v_bootstrap_Current_Speed, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
default:
isSBRM = FALSE;
break;
}
}
if ( u3v_conv_info->sirm_addr != 0 && (addr >= u3v_conv_info->sirm_addr)) {
guint64 map_offset = addr - u3v_conv_info->sirm_addr;
isSIRM = TRUE;
switch(map_offset) {
case U3V_SIRM_SI_INFO:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Info, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_CONTROL:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Control, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_REQUIRED_PAYLOAD_SIZE:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Required_Payload_Size, tvb, offset, 8, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_REQUIRED_LEADER_SIZE:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Required_Leader_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_REQUIRED_TRAILER_SIZE:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Required_Trailer_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_MAXIMUM_LEADER_SIZE:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Maximum_Leader_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_PAYLOAD_TRANSFER_SIZE:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Payload_Transfer_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_PAYLOAD_TRANSFER_COUNT:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Payload_Transfer_Count, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER1_SIZE:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Payload_Final_Transfer1_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER2_SIZE:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Payload_Final_Transfer2_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_SIRM_SI_MAXIMUM_TRAILER_SIZE:
proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Maximum_Trailer_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
default:
isSIRM = FALSE;
break;
}
}
if ( u3v_conv_info->eirm_addr != 0 && (addr >= u3v_conv_info->eirm_addr)) {
guint64 map_offset = addr -u3v_conv_info->eirm_addr;
isEIRM=TRUE;
switch(map_offset) {
case U3V_EIRM_EI_CONTROL:
proto_tree_add_item(branch, hf_u3v_bootstrap_EI_Control, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_EIRM_MAXIMUM_EVENT_TRANSFER_LENGTH:
proto_tree_add_item(branch, hf_u3v_bootstrap_Maximum_Event_Transfer_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case U3V_EIRM_EVENT_TEST_CONTROL:
proto_tree_add_item(branch, hf_u3v_bootstrap_Event_Test_Control, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
default:
isEIRM = FALSE;
break;
}
}
if(isABRM || isSBRM || isSIRM || isEIRM ) {
return 1;
}
return 0;
}
/*
\brief DISSECT: Read memory command
*/
static void
dissect_u3v_read_mem_cmd(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info, gencp_transaction_t * gencp_trans)
{
guint64 addr = 0;
const gchar* address_string = NULL;
gboolean is_custom_register = FALSE;
guint16 count = 0;
gint offset = startoffset;
proto_item *item = NULL;
addr = tvb_get_letoh64(tvb, offset);
gencp_trans->address = addr;
address_string = get_register_name_from_address(addr, &is_custom_register, u3v_conv_info);
count = tvb_get_letohs(tvb, offset + 10); /* Number of bytes to read from memory */
gencp_trans->count = count;
if ( 0xffffffff00000000 & addr ) {
col_append_fstr(pinfo->cinfo, COL_INFO, " (0x%016" G_GINT64_MODIFIER "X (%d) bytes) %s", addr, count, address_string);
} else {
col_append_fstr(pinfo->cinfo, COL_INFO, " (0x%08X (%d) bytes)", (guint32)addr, count);
}
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_readmem_cmd, tvb, offset, length, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd);
/* address */
if (is_known_bootstrap_register(addr, u3v_conv_info)) {
item = proto_tree_add_uint64(u3v_telegram_tree, hf_u3v_address, tvb, offset, 8, addr);
proto_item_append_text(item, " %s", address_string);
} else {
proto_tree_add_item(u3v_telegram_tree, hf_u3v_custom_memory_addr, tvb, offset, 8, ENC_LITTLE_ENDIAN);
}
offset += 8;
/* reserved field */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_reserved, tvb, offset, 2, ENC_NA);
offset += 2;
/* count */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_count, tvb, offset, 2, ENC_LITTLE_ENDIAN);
}
/*
\brief DISSECT: Write memory command
*/
static void
dissect_u3v_write_mem_cmd(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info, gencp_transaction_t *gencp_trans)
{
const gchar* address_string = NULL;
gboolean is_custom_register = FALSE;
guint64 addr = 0;
guint byte_count = 0;
proto_item *item = NULL;
guint offset = startoffset + 8;
addr = tvb_get_letoh64(tvb, startoffset);
byte_count = length - 8;
address_string = get_register_name_from_address(addr, &is_custom_register, u3v_conv_info);
gencp_trans->address = addr;
gencp_trans->count = byte_count;
/* fill in Info column in Wireshark GUI */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s: %d bytes", address_string, byte_count);
/* Subtree initialization for Payload Data: WRITEMEM_CMD */
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_writemem_cmd, tvb, startoffset, length, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd);
if (is_known_bootstrap_register(addr, u3v_conv_info)) {
item = proto_tree_add_uint64(u3v_telegram_tree, hf_u3v_address, tvb, startoffset, 8, addr);
proto_item_append_text(item, " %s", address_string);
dissect_u3v_register(addr, u3v_telegram_tree, tvb, offset, byte_count, u3v_conv_info);
} else {
proto_tree_add_item(u3v_telegram_tree, hf_u3v_custom_memory_addr, tvb, startoffset, 8, ENC_LITTLE_ENDIAN);
proto_tree_add_item(u3v_telegram_tree, hf_u3v_custom_memory_data, tvb, startoffset + 8, byte_count, ENC_NA);
}
}
/*
* \brief DISSECT: Event command
*/
static void
dissect_u3v_event_cmd(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length)
{
gint32 eventid;
gint offset = startoffset;
proto_item *item = NULL;
/* Get event ID */
eventid = tvb_get_letohs(tvb, offset + 2);
/* fill in Info column in Wireshark GUI */
col_append_fstr(pinfo->cinfo, COL_INFO, "[ID: 0x%04X]", eventid);
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_event_cmd, tvb, offset, length, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd);
offset += 2;
/* Use range to determine type of event */
if ((eventid >= 0x0000) && (eventid <= 0x8000)) {
/* Standard ID */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
} else if ((eventid >= 0x8001) && (eventid <= 0x8FFF)) {
/* Error */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_error_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
} else if ((eventid >= 0x9000) && (eventid <= 0xFFFF)) {
/* Device specific */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_device_specific_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
}
offset += 2;
/* Timestamp (64 bit) associated with event */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_timestamp, tvb, offset, 8, ENC_LITTLE_ENDIAN);
offset += 8;
/* Data */
if (length > offset ) {
proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_data, tvb, offset, length - 12, ENC_NA);
}
}
/*
\brief DISSECT: Read memory acknowledge
*/
static void
dissect_u3v_read_mem_ack(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info, gencp_transaction_t * gencp_trans)
{
guint64 addr = 0;
const gchar *address_string = NULL;
gboolean is_custom_register = FALSE;
gboolean have_address = (0 != gencp_trans->cmd_frame);
proto_item *item = NULL;
guint offset = startoffset;
guint byte_count = (length);
addr = gencp_trans->address;
dissect_u3v_register_bases(addr, tvb, startoffset, u3v_conv_info);
if (have_address) {
address_string = get_register_name_from_address(addr, &is_custom_register, u3v_conv_info);
/* Fill in Wireshark GUI Info column */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s", address_string);
}
/* Subtree initialization for Payload Data: READMEM_ACK */
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_ack_readmem_ack, tvb, startoffset, length, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd);
/* Bootstrap register known address */
if (have_address) {
item = proto_tree_add_uint64(u3v_telegram_tree, hf_u3v_address, tvb, 0,0 , addr);
PROTO_ITEM_SET_GENERATED(item);
if (is_known_bootstrap_register(addr, u3v_conv_info)) {
dissect_u3v_register(addr, u3v_telegram_tree, tvb, offset, byte_count, u3v_conv_info);
} else {
proto_tree_add_item(u3v_telegram_tree, hf_u3v_custom_memory_data, tvb, startoffset, length, ENC_NA);
}
}
}
/*
\brief DISSECT: Write memory acknowledge
*/
static void
dissect_u3v_write_mem_ack(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info , gencp_transaction_t * gencp_trans)
{
guint64 addr = 0;
gint offset = startoffset;
const gchar *address_string = NULL;
gboolean is_custom_register = FALSE;
gboolean have_address = (0 != gencp_trans->cmd_frame);
proto_item *item = NULL;
addr = gencp_trans->address;
if (have_address) {
address_string = get_register_name_from_address(addr, &is_custom_register, u3v_conv_info);
/* Fill in Wireshark GUI Info column */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s", address_string);
}
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_writemem_ack, tvb, startoffset, length, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd);
if (have_address) {
item = proto_tree_add_uint64(u3v_telegram_tree, hf_u3v_address, tvb, 0,0 , addr);
PROTO_ITEM_SET_GENERATED(item);
}
/* Number of bytes successfully written to the device register map */
if ( length == 4 ) {
/* reserved field */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_reserved, tvb, offset, 2, ENC_NA);
offset += 2;
proto_tree_add_item(u3v_telegram_tree, hf_u3v_count, tvb, offset, 2, ENC_LITTLE_ENDIAN);
}
}
/*
\brief DISSECT: Pending acknowledge
*/
static void
dissect_u3v_pending_ack(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo _U_, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info _U_, gencp_transaction_t *gencp_trans _U_)
{
proto_item *item = NULL;
guint offset = startoffset;
/* Fill in Wireshark GUI Info column */
col_append_fstr(pinfo->cinfo, COL_INFO, " %d ms", tvb_get_letohs(tvb, startoffset+2));
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_ccd_pending_ack, tvb, startoffset, length, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd);
/* reserved field */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_reserved, tvb, offset, 2, ENC_NA);
offset += 2;
proto_tree_add_item(u3v_telegram_tree, hf_u3v_time_to_completion, tvb, offset, 2, ENC_LITTLE_ENDIAN);
}
/*
\brief DISSECT: Stream Leader
*/
static void
dissect_u3v_stream_leader(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, usb_conv_info_t *usb_conv_info _U_)
{
guint32 offset = 0;
guint32 payload_type = 0;
guint64 block_id = 0;
proto_item *item = NULL;
/* Subtree initialization for Stream Leader */
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_leader, tvb, 0, -1, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_stream_leader);
/* Add the prefix code: */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_prefix, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* reserved field */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA);
offset += 2;
/* leader size */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_leader_size, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* block id */
block_id = tvb_get_letoh64(tvb, offset);
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_block_id, tvb, offset, 8, ENC_LITTLE_ENDIAN);
offset += 8;
/* reserved field */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA);
offset += 2;
/* payload type */
payload_type = tvb_get_letohs(tvb, offset);
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_payload_type, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* Add payload type to information string */
col_append_fstr(pinfo->cinfo, COL_INFO, "Stream Leader [ Block ID: %" G_GINT64_MODIFIER "u , Type %s]",
block_id,
val_to_str(payload_type, payload_type_names, "Unknown Payload Type"));
if (payload_type == U3V_STREAM_PAYLOAD_IMAGE ||
payload_type == U3V_STREAM_PAYLOAD_IMAGE_EXT_CHUNK ||
payload_type == U3V_STREAM_PAYLOAD_CHUNK) {
/* timestamp */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_timestamp, tvb, offset, 8, ENC_LITTLE_ENDIAN);
offset += 8;
}
if (payload_type == U3V_STREAM_PAYLOAD_IMAGE ||
payload_type == U3V_STREAM_PAYLOAD_IMAGE_EXT_CHUNK ) {
/* pixel format */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_pixel_format, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* size_x */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_size_x, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* size_y */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_size_y, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* offset_x */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_offset_x, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* offset_x */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_offset_y, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* padding_x */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_padding_x, tvb, offset, 2, ENC_LITTLE_ENDIAN);
/* offset += 2; */
/* reserved field */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA);
/* offset += 2; */
}
}
/*
\brief DISSECT: Stream Trailer
*/
static void
dissect_u3v_stream_trailer(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, usb_conv_info_t *usb_conv_info _U_)
{
gint offset = 0;
guint64 block_id;
proto_item *item = NULL;
/* Subtree initialization for Stream Leader */
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_trailer, tvb, 0, -1, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_stream_trailer);
/* Add the prefix code: */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_prefix, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* reserved field */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA);
offset += 2;
/* trailer size */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_trailer_size, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* block id */
block_id = tvb_get_letoh64(tvb, offset);
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_block_id, tvb, offset, 8, ENC_LITTLE_ENDIAN);
offset += 8;
/* status*/
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_status, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* reserved field */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA);
offset += 2;
/* block id */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_valid_payload_size, tvb, offset, 8, ENC_LITTLE_ENDIAN);
offset += 8;
/* Add payload type to information string */
col_append_fstr(pinfo->cinfo, COL_INFO, "Stream Trailer [ Block ID: %" G_GINT64_MODIFIER "u]", block_id);
if (tvb_captured_length_remaining(tvb,offset) >=4 ) {
/* size_y */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_size_y, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
}
if (tvb_captured_length_remaining(tvb,offset) >=4 ) {
/* chunk layout id */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_chunk_layout_id, tvb, offset, 4, ENC_LITTLE_ENDIAN);
/* offset += 4; */
}
}
/*
\brief DISSECT: Stream Payload
*/
static void
dissect_u3v_stream_payload(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, usb_conv_info_t *usb_conv_info _U_)
{
proto_item *item = NULL;
/* Subtree initialization for Stream Leader */
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_payload, tvb, 0, -1, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_stream_payload);
/* Data */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_data, tvb, 0, -1, ENC_NA);
/* Add payload type to information string */
col_append_fstr(pinfo->cinfo, COL_INFO, "Stream Payload");
}
/*
\brief Point of entry of all U3V packet dissection
*/
static int
dissect_u3v(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
gint offset = 0;
proto_tree *u3v_tree = NULL, *ccd_tree_flag, *u3v_telegram_tree = NULL, *ccd_tree = NULL;
gint data_length = 0;
gint req_id = 0;
gint command_id = -1;
gint status = 0;
guint prefix = 0;
proto_item *ti = NULL;
proto_item *item = NULL;
const char *command_string;
usb_conv_info_t *usb_conv_info;
gint stream_detected = FALSE;
gint control_detected = FALSE;
u3v_conv_info_t *u3v_conv_info = NULL;
gencp_transaction_t *gencp_trans = NULL;
usb_conv_info = (usb_conv_info_t *)data;
/* decide if this packet belongs to U3V protocol */
u3v_conv_info = (u3v_conv_info_t *)usb_conv_info->class_data;
if (!u3v_conv_info) {
u3v_conv_info = wmem_new0(wmem_file_scope(), u3v_conv_info_t);
usb_conv_info->class_data = u3v_conv_info;
usb_conv_info->class_data_type = USB_CONV_U3V;
} else if (usb_conv_info->class_data_type != USB_CONV_U3V) {
/* Don't dissect if another USB type is in the conversation */
return 0;
}
prefix = tvb_get_letohl(tvb, 0);
if ((tvb_reported_length(tvb) >= 4) && ( ( U3V_CONTROL_PREFIX == prefix ) || ( U3V_EVENT_PREFIX == prefix ) ) ) {
control_detected = TRUE;
}
if (((tvb_reported_length(tvb) >= 4) && (( U3V_STREAM_LEADER_PREFIX == prefix ) || ( U3V_STREAM_TRAILER_PREFIX == prefix )))
|| (usb_conv_info->endpoint == u3v_conv_info->ep_stream)) {
stream_detected = TRUE;
}
/* initialize interface class/subclass in case no descriptors have been dissected yet */
if ( control_detected || stream_detected){
if ( usb_conv_info->interfaceClass == IF_CLASS_UNKNOWN &&
usb_conv_info->interfaceSubclass == IF_SUBCLASS_UNKNOWN){
usb_conv_info->interfaceClass = IF_CLASS_MISCELLANEOUS;
usb_conv_info->interfaceSubclass = IF_SUBCLASS_MISC_U3V;
}
}
if ( control_detected ) {
/* Set the protocol column */
col_set_str(pinfo->cinfo, COL_PROTOCOL, "U3V");
/* Clear out stuff in the info column */
col_clear(pinfo->cinfo, COL_INFO);
/* Adds "USB3Vision" heading to protocol tree */
/* We will add fields to this using the u3v_tree pointer */
ti = proto_tree_add_item(tree, proto_u3v, tvb, offset, -1, ENC_NA);
u3v_tree = proto_item_add_subtree(ti, ett_u3v);
prefix = tvb_get_letohl(tvb, offset);
command_id = tvb_get_letohs(tvb, offset+6);
/* decode CCD ( DCI/DCE command data layout) */
if ((prefix == U3V_CONTROL_PREFIX || prefix == U3V_EVENT_PREFIX) && ((command_id % 2) == 0)) {
command_string = val_to_str(command_id,command_names,"Unknown Command (0x%x)");
item = proto_tree_add_item(u3v_tree, hf_u3v_ccd_cmd, tvb, offset, 8, ENC_NA);
proto_item_append_text(item, ": %s", command_string);
ccd_tree = proto_item_add_subtree(item, ett_u3v_cmd);
/* Add the prefix code: */
proto_tree_add_item(ccd_tree, hf_u3v_gencp_prefix, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* Add the flags */
item = proto_tree_add_item(ccd_tree, hf_u3v_flag, tvb, offset, 2, ENC_LITTLE_ENDIAN);
ccd_tree_flag = proto_item_add_subtree(item, ett_u3v_flags);
proto_tree_add_item(ccd_tree_flag, hf_u3v_acknowledge_required_flag, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
col_append_fstr(pinfo->cinfo, COL_INFO, "> %s ", command_string);
} else if (prefix == U3V_CONTROL_PREFIX && ((command_id % 2) == 1)) {
command_string = val_to_str(command_id,command_names,"Unknown Acknowledge (0x%x)");
item = proto_tree_add_item(u3v_tree, hf_u3v_ccd_ack, tvb, offset, 8, ENC_NA);
proto_item_append_text(item, ": %s", command_string);
ccd_tree = proto_item_add_subtree(item, ett_u3v_ack);
/* Add the prefix code: */
proto_tree_add_item(ccd_tree, hf_u3v_gencp_prefix, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* Add the status: */
proto_tree_add_item(ccd_tree, hf_u3v_status, tvb, offset, 2,ENC_LITTLE_ENDIAN);
status = tvb_get_letohs(tvb, offset);
offset += 2;
col_append_fstr(pinfo->cinfo, COL_INFO, "< %s %s",
command_string,
val_to_str(status, status_names_short, "Unknown status (0x%04X)"));
} else {
return 0;
}
/* Add the command id*/
proto_tree_add_item(ccd_tree, hf_u3v_command_id, tvb, offset, 2,ENC_LITTLE_ENDIAN);
offset += 2;
/* Parse the second part of both the command and the acknowledge header:
0 15 16 31
-------- -------- -------- --------
| status | acknowledge |
-------- -------- -------- --------
| length | req_id |
-------- -------- -------- --------
Add the data length
Number of valid data bytes in this message, not including this header. This
represents the number of bytes of payload appended after this header */
proto_tree_add_item(ccd_tree, hf_u3v_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
data_length = tvb_get_letohs(tvb, offset);
offset += 2;
/* Add the request ID */
proto_tree_add_item(ccd_tree, hf_u3v_request_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
req_id = tvb_get_letohs(tvb, offset);
offset += 2;
/* Add telegram subtree */
u3v_telegram_tree = proto_item_add_subtree(u3v_tree, ett_u3v);
if (!PINFO_FD_VISITED(pinfo)) {
if ((command_id % 2) == 0) {
/* This is a command */
gencp_trans = wmem_new(wmem_file_scope(), gencp_transaction_t);
gencp_trans->cmd_frame = pinfo->fd->num;
gencp_trans->ack_frame = 0;
gencp_trans->cmd_time = pinfo->fd->abs_ts;
/* add reference to current packet */
p_add_proto_data(wmem_file_scope(), pinfo, proto_u3v, req_id, gencp_trans);
/* add reference to current */
u3v_conv_info->trans_info = gencp_trans;
} else {
gencp_trans = u3v_conv_info->trans_info;
if (gencp_trans) {
gencp_trans->ack_frame = pinfo->fd->num;
/* add reference to current packet */
p_add_proto_data(wmem_file_scope(), pinfo, proto_u3v, req_id, gencp_trans);
}
}
} else {
gencp_trans = (gencp_transaction_t*)p_get_proto_data(wmem_file_scope(),pinfo, proto_u3v, req_id);
}
if (!gencp_trans) {
/* create a "fake" gencp_trans structure */
gencp_trans = wmem_new(wmem_packet_scope(), gencp_transaction_t);
gencp_trans->cmd_frame = 0;
gencp_trans->ack_frame = 0;
gencp_trans->cmd_time = pinfo->fd->abs_ts;
}
/* dissect depending on command? */
switch (command_id) {
case U3V_READMEM_CMD:
dissect_u3v_read_mem_cmd(u3v_telegram_tree, tvb, pinfo, offset, data_length,u3v_conv_info,gencp_trans);
break;
case U3V_WRITEMEM_CMD:
dissect_u3v_write_mem_cmd(u3v_telegram_tree, tvb, pinfo, offset, data_length,u3v_conv_info,gencp_trans);
break;
case U3V_EVENT_CMD:
dissect_u3v_event_cmd(u3v_telegram_tree, tvb, pinfo, offset, data_length);
break;
case U3V_READMEM_ACK:
if ( U3V_STATUS_GENCP_SUCCESS == status ) {
dissect_u3v_read_mem_ack(u3v_telegram_tree, tvb, pinfo, offset, data_length,u3v_conv_info,gencp_trans);
}
break;
case U3V_WRITEMEM_ACK:
dissect_u3v_write_mem_ack(u3v_telegram_tree, tvb, pinfo, offset, data_length, u3v_conv_info,gencp_trans);
break;
case U3V_PENDING_ACK:
dissect_u3v_pending_ack(u3v_telegram_tree, tvb, pinfo, offset, data_length, u3v_conv_info,gencp_trans);
break;
default:
proto_tree_add_item(u3v_telegram_tree, hf_u3v_payloaddata, tvb, offset, data_length, ENC_NA);
break;
}
return data_length + 12;
} else if ( stream_detected ) {
/* this is streaming data */
/* init this stream configuration */
u3v_conv_info = (u3v_conv_info_t *)usb_conv_info->class_data;
u3v_conv_info->ep_stream = usb_conv_info->endpoint;
/* Set the protocol column */
col_set_str(pinfo->cinfo, COL_PROTOCOL, "U3V");
/* Clear out stuff in the info column */
col_clear(pinfo->cinfo, COL_INFO);
/* Adds "USB3Vision" heading to protocol tree */
/* We will add fields to this using the u3v_tree pointer */
ti = proto_tree_add_item(tree, proto_u3v, tvb, offset, -1, ENC_NA);
u3v_tree = proto_item_add_subtree(ti, ett_u3v);
if(tvb_captured_length(tvb) >=4) {
prefix = tvb_get_letohl(tvb, offset);
switch (prefix) {
case U3V_STREAM_LEADER_PREFIX:
dissect_u3v_stream_leader(u3v_tree, tvb, pinfo, usb_conv_info);
break;
case U3V_STREAM_TRAILER_PREFIX:
dissect_u3v_stream_trailer(u3v_tree, tvb, pinfo, usb_conv_info);
break;
default:
dissect_u3v_stream_payload(u3v_tree, tvb, pinfo, usb_conv_info);
break;
}
}
return tvb_captured_length(tvb);
}
return 0;
}
static gboolean
dissect_u3v_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
guint32 prefix;
usb_conv_info_t *usb_conv_info;
/* all control and meta data packets of U3V contain at least the prefix */
if (tvb_reported_length(tvb) < 4)
return FALSE;
prefix = tvb_get_letohl(tvb, 0);
/* check if stream endpoint has been already set up for this conversation */
usb_conv_info = (usb_conv_info_t *)data;
if (!usb_conv_info)
return FALSE;
/* either right prefix or the endpoint of the interface descriptor
set the correct class and subclass */
if ((U3V_STREAM_LEADER_PREFIX == prefix) || (U3V_STREAM_TRAILER_PREFIX == prefix) ||
(U3V_CONTROL_PREFIX == prefix) || (U3V_EVENT_PREFIX == prefix) ||
((usb_conv_info->interfaceClass == IF_CLASS_MISCELLANEOUS &&
usb_conv_info->interfaceSubclass == IF_SUBCLASS_MISC_U3V))) {
dissect_u3v(tvb, pinfo, tree, data);
return TRUE;
}
return FALSE;
}
static gint
dissect_u3v_descriptors(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, void *data _U_)
{
guint8 type;
gint offset = 0;
proto_item * ti;
proto_tree * sub_tree;
guint32 version;
/* The descriptor must at least have a length and type field. */
if (tvb_reported_length(tvb) < 2) {
return 0;
}
/* skip len */
type = tvb_get_guint8(tvb, 1);
/* Check for U3V device info descriptor. */
if (type != DESCRIPTOR_TYPE_U3V_INTERFACE) {
return 0;
}
ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor);
/* bLength */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bLength, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* bDescriptorType */
ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bDescriptorType, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_item_append_text(ti, " (U3V INTERFACE)");
offset++;
/* bDescriptorSubtype */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bDescriptorSubtype, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* bGenCPVersion */
if (!tvb_bytes_exist(tvb, offset, 4)) {
/* Version not completely in buffer -> break dissection here. */
return offset;
}
version = tvb_get_letohl(tvb, offset);
ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bGenCPVersion, tvb, offset, 4, ENC_NA);
proto_item_append_text(ti, ": %u.%u", version >> 16, version & 0xFFFF);
sub_tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor_gencp_version);
proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bGenCPVersion_minor, tvb, offset, 4, ENC_LITTLE_ENDIAN);
proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bGenCPVersion_major, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* bU3VVersion */
if (!tvb_bytes_exist(tvb, offset, 4)) {
/* Version not completely in buffer -> break dissection here. */
return offset;
}
version = tvb_get_letohl(tvb, offset);
ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bU3VVersion, tvb, offset, 4, ENC_NA);
proto_item_append_text(ti, ": %u.%u", version >> 16, version & 0xFFFF);
sub_tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor_u3v_version);
proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bU3VVersion_minor, tvb, offset, 4, ENC_LITTLE_ENDIAN);
proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bU3VVersion_major, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* iDeviceGUID */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iDeviceGUID, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iVendorName */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iVendorName, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iModelName */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iModelName, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iFamilyName */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iFamilyName, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iDeviceVersion */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iDeviceVersion, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iManufacturerInfo */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iManufacturerInfo, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iSerialNumber */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iSerialNumber, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iUserDefinedName */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iUserDefinedName, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* bmSpeedSupport */
proto_tree_add_bitmask(tree, tvb, offset, hf_u3v_device_info_descriptor_bmSpeedSupport,
ett_u3v_device_info_descriptor_speed_support, speed_support_fields, ENC_LITTLE_ENDIAN);
offset++;
return offset;
}
/*
\brief Structures for register dissection
*/
static hf_register_info hf[] =
{
/* Common U3V data */
{ &hf_u3v_gencp_prefix,
{ "Prefix", "u3v.gencp.prefix",
FT_UINT8, BASE_HEX, NULL, 0x0,
"U3V GenCP Prefix", HFILL
} },
{ &hf_u3v_flag,
{ "Flags", "u3v.gencp.flags",
FT_UINT16, BASE_HEX, NULL, 0x0,
"U3V Flags", HFILL
} },
{ &hf_u3v_acknowledge_required_flag,
{ "Acknowledge Required", "u3v.gencp.flag.acq_required",
FT_BOOLEAN, 16, NULL, 0x4000,
"U3V Acknowledge Required", HFILL
} },
{ &hf_u3v_command_id,
{ "Command", "u3v.gencp.command_id",
FT_UINT16, BASE_HEX, VALS( command_names ), 0x0,
"U3V Command", HFILL
} },
{ &hf_u3v_length,
{ "Payload Length", "u3v.gencp.payloadlength",
FT_UINT16, BASE_HEX_DEC, NULL, 0x0,
"U3V Payload Length", HFILL
} },
{ &hf_u3v_request_id,
{ "Request ID", "u3v.gencp.req_id",
FT_UINT16, BASE_HEX, NULL, 0x0,
"U3V Request ID", HFILL
} },
{ &hf_u3v_payloaddata,
{ "Payload Data", "u3v.gencp.payloaddata",
FT_BYTES, BASE_NONE, NULL, 0x0,
"U3V Payload", HFILL
} },
{ &hf_u3v_status,
{ "Status", "u3v.gencp.status",
FT_UINT16, BASE_HEX, VALS( status_names ), 0x0,
"U3V Status", HFILL
} },
/* Read memory */
{ &hf_u3v_address,
{ "Address", "u3v.gencp.address",
FT_UINT64, BASE_HEX, NULL, 0x0,
"U3V Address", HFILL } },
{ &hf_u3v_count,
{ "Count", "u3v.gencp.count",
FT_UINT16, BASE_HEX_DEC, NULL, 0x0,
"U3V Count", HFILL
} },
/* Event */
{ &hf_u3v_eventcmd_id,
{ "ID", "u3v.cmd.event.id",
FT_UINT16, BASE_HEX_DEC, VALS( event_id_names ), 0x0,
"U3V Event ID", HFILL
} },
{ &hf_u3v_eventcmd_error_id,
{ "Error ID", "u3v.cmd.event.errorid",
FT_UINT16, BASE_HEX_DEC, NULL, 0x0,
"U3V Event Error ID", HFILL
} },
{ &hf_u3v_eventcmd_device_specific_id,
{ "Device Specific ID", "u3v.cmd.event.devicespecificid",
FT_UINT16, BASE_HEX_DEC, NULL, 0x0,
"U3V Event Device Specific ID", HFILL
} },
{ &hf_u3v_eventcmd_timestamp,
{ "Timestamp", "u3v.cmd.event.timestamp",
FT_UINT64, BASE_HEX_DEC, NULL, 0x0,
"U3V Event Timestamp", HFILL
} },
{ &hf_u3v_eventcmd_data,
{ "Data", "u3v.cmd.event.data",
FT_BYTES, BASE_NONE, NULL, 0x0,
"U3V Event Data", HFILL
} },
/* Pending acknowledge */
{ &hf_u3v_time_to_completion,
{ "Time to completion", "u3v.gencp.timetocompletion",
FT_UINT16, BASE_DEC, NULL, 0x0,
"U3V Time to completion [ms]", HFILL
} },
{ &hf_u3v_reserved,
{ "Reserved", "u3v.reserved",
FT_BYTES, BASE_NONE, NULL, 0,
NULL, HFILL
} },
/* Custom */
{ &hf_u3v_custom_memory_addr,
{ "Custom Memory Address", "u3v.gencp.custom_addr",
FT_UINT64, BASE_HEX, NULL, 0x0,
"U3V Custom Memory Address", HFILL
} },
{ &hf_u3v_custom_memory_data,
{ "Custom Memory Data", "u3v.gencp.custom_data",
FT_BYTES, BASE_NONE, NULL, 0x0,
"U3V Custom Memory Data", HFILL
} },
/* Bootstrap Defines */
{ &hf_u3v_bootstrap_GenCP_Version,
{ "GenCP Version", "u3v.bootstrap.GenCP_Version",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Complying GenCP Version", HFILL
} },
{ &hf_u3v_bootstrap_Manufacturer_Name,
{ "Manufacturer Name", "u3v.bootstrap.Manufacturer_Name",
FT_STRING, BASE_NONE, NULL, 0x0,
"String containing the self-describing name of the manufacturer", HFILL
} },
{ &hf_u3v_bootstrap_Model_Name,
{ "Model Name", "u3v.bootstrap.Model_Name",
FT_STRING, BASE_NONE, NULL, 0x0,
"String containing the self-describing name of the device model", HFILL
} },
{ &hf_u3v_bootstrap_Family_Name,
{ "Family Name", "u3v.bootstrap.Family_Name",
FT_STRING, BASE_NONE, NULL, 0x0,
"String containing the name of the family of this device", HFILL
} },
{ &hf_u3v_bootstrap_Device_Version,
{ "Device Version", "u3v.bootstrap.Device_Version",
FT_STRING, BASE_NONE, NULL, 0x0,
"String containing the version of this device", HFILL
} },
{ &hf_u3v_bootstrap_Manufacturer_Info,
{ "Manufacturer Information", "u3v.bootstrap.Manufacturer_Info",
FT_STRING, BASE_NONE, NULL, 0x0,
"String containing additional manufacturer information", HFILL
} },
{ &hf_u3v_bootstrap_Serial_Number,
{ "Serial Number", "u3v.bootstrap.Serial_Number",
FT_STRING, BASE_NONE, NULL, 0x0,
"String containing the serial number of the device", HFILL
} },
{ &hf_u3v_bootstrap_User_Defined_Name,
{ "User Defined Name", "u3v.bootstrap.User_Defined_Name",
FT_STRING, BASE_NONE, NULL, 0x0,
"String containing the user defined name of the device", HFILL
} },
{ &hf_u3v_bootstrap_Device_Capability,
{ "Device Capabilities", "u3v.bootstrap.Device_Capability",
FT_UINT64, BASE_DEC, NULL, 0x0,
"Bit field describing the device?s capabilities", HFILL
} },
{ &hf_u3v_bootstrap_Maximum_Device_Response_Time,
{ "Device Maximum response time in ms", "u3v.bootstrap.Maximum_Device_Response_Time",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Maximum response time in ms", HFILL
} },
{ &hf_u3v_bootstrap_Manifest_Table_Address,
{ "Pointer to the Manifest Table", "u3v.bootstrap.Manifest_Table_Address",
FT_UINT64, BASE_HEX, NULL, 0x0,
NULL, HFILL
} },
{ &hf_u3v_bootstrap_SBRM_Address,
{ "Pointer to the SBRM", "u3v.bootstrap.SBRM_Address",
FT_UINT64, BASE_HEX, NULL, 0x0,
"Pointer to the Technology Specific Bootstrap Register Map", HFILL
} },
{ &hf_u3v_bootstrap_Device_Configuration,
{ "Device Configuration", "u3v.bootstrap.Device_Configuration",
FT_UINT64, BASE_DEC, NULL, 0x0,
"Bit field describing the device?s configuration", HFILL
} },
{ &hf_u3v_bootstrap_Heartbeat_Timeout,
{ "Heartbeat Timeout in ms.", "u3v.bootstrap.Heartbeat_Timeout",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Heartbeat Timeout in ms. Not used for these specification.", HFILL
} },
{ &hf_u3v_bootstrap_Message_Channel_channel_id,
{ "Message channel id", "u3v.bootstrap.Message_Channel_channel_id",
FT_UINT32, BASE_DEC, NULL, 0x0,
"channel_id use for the message channel", HFILL
} },
{ &hf_u3v_bootstrap_Timestamp,
{ "Timestamp", "u3v.bootstrap.Timestamp",
FT_UINT64, BASE_DEC, NULL, 0x0,
"Current device time in ns", HFILL
} },
{ &hf_u3v_bootstrap_Timestamp_Latch,
{ "Latch Timestamp", "u3v.bootstrap.Timestamp_Latch",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Timestamp Latch", HFILL
} },
{ &hf_u3v_bootstrap_Timestamp_Increment,
{ "Timestamp Increment Value", "u3v.bootstrap.Timestamp_Increment",
FT_UINT64, BASE_DEC, NULL, 0x0,
"Timestamp Increment", HFILL
} },
{ &hf_u3v_bootstrap_Access_Privilege,
{ "Access Privilege.", "u3v.bootstrap.Access_Privilege",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Access Privilege. Not used for these specification.", HFILL
} },
{ &hf_u3v_bootstrap_Protocol_Endianess,
{ "Protocol Endianess", "u3v.bootstrap.Protocol_Endianess",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Endianess of protocol fields and bootstrap registers. Only little endian is supported by these specification.", HFILL
} },
{ &hf_u3v_bootstrap_Implementation_Endianess,
{ "Device Endianess", "u3v.bootstrap.Implementation_Endianess",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Endianess of device implementation registers. Only little endian is supported by these specification.", HFILL
} },
{ &hf_u3v_bootstrap_U3V_Version,
{ "TL Version", "u3v.bootstrap.U3V_Version",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Version of the TL specification", HFILL
} },
{ &hf_u3v_bootstrap_U3VCP_Capability_Register,
{ "Control channel capabilities", "u3v.bootstrap.U3VCP_Capability_Register",
FT_UINT64, BASE_DEC, NULL, 0x0,
"Indicates additional features on the control channel", HFILL
} },
{ &hf_u3v_bootstrap_U3VCP_Configuration_Register,
{ "Control channel configuration", "u3v.bootstrap.U3VCP_Configuration_Register",
FT_UINT64, BASE_DEC, NULL, 0x0,
"Configures additional features on the control channel", HFILL
} },
{ &hf_u3v_bootstrap_Maximum_Command_Transfer_Length,
{ "Maximum Command Transfer Length", "u3v.bootstrap.Maximum_Command_Transfer_Length",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Specifies the maximum supported command transfer length of the device", HFILL
} },
{ &hf_u3v_bootstrap_Maximum_Acknowledge_Transfer_Length,
{ "Maximum Acknowledge Transfer Length", "u3v.bootstrap.Maximum_Acknowledge_Transfer_Length",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Specifies the maximum supported acknowledge transfer length of the device", HFILL
} },
{ &hf_u3v_bootstrap_Number_of_Stream_Channels,
{ "Number of Stream Channels", "u3v.bootstrap.Number_of_Stream_Channels",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Number of Stream Channels and its corresponding Streaming Interface Register Maps (SIRM)", HFILL
} },
{ &hf_u3v_bootstrap_SIRM_Address,
{ "Pointer to the first SIRM", "u3v.bootstrap.SIRM_Address",
FT_UINT64, BASE_HEX, NULL, 0x0,
"Pointer to the first Streaming Interface Register Map.", HFILL
} },
{ &hf_u3v_bootstrap_SIRM_Length,
{ "Length of SIRM", "u3v.bootstrap.SIRM_Length",
FT_UINT32, BASE_HEX, NULL, 0x0,
"Specifies the length of each SIRM", HFILL
} },
{ &hf_u3v_bootstrap_EIRM_Address,
{ "Pointer to the EIRM", "u3v.bootstrap.EIRM_Address",
FT_UINT64, BASE_HEX, NULL, 0x0,
"Pointer to the Event Interface Register Map.", HFILL
} },
{ &hf_u3v_bootstrap_EIRM_Length,
{ "Length of EIRM", "u3v.bootstrap.EIRM_Length",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Specifies the length of the EIRM", HFILL
} },
{ &hf_u3v_bootstrap_IIDC2_Address,
{ "Pointer to the IIDC2", "u3v.bootstrap.IIDC2_Address",
FT_UINT64, BASE_HEX, NULL, 0x0,
"Pointer to the IIDC2 register set.", HFILL
} },
{ &hf_u3v_bootstrap_Current_Speed,
{ "LinkSpeed", "u3v.bootstrap.Current_Speed",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Specifies the current speed of the USB link.", HFILL
} },
{ &hf_u3v_bootstrap_SI_Info,
{ "Stream Info", "u3v.bootstrap.SI_Info",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Device reports information about stream interface", HFILL
} },
{ &hf_u3v_bootstrap_SI_Control,
{ "Stream Control", "u3v.bootstrap.SI_Control",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Stream interface Operation Control", HFILL
} },
{ &hf_u3v_bootstrap_SI_Required_Payload_Size,
{ "Stream Max Required Payload Size", "u3v.bootstrap.SI_Required_Payload_Size",
FT_UINT64, BASE_DEC, NULL, 0x0,
"Device reports maximum payload size with current settings", HFILL
} },
{ &hf_u3v_bootstrap_SI_Required_Leader_Size,
{ "Stream Max Required Leader Size", "u3v.bootstrap.SI_Required_Leader_Size",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Device reports maximum leader size it will use", HFILL
} },
{ &hf_u3v_bootstrap_SI_Required_Trailer_Size,
{ "Stream Max Required Trailer Size", "u3v.bootstrap.SI_Required_Trailer_Size",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Device reports maximum trailer size it will use", HFILL
} },
{ &hf_u3v_bootstrap_SI_Maximum_Leader_Size,
{ "Stream Max leader size", "u3v.bootstrap.SI_Maximum_Leader_Size",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Maximum leader size", HFILL
} },
{ &hf_u3v_bootstrap_SI_Payload_Transfer_Size,
{ "Stream transfer size", "u3v.bootstrap.SI_Payload_Transfer_Size",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Expected Size of a single Payload Transfer", HFILL
} },
{ &hf_u3v_bootstrap_SI_Payload_Transfer_Count,
{ "Stream transfer count", "u3v.bootstrap.SI_Payload_Transfer_Count",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Expected Number of Payload Transfers", HFILL
} },
{ &hf_u3v_bootstrap_SI_Payload_Final_Transfer1_Size,
{ "Stream final transfer 1 size", "u3v.bootstrap.SI_Payload_Final_Transfer1_Size",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Size of first final Payload transfer", HFILL
} },
{ &hf_u3v_bootstrap_SI_Payload_Final_Transfer2_Size,
{ "Stream final transfer 2 size", "u3v.bootstrap.SI_Payload_Final_Transfer2_Size",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Size of second final Payload transfer", HFILL
} },
{ &hf_u3v_bootstrap_SI_Maximum_Trailer_Size,
{ "Stream Max trailer size", "u3v.bootstrap.SI_Maximum_Trailer_Size",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Maximum trailer size", HFILL
} },
{ &hf_u3v_bootstrap_EI_Control,
{ "Event Interface Control", "u3v.bootstrap.EI_Control",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Event Interface Control Register", HFILL
} },
{ &hf_u3v_bootstrap_Maximum_Event_Transfer_Length,
{ "Event max Transfer size", "u3v.bootstrap.Maximum_Event_Transfer_Length",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Specifies the maximum supported event command transfer length of the device.", HFILL
} },
{ &hf_u3v_bootstrap_Event_Test_Control,
{ "Event test event control", "u3v.bootstrap.Event_Test_Control",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Control the generation of test events.", HFILL
} },
{ &hf_u3v_stream_prefix,
{ "Stream Prefix", "u3v.stream.prefix",
FT_UINT32, BASE_HEX, NULL, 0,
"U3V stream prefix", HFILL
} },
{ &hf_u3v_stream_reserved,
{ "Reserved", "u3v.stream.reserved",
FT_BYTES, BASE_NONE, NULL, 0,
NULL, HFILL
} },
{ &hf_u3v_stream_leader_size,
{ "Leader Size", "u3v.stream.leader_size",
FT_UINT16, BASE_DEC, NULL, 0x0,
"U3V stream leader size", HFILL
} },
{ &hf_u3v_stream_trailer_size,
{ "Trailer Size", "u3v.stream.trailer_size",
FT_UINT16, BASE_DEC, NULL, 0x0,
"U3V stream trailer size", HFILL
} },
{ &hf_u3v_stream_block_id,
{ "Block ID", "u3v.stream.block_id",
FT_UINT64, BASE_DEC, NULL, 0x0,
"U3V stream block id", HFILL
} },
{ &hf_u3v_stream_payload_type,
{ "Payload Type", "u3v.stream.payload_type",
FT_UINT16, BASE_HEX, VALS( payload_type_names ), 0x0,
"U3V Payload Type", HFILL
} },
{ &hf_u3v_stream_timestamp,
{ "Timestamp", "u3v.stream.timestamp",
FT_UINT64, BASE_HEX_DEC, NULL, 0x0,
"U3V Stream Timestamp", HFILL
} },
{ &hf_u3v_stream_pixel_format,
{ "Pixel Format", "u3v.stream.pixel_format",
FT_UINT32, BASE_HEX|BASE_EXT_STRING, VALS_EXT_PTR( &pixel_format_names_ext ), 0x0,
"U3V Stream Pixel Format", HFILL
} },
{ &hf_u3v_stream_size_x,
{ "Size X", "u3v.stream.sizex",
FT_UINT32, BASE_DEC, NULL, 0x0,
"U3V Stream Size X", HFILL
} },
{ &hf_u3v_stream_size_y,
{ "Size Y", "u3v.stream.sizey",
FT_UINT32, BASE_DEC, NULL, 0x0,
"U3V Stream Size Y", HFILL
} },
{ &hf_u3v_stream_offset_x,
{ "Offset X", "u3v.stream.offsetx",
FT_UINT32, BASE_DEC, NULL, 0x0,
"U3V Stream Offset X", HFILL
} },
{ &hf_u3v_stream_offset_y,
{ "Offset Y", "u3v.stream.offsety",
FT_UINT32, BASE_DEC, NULL, 0x0,
"U3V Stream Offset Y", HFILL
} },
{ &hf_u3v_stream_padding_x,
{ "Padding X", "u3v.stream.paddingx",
FT_UINT16, BASE_DEC, NULL, 0x0,
"U3V Stream Padding X", HFILL
} },
{ &hf_u3v_stream_chunk_layout_id,
{ "Chunk Layout ID", "u3v.stream.chunk_layout_id",
FT_UINT32, BASE_HEX, NULL, 0x0,
"U3V Stream Chunk Layout ID", HFILL
} },
{ &hf_u3v_stream_valid_payload_size,
{ "Valid Payload Size", "u3v.stream.valid_payload_size",
FT_UINT64, BASE_HEX, NULL, 0x0,
"U3V Stream Valid Payload Size", HFILL
} },
{ &hf_u3v_stream_status,
{ "Status", "u3v.stream.status",
FT_UINT16, BASE_HEX, VALS( status_names ), 0x0,
"U3V Stream Status", HFILL
} },
{ &hf_u3v_stream_data,
{ "Payload Data", "u3v.stream.data",
FT_BYTES, BASE_NONE, NULL, 0x0,
"U3V Stream Payload Data", HFILL
} },
/* U3V device info descriptor */
{ &hf_u3v_device_info_descriptor_bLength,
{ "bLength", "u3v.device_info.bLength",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bDescriptorType,
{ "bDescriptorType", "u3v.device_info.bDescriptorType",
FT_UINT8, BASE_HEX, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bDescriptorSubtype,
{ "bDescriptorSubtype", "u3v.device_info.bDescriptorSubtype",
FT_UINT8, BASE_HEX, VALS( u3v_descriptor_subtypes ), 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bGenCPVersion,
{ "bGenCPVersion", "u3v.device_info.bGenCPVersion",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bGenCPVersion_minor,
{ "Minor Version", "u3v.device_info.bGenCPVersion.minor",
FT_UINT32, BASE_DEC, NULL, 0x0000FFFF,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bGenCPVersion_major,
{ "Major Version", "u3v.device_info.bGenCPVersion.major",
FT_UINT32, BASE_DEC, NULL, 0xFFFF0000,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bU3VVersion,
{ "bU3VVersion", "u3v.device_info.bU3VVersion",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bU3VVersion_minor,
{ "Minor Version", "u3v.device_info.bU3VVersion.minor",
FT_UINT32, BASE_DEC, NULL, 0x0000FFFF,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bU3VVersion_major,
{ "Major Version", "u3v.device_info.bU3VVersion.major",
FT_UINT32, BASE_DEC, NULL, 0xFFFF0000,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_iDeviceGUID,
{ "iDeviceGUID", "u3v.device_info.iDeviceGUID",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_iVendorName,
{ "iVendorName", "u3v.device_info.iVendorName",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_iModelName,
{ "iModelName", "u3v.device_info.iModelName",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_iFamilyName,
{ "iFamilyName", "u3v.device_info.iFamilyName",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_iDeviceVersion,
{ "iDeviceVersion", "u3v.device_info.iDeviceVersion",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_iManufacturerInfo,
{ "iManufacturerInfo", "u3v.device_info.iManufacturerInfo",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_iSerialNumber,
{ "iSerialNumber", "u3v.device_info.iSerialNumber",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_iUserDefinedName,
{ "iVendorName", "u3v.device_info.iUserDefinedName",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bmSpeedSupport,
{ "bmSpeedSupport", "u3v.device_info.bmSpeedSupport",
FT_UINT8, BASE_HEX, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bmSpeedSupport_low_speed,
{ "Low-Speed", "u3v.device_info.bmSpeedSupport.lowSpeed",
FT_BOOLEAN, 8, TFS(&tfs_supported_not_supported), 0x01,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bmSpeedSupport_full_speed,
{ "Full-Speed", "u3v.device_info.bmSpeedSupport.fullSpeed",
FT_BOOLEAN, 8, TFS(&tfs_supported_not_supported), 0x02,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bmSpeedSupport_high_speed,
{ "High-Speed", "u3v.device_info.bmSpeedSupport.highSpeed",
FT_BOOLEAN, 8, TFS(&tfs_supported_not_supported), 0x04,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bmSpeedSupport_super_speed,
{ "Super-Speed", "u3v.device_info.bmSpeedSupport.superSpeed",
FT_BOOLEAN, 8, TFS(&tfs_supported_not_supported), 0x08,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor_bmSpeedSupport_reserved,
{ "Reserved", "u3v.device_info.bmSpeedSupport.reserved",
FT_UINT8, BASE_HEX, NULL, 0xF0,
NULL, HFILL } },
{ &hf_u3v_scd_readmem_cmd,
{ "SCD: READMEM_CMD", "u3v.scd_readmem_cmd",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_scd_writemem_cmd,
{ "SCD: WRITEMEM_CMD", "u3v.scd_writemem_cmd",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_scd_event_cmd,
{ "SCD: EVENT_CMD", "u3v.scd_event_cmd",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_scd_ack_readmem_ack,
{ "SCD: READMEM_ACK", "u3v.scd_ack_readmem_ack",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_scd_writemem_ack,
{ "SCD: WRITEMEM_ACK", "u3v.scd_writemem_ack",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_ccd_pending_ack,
{ "CCD: PENDING_ACK", "u3v.ccd_pending_ack",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_stream_leader,
{ "Stream: Leader", "u3v.stream_leader",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_stream_trailer,
{ "Stream: Trailer", "u3v.stream_trailer",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_stream_payload,
{ "Stream: Payload", "u3v.stream_payload",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_ccd_cmd,
{ "CCD", "u3v.ccd_cmd",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_ccd_ack,
{ "CCD", "u3v.ccd_ack",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } },
{ &hf_u3v_device_info_descriptor,
{ "U3V DEVICE INFO DESCRIPTOR", "u3v.device_info_descriptor",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL } }
};
void
proto_register_u3v(void)
{
static gint *ett[] = {
&ett_u3v,
&ett_u3v_cmd,
&ett_u3v_flags,
&ett_u3v_ack,
&ett_u3v_payload_cmd,
&ett_u3v_payload_ack,
&ett_u3v_payload_ack_subtree,
&ett_u3v_payload_cmd_subtree,
&ett_u3v_bootstrap_fields,
&ett_u3v_stream_leader,
&ett_u3v_stream_trailer,
&ett_u3v_stream_payload,
&ett_u3v_device_info_descriptor,
&ett_u3v_device_info_descriptor_speed_support,
&ett_u3v_device_info_descriptor_gencp_version,
&ett_u3v_device_info_descriptor_u3v_version,
};
proto_u3v = proto_register_protocol("USB 3 Vision", "U3V", "u3v");
proto_register_field_array(proto_u3v, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
register_dissector("u3v", dissect_u3v, proto_u3v);
}
void
proto_reg_handoff_u3v(void)
{
dissector_handle_t u3v_handle = NULL;
dissector_handle_t u3v_descr_handle = NULL;
u3v_handle = find_dissector("u3v");
dissector_add_uint("usb.bulk", IF_CLASS_MISCELLANEOUS, u3v_handle);
heur_dissector_add("usb.bulk", dissect_u3v_heur, "USB3Vision Protocol", "u3v", proto_u3v,HEURISTIC_ENABLE);
u3v_descr_handle = create_dissector_handle(dissect_u3v_descriptors, proto_u3v);
dissector_add_uint("usb.descriptor", IF_CLASS_MISCELLANEOUS, u3v_descr_handle);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5108_0 |
crossvul-cpp_data_bad_659_0 | /*
* Broadcom UniMAC MDIO bus controller driver
*
* Copyright (C) 2014-2017 Broadcom
*
* 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/kernel.h>
#include <linux/phy.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/of_mdio.h>
#include <linux/platform_data/mdio-bcm-unimac.h>
#define MDIO_CMD 0x00
#define MDIO_START_BUSY (1 << 29)
#define MDIO_READ_FAIL (1 << 28)
#define MDIO_RD (2 << 26)
#define MDIO_WR (1 << 26)
#define MDIO_PMD_SHIFT 21
#define MDIO_PMD_MASK 0x1F
#define MDIO_REG_SHIFT 16
#define MDIO_REG_MASK 0x1F
#define MDIO_CFG 0x04
#define MDIO_C22 (1 << 0)
#define MDIO_C45 0
#define MDIO_CLK_DIV_SHIFT 4
#define MDIO_CLK_DIV_MASK 0x3F
#define MDIO_SUPP_PREAMBLE (1 << 12)
struct unimac_mdio_priv {
struct mii_bus *mii_bus;
void __iomem *base;
int (*wait_func) (void *wait_func_data);
void *wait_func_data;
};
static inline u32 unimac_mdio_readl(struct unimac_mdio_priv *priv, u32 offset)
{
/* MIPS chips strapped for BE will automagically configure the
* peripheral registers for CPU-native byte order.
*/
if (IS_ENABLED(CONFIG_MIPS) && IS_ENABLED(CONFIG_CPU_BIG_ENDIAN))
return __raw_readl(priv->base + offset);
else
return readl_relaxed(priv->base + offset);
}
static inline void unimac_mdio_writel(struct unimac_mdio_priv *priv, u32 val,
u32 offset)
{
if (IS_ENABLED(CONFIG_MIPS) && IS_ENABLED(CONFIG_CPU_BIG_ENDIAN))
__raw_writel(val, priv->base + offset);
else
writel_relaxed(val, priv->base + offset);
}
static inline void unimac_mdio_start(struct unimac_mdio_priv *priv)
{
u32 reg;
reg = unimac_mdio_readl(priv, MDIO_CMD);
reg |= MDIO_START_BUSY;
unimac_mdio_writel(priv, reg, MDIO_CMD);
}
static inline unsigned int unimac_mdio_busy(struct unimac_mdio_priv *priv)
{
return unimac_mdio_readl(priv, MDIO_CMD) & MDIO_START_BUSY;
}
static int unimac_mdio_poll(void *wait_func_data)
{
struct unimac_mdio_priv *priv = wait_func_data;
unsigned int timeout = 1000;
do {
if (!unimac_mdio_busy(priv))
return 0;
usleep_range(1000, 2000);
} while (--timeout);
if (!timeout)
return -ETIMEDOUT;
return 0;
}
static int unimac_mdio_read(struct mii_bus *bus, int phy_id, int reg)
{
struct unimac_mdio_priv *priv = bus->priv;
int ret;
u32 cmd;
/* Prepare the read operation */
cmd = MDIO_RD | (phy_id << MDIO_PMD_SHIFT) | (reg << MDIO_REG_SHIFT);
unimac_mdio_writel(priv, cmd, MDIO_CMD);
/* Start MDIO transaction */
unimac_mdio_start(priv);
ret = priv->wait_func(priv->wait_func_data);
if (ret)
return ret;
cmd = unimac_mdio_readl(priv, MDIO_CMD);
/* Some broken devices are known not to release the line during
* turn-around, e.g: Broadcom BCM53125 external switches, so check for
* that condition here and ignore the MDIO controller read failure
* indication.
*/
if (!(bus->phy_ignore_ta_mask & 1 << phy_id) && (cmd & MDIO_READ_FAIL))
return -EIO;
return cmd & 0xffff;
}
static int unimac_mdio_write(struct mii_bus *bus, int phy_id,
int reg, u16 val)
{
struct unimac_mdio_priv *priv = bus->priv;
u32 cmd;
/* Prepare the write operation */
cmd = MDIO_WR | (phy_id << MDIO_PMD_SHIFT) |
(reg << MDIO_REG_SHIFT) | (0xffff & val);
unimac_mdio_writel(priv, cmd, MDIO_CMD);
unimac_mdio_start(priv);
return priv->wait_func(priv->wait_func_data);
}
/* Workaround for integrated BCM7xxx Gigabit PHYs which have a problem with
* their internal MDIO management controller making them fail to successfully
* be read from or written to for the first transaction. We insert a dummy
* BMSR read here to make sure that phy_get_device() and get_phy_id() can
* correctly read the PHY MII_PHYSID1/2 registers and successfully register a
* PHY device for this peripheral.
*
* Once the PHY driver is registered, we can workaround subsequent reads from
* there (e.g: during system-wide power management).
*
* bus->reset is invoked before mdiobus_scan during mdiobus_register and is
* therefore the right location to stick that workaround. Since we do not want
* to read from non-existing PHYs, we either use bus->phy_mask or do a manual
* Device Tree scan to limit the search area.
*/
static int unimac_mdio_reset(struct mii_bus *bus)
{
struct device_node *np = bus->dev.of_node;
struct device_node *child;
u32 read_mask = 0;
int addr;
if (!np) {
read_mask = ~bus->phy_mask;
} else {
for_each_available_child_of_node(np, child) {
addr = of_mdio_parse_addr(&bus->dev, child);
if (addr < 0)
continue;
read_mask |= 1 << addr;
}
}
for (addr = 0; addr < PHY_MAX_ADDR; addr++) {
if (read_mask & 1 << addr) {
dev_dbg(&bus->dev, "Workaround for PHY @ %d\n", addr);
mdiobus_read(bus, addr, MII_BMSR);
}
}
return 0;
}
static int unimac_mdio_probe(struct platform_device *pdev)
{
struct unimac_mdio_pdata *pdata = pdev->dev.platform_data;
struct unimac_mdio_priv *priv;
struct device_node *np;
struct mii_bus *bus;
struct resource *r;
int ret;
np = pdev->dev.of_node;
priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
/* Just ioremap, as this MDIO block is usually integrated into an
* Ethernet MAC controller register range
*/
priv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));
if (!priv->base) {
dev_err(&pdev->dev, "failed to remap register\n");
return -ENOMEM;
}
priv->mii_bus = mdiobus_alloc();
if (!priv->mii_bus)
return -ENOMEM;
bus = priv->mii_bus;
bus->priv = priv;
if (pdata) {
bus->name = pdata->bus_name;
priv->wait_func = pdata->wait_func;
priv->wait_func_data = pdata->wait_func_data;
bus->phy_mask = ~pdata->phy_mask;
} else {
bus->name = "unimac MII bus";
priv->wait_func_data = priv;
priv->wait_func = unimac_mdio_poll;
}
bus->parent = &pdev->dev;
bus->read = unimac_mdio_read;
bus->write = unimac_mdio_write;
bus->reset = unimac_mdio_reset;
snprintf(bus->id, MII_BUS_ID_SIZE, "%s-%d", pdev->name, pdev->id);
ret = of_mdiobus_register(bus, np);
if (ret) {
dev_err(&pdev->dev, "MDIO bus registration failed\n");
goto out_mdio_free;
}
platform_set_drvdata(pdev, priv);
dev_info(&pdev->dev, "Broadcom UniMAC MDIO bus at 0x%p\n", priv->base);
return 0;
out_mdio_free:
mdiobus_free(bus);
return ret;
}
static int unimac_mdio_remove(struct platform_device *pdev)
{
struct unimac_mdio_priv *priv = platform_get_drvdata(pdev);
mdiobus_unregister(priv->mii_bus);
mdiobus_free(priv->mii_bus);
return 0;
}
static const struct of_device_id unimac_mdio_ids[] = {
{ .compatible = "brcm,genet-mdio-v5", },
{ .compatible = "brcm,genet-mdio-v4", },
{ .compatible = "brcm,genet-mdio-v3", },
{ .compatible = "brcm,genet-mdio-v2", },
{ .compatible = "brcm,genet-mdio-v1", },
{ .compatible = "brcm,unimac-mdio", },
{ /* sentinel */ },
};
MODULE_DEVICE_TABLE(of, unimac_mdio_ids);
static struct platform_driver unimac_mdio_driver = {
.driver = {
.name = UNIMAC_MDIO_DRV_NAME,
.of_match_table = unimac_mdio_ids,
},
.probe = unimac_mdio_probe,
.remove = unimac_mdio_remove,
};
module_platform_driver(unimac_mdio_driver);
MODULE_AUTHOR("Broadcom Corporation");
MODULE_DESCRIPTION("Broadcom UniMAC MDIO bus controller");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" UNIMAC_MDIO_DRV_NAME);
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_659_0 |
crossvul-cpp_data_good_421_1 | /* This file is part of libmspack.
* (C) 2003-2018 Stuart Caie.
*
* libmspack is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License (LGPL) version 2.1
*
* For further details, see the file COPYING.LIB distributed with libmspack
*/
/* CHM decompression implementation */
#include <system.h>
#include <chm.h>
/* prototypes */
static struct mschmd_header * chmd_open(
struct mschm_decompressor *base, const char *filename);
static struct mschmd_header * chmd_fast_open(
struct mschm_decompressor *base, const char *filename);
static struct mschmd_header *chmd_real_open(
struct mschm_decompressor *base, const char *filename, int entire);
static void chmd_close(
struct mschm_decompressor *base, struct mschmd_header *chm);
static int chmd_read_headers(
struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire);
static int chmd_fast_find(
struct mschm_decompressor *base, struct mschmd_header *chm,
const char *filename, struct mschmd_file *f_ptr, int f_size);
static unsigned char *read_chunk(
struct mschm_decompressor_p *self, struct mschmd_header *chm,
struct mspack_file *fh, unsigned int chunk);
static int search_chunk(
struct mschmd_header *chm, const unsigned char *chunk, const char *filename,
const unsigned char **result, const unsigned char **result_end);
static inline int compare(
const char *s1, const char *s2, int l1, int l2);
static int chmd_extract(
struct mschm_decompressor *base, struct mschmd_file *file,
const char *filename);
static int chmd_sys_write(
struct mspack_file *file, void *buffer, int bytes);
static int chmd_init_decomp(
struct mschm_decompressor_p *self, struct mschmd_file *file);
static int read_reset_table(
struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec,
int entry, off_t *length_ptr, off_t *offset_ptr);
static int read_spaninfo(
struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec,
off_t *length_ptr);
static int find_sys_file(
struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec,
struct mschmd_file **f_ptr, const char *name);
static unsigned char *read_sys_file(
struct mschm_decompressor_p *self, struct mschmd_file *file);
static int chmd_error(
struct mschm_decompressor *base);
static int read_off64(
off_t *var, unsigned char *mem, struct mspack_system *sys,
struct mspack_file *fh);
/* filenames of the system files used for decompression.
* Content and ControlData are essential.
* ResetTable is preferred, but SpanInfo can be used if not available
*/
static const char *content_name = "::DataSpace/Storage/MSCompressed/Content";
static const char *control_name = "::DataSpace/Storage/MSCompressed/ControlData";
static const char *spaninfo_name = "::DataSpace/Storage/MSCompressed/SpanInfo";
static const char *rtable_name = "::DataSpace/Storage/MSCompressed/Transform/"
"{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable";
/***************************************
* MSPACK_CREATE_CHM_DECOMPRESSOR
***************************************
* constructor
*/
struct mschm_decompressor *
mspack_create_chm_decompressor(struct mspack_system *sys)
{
struct mschm_decompressor_p *self = NULL;
if (!sys) sys = mspack_default_system;
if (!mspack_valid_system(sys)) return NULL;
if ((self = (struct mschm_decompressor_p *) sys->alloc(sys, sizeof(struct mschm_decompressor_p)))) {
self->base.open = &chmd_open;
self->base.close = &chmd_close;
self->base.extract = &chmd_extract;
self->base.last_error = &chmd_error;
self->base.fast_open = &chmd_fast_open;
self->base.fast_find = &chmd_fast_find;
self->system = sys;
self->error = MSPACK_ERR_OK;
self->d = NULL;
}
return (struct mschm_decompressor *) self;
}
/***************************************
* MSPACK_DESTROY_CAB_DECOMPRESSOR
***************************************
* destructor
*/
void mspack_destroy_chm_decompressor(struct mschm_decompressor *base) {
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
if (self) {
struct mspack_system *sys = self->system;
if (self->d) {
if (self->d->infh) sys->close(self->d->infh);
if (self->d->state) lzxd_free(self->d->state);
sys->free(self->d);
}
sys->free(self);
}
}
/***************************************
* CHMD_OPEN
***************************************
* opens a file and tries to read it as a CHM file.
* Calls chmd_real_open() with entire=1.
*/
static struct mschmd_header *chmd_open(struct mschm_decompressor *base,
const char *filename)
{
return chmd_real_open(base, filename, 1);
}
/***************************************
* CHMD_FAST_OPEN
***************************************
* opens a file and tries to read it as a CHM file, but does not read
* the file headers. Calls chmd_real_open() with entire=0
*/
static struct mschmd_header *chmd_fast_open(struct mschm_decompressor *base,
const char *filename)
{
return chmd_real_open(base, filename, 0);
}
/***************************************
* CHMD_REAL_OPEN
***************************************
* the real implementation of chmd_open() and chmd_fast_open(). It simply
* passes the "entire" parameter to chmd_read_headers(), which will then
* either read all headers, or a bare mininum.
*/
static struct mschmd_header *chmd_real_open(struct mschm_decompressor *base,
const char *filename, int entire)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mschmd_header *chm = NULL;
struct mspack_system *sys;
struct mspack_file *fh;
int error;
if (!base) return NULL;
sys = self->system;
if ((fh = sys->open(sys, filename, MSPACK_SYS_OPEN_READ))) {
if ((chm = (struct mschmd_header *) sys->alloc(sys, sizeof(struct mschmd_header)))) {
chm->filename = filename;
error = chmd_read_headers(sys, fh, chm, entire);
if (error) {
/* if the error is DATAFORMAT, and there are some results, return
* partial results with a warning, rather than nothing */
if (error == MSPACK_ERR_DATAFORMAT && (chm->files || chm->sysfiles)) {
sys->message(fh, "WARNING; contents are corrupt");
error = MSPACK_ERR_OK;
}
else {
chmd_close(base, chm);
chm = NULL;
}
}
self->error = error;
}
else {
self->error = MSPACK_ERR_NOMEMORY;
}
sys->close(fh);
}
else {
self->error = MSPACK_ERR_OPEN;
}
return chm;
}
/***************************************
* CHMD_CLOSE
***************************************
* frees all memory associated with a given mschmd_header
*/
static void chmd_close(struct mschm_decompressor *base,
struct mschmd_header *chm)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mschmd_file *fi, *nfi;
struct mspack_system *sys;
unsigned int i;
if (!base) return;
sys = self->system;
self->error = MSPACK_ERR_OK;
/* free files */
for (fi = chm->files; fi; fi = nfi) {
nfi = fi->next;
sys->free(fi);
}
for (fi = chm->sysfiles; fi; fi = nfi) {
nfi = fi->next;
sys->free(fi);
}
/* if this CHM was being decompressed, free decompression state */
if (self->d && (self->d->chm == chm)) {
if (self->d->infh) sys->close(self->d->infh);
if (self->d->state) lzxd_free(self->d->state);
sys->free(self->d);
self->d = NULL;
}
/* if this CHM had a chunk cache, free it and contents */
if (chm->chunk_cache) {
for (i = 0; i < chm->num_chunks; i++) sys->free(chm->chunk_cache[i]);
sys->free(chm->chunk_cache);
}
sys->free(chm);
}
/***************************************
* CHMD_READ_HEADERS
***************************************
* reads the basic CHM file headers. If the "entire" parameter is
* non-zero, all file entries will also be read. fills out a pre-existing
* mschmd_header structure, allocates memory for files as necessary
*/
/* The GUIDs found in CHM headers */
static const unsigned char guids[32] = {
/* {7C01FD10-7BAA-11D0-9E0C-00A0-C922-E6EC} */
0x10, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11,
0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC,
/* {7C01FD11-7BAA-11D0-9E0C-00A0-C922-E6EC} */
0x11, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11,
0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC
};
/* reads an encoded integer into a variable; 7 bits of data per byte,
* the high bit is used to indicate that there is another byte */
#define READ_ENCINT(var) do { \
(var) = 0; \
do { \
if (p >= end) goto chunk_end; \
(var) = ((var) << 7) | (*p & 0x7F); \
} while (*p++ & 0x80); \
} while (0)
static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire)
{
unsigned int section, name_len, x, errors, num_chunks;
unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;
struct mschmd_file *fi, *link = NULL;
off_t offset, length;
int num_entries;
/* initialise pointers */
chm->files = NULL;
chm->sysfiles = NULL;
chm->chunk_cache = NULL;
chm->sec0.base.chm = chm;
chm->sec0.base.id = 0;
chm->sec1.base.chm = chm;
chm->sec1.base.id = 1;
chm->sec1.content = NULL;
chm->sec1.control = NULL;
chm->sec1.spaninfo = NULL;
chm->sec1.rtable = NULL;
/* read the first header */
if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check ITSF signature */
if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {
return MSPACK_ERR_SIGNATURE;
}
/* check both header GUIDs */
if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {
D(("incorrect GUIDs"))
return MSPACK_ERR_SIGNATURE;
}
chm->version = EndGetI32(&buf[chmhead_Version]);
chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);
chm->language = EndGetI32(&buf[chmhead_LanguageID]);
if (chm->version > 3) {
sys->message(fh, "WARNING; CHM version > 3");
}
/* read the header section table */
if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {
return MSPACK_ERR_READ;
}
/* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.
* The offset will be corrected later, once HS1 is read.
*/
if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) ||
read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) ||
read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))
{
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 0 */
if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 0 */
if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {
return MSPACK_ERR_READ;
}
if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 1 */
if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 1 */
if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {
return MSPACK_ERR_READ;
}
chm->dir_offset = sys->tell(fh);
chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);
chm->density = EndGetI32(&buf[chmhs1_Density]);
chm->depth = EndGetI32(&buf[chmhs1_Depth]);
chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);
chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);
chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);
chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]);
if (chm->version < 3) {
/* versions before 3 don't have chmhst3_OffsetCS0 */
chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);
}
/* check if content offset or file size is wrong */
if (chm->sec0.offset > chm->length) {
D(("content section begins after file has ended"))
return MSPACK_ERR_DATAFORMAT;
}
/* ensure there are chunks and that chunk size is
* large enough for signature and num_entries */
if (chm->chunk_size < (pmgl_Entries + 2)) {
D(("chunk size not large enough"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->num_chunks == 0) {
D(("no chunks"))
return MSPACK_ERR_DATAFORMAT;
}
/* The chunk_cache data structure is not great; large values for num_chunks
* or num_chunks*chunk_size can exhaust all memory. Until a better chunk
* cache is implemented, put arbitrary limits on num_chunks and chunk size.
*/
if (chm->num_chunks > 100000) {
D(("more than 100,000 chunks"))
return MSPACK_ERR_DATAFORMAT;
}
if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {
D(("chunks larger than entire file"))
return MSPACK_ERR_DATAFORMAT;
}
/* common sense checks on header section 1 fields */
if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {
sys->message(fh, "WARNING; chunk size is not a power of two");
}
if (chm->first_pmgl != 0) {
sys->message(fh, "WARNING; first PMGL chunk is not zero");
}
if (chm->first_pmgl > chm->last_pmgl) {
D(("first pmgl chunk is after last pmgl chunk"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) {
D(("index_root outside valid range"))
return MSPACK_ERR_DATAFORMAT;
}
/* if we are doing a quick read, stop here! */
if (!entire) {
return MSPACK_ERR_OK;
}
/* seek to the first PMGL chunk, and reduce the number of chunks to read */
if ((x = chm->first_pmgl) != 0) {
if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {
return MSPACK_ERR_SEEK;
}
}
num_chunks = chm->last_pmgl - x + 1;
if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {
return MSPACK_ERR_NOMEMORY;
}
/* read and process all chunks from FirstPMGL to LastPMGL */
errors = 0;
while (num_chunks--) {
/* read next chunk */
if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {
sys->free(chunk);
return MSPACK_ERR_READ;
}
/* process only directory (PMGL) chunks */
if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;
if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {
sys->message(fh, "WARNING; PMGL quickref area is too small");
}
if (EndGetI32(&chunk[pmgl_QuickRefSize]) >
((int)chm->chunk_size - pmgl_Entries))
{
sys->message(fh, "WARNING; PMGL quickref area is too large");
}
p = &chunk[pmgl_Entries];
end = &chunk[chm->chunk_size - 2];
num_entries = EndGetI16(end);
while (num_entries--) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
name = p; p += name_len;
READ_ENCINT(section);
READ_ENCINT(offset);
READ_ENCINT(length);
/* ignore blank or one-char (e.g. "/") filenames we'd return as blank */
if (name_len < 2 || !name[0] || !name[1]) continue;
/* empty files and directory names are stored as a file entry at
* offset 0 with length 0. We want to keep empty files, but not
* directory names, which end with a "/" */
if ((offset == 0) && (length == 0)) {
if ((name_len > 0) && (name[name_len-1] == '/')) continue;
}
if (section > 1) {
sys->message(fh, "invalid section number '%u'.", section);
continue;
}
if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {
sys->free(chunk);
return MSPACK_ERR_NOMEMORY;
}
fi->next = NULL;
fi->filename = (char *) &fi[1];
fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)
: (struct mschmd_section *) (&chm->sec1));
fi->offset = offset;
fi->length = length;
sys->copy(name, fi->filename, (size_t) name_len);
fi->filename[name_len] = '\0';
if (name[0] == ':' && name[1] == ':') {
/* system file */
if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) {
if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) {
chm->sec1.content = fi;
}
else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) {
chm->sec1.control = fi;
}
else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) {
chm->sec1.spaninfo = fi;
}
else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) {
chm->sec1.rtable = fi;
}
}
fi->next = chm->sysfiles;
chm->sysfiles = fi;
}
else {
/* normal file */
if (link) link->next = fi; else chm->files = fi;
link = fi;
}
}
/* this is reached either when num_entries runs out, or if
* reading data from the chunk reached a premature end of chunk */
chunk_end:
if (num_entries >= 0) {
D(("chunk ended before all entries could be read"))
errors++;
}
}
sys->free(chunk);
return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;
}
/***************************************
* CHMD_FAST_FIND
***************************************
* uses PMGI index chunks and quickref data to quickly locate a file
* directly from the on-disk index.
*
* TODO: protect against infinite loops in chunks (where pgml_NextChunk
* or a PMGI index entry point to an already visited chunk)
*/
static int chmd_fast_find(struct mschm_decompressor *base,
struct mschmd_header *chm, const char *filename,
struct mschmd_file *f_ptr, int f_size)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mspack_system *sys;
struct mspack_file *fh;
const unsigned char *chunk, *p, *end;
int err = MSPACK_ERR_OK, result = -1;
unsigned int n, sec;
if (!self || !chm || !f_ptr || (f_size != sizeof(struct mschmd_file))) {
return MSPACK_ERR_ARGS;
}
sys = self->system;
/* clear the results structure */
memset(f_ptr, 0, f_size);
if (!(fh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ))) {
return MSPACK_ERR_OPEN;
}
/* go through PMGI chunk hierarchy to reach PMGL chunk */
if (chm->index_root < chm->num_chunks) {
n = chm->index_root;
for (;;) {
if (!(chunk = read_chunk(self, chm, fh, n))) {
sys->close(fh);
return self->error;
}
/* search PMGI/PMGL chunk. exit early if no entry found */
if ((result = search_chunk(chm, chunk, filename, &p, &end)) <= 0) {
break;
}
/* found result. loop around for next chunk if this is PMGI */
if (chunk[3] == 0x4C) break; else READ_ENCINT(n);
}
}
else {
/* PMGL chunks only, search from first_pmgl to last_pmgl */
for (n = chm->first_pmgl; n <= chm->last_pmgl;
n = EndGetI32(&chunk[pmgl_NextChunk]))
{
if (!(chunk = read_chunk(self, chm, fh, n))) {
err = self->error;
break;
}
/* search PMGL chunk. exit if file found */
if ((result = search_chunk(chm, chunk, filename, &p, &end)) > 0) {
break;
}
/* stop simple infinite loops: can't visit the same chunk twice */
if ((int)n == EndGetI32(&chunk[pmgl_NextChunk])) {
break;
}
}
}
/* if we found a file, read it */
if (result > 0) {
READ_ENCINT(sec);
f_ptr->section = (sec == 0) ? (struct mschmd_section *) &chm->sec0
: (struct mschmd_section *) &chm->sec1;
READ_ENCINT(f_ptr->offset);
READ_ENCINT(f_ptr->length);
}
else if (result < 0) {
err = MSPACK_ERR_DATAFORMAT;
}
sys->close(fh);
return self->error = err;
chunk_end:
D(("read beyond end of chunk entries"))
sys->close(fh);
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* reads the given chunk into memory, storing it in a chunk cache
* so it doesn't need to be read from disk more than once
*/
static unsigned char *read_chunk(struct mschm_decompressor_p *self,
struct mschmd_header *chm,
struct mspack_file *fh,
unsigned int chunk_num)
{
struct mspack_system *sys = self->system;
unsigned char *buf;
/* check arguments - most are already checked by chmd_fast_find */
if (chunk_num >= chm->num_chunks) return NULL;
/* ensure chunk cache is available */
if (!chm->chunk_cache) {
size_t size = sizeof(unsigned char *) * chm->num_chunks;
if (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) {
self->error = MSPACK_ERR_NOMEMORY;
return NULL;
}
memset(chm->chunk_cache, 0, size);
}
/* try to answer out of chunk cache */
if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num];
/* need to read chunk - allocate memory for it */
if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) {
self->error = MSPACK_ERR_NOMEMORY;
return NULL;
}
/* seek to block and read it */
if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)),
MSPACK_SYS_SEEK_START))
{
self->error = MSPACK_ERR_SEEK;
sys->free(buf);
return NULL;
}
if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) {
self->error = MSPACK_ERR_READ;
sys->free(buf);
return NULL;
}
/* check the signature. Is is PMGL or PMGI? */
if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) &&
((buf[3] == 0x4C) || (buf[3] == 0x49))))
{
self->error = MSPACK_ERR_SEEK;
sys->free(buf);
return NULL;
}
/* all OK. Store chunk in cache and return it */
return chm->chunk_cache[chunk_num] = buf;
}
/* searches a PMGI/PMGL chunk for a given filename entry. Returns -1 on
* data format error, 0 if entry definitely not found, 1 if entry
* found. In the latter case, *result and *result_end are set pointing
* to that entry's data (either the "next chunk" ENCINT for a PMGI or
* the section, offset and length ENCINTs for a PMGL).
*
* In the case of PMGL chunks, the entry has definitely been
* found. In the case of PMGI chunks, the entry which points to the
* chunk that may eventually contain that entry has been found.
*/
static int search_chunk(struct mschmd_header *chm,
const unsigned char *chunk,
const char *filename,
const unsigned char **result,
const unsigned char **result_end)
{
const unsigned char *start, *end, *p;
unsigned int qr_size, num_entries, qr_entries, qr_density, name_len;
unsigned int L, R, M, fname_len, entries_off, is_pmgl;
int cmp;
fname_len = strlen(filename);
/* PMGL chunk or PMGI chunk? (note: read_chunk() has already
* checked the rest of the characters in the chunk signature) */
if (chunk[3] == 0x4C) {
is_pmgl = 1;
entries_off = pmgl_Entries;
}
else {
is_pmgl = 0;
entries_off = pmgi_Entries;
}
/* Step 1: binary search first filename of each QR entry
* - target filename == entry
* found file
* - target filename < all entries
* file not found
* - target filename > all entries
* proceed to step 2 using final entry
* - target filename between two searched entries
* proceed to step 2
*/
qr_size = EndGetI32(&chunk[pmgl_QuickRefSize]);
start = &chunk[chm->chunk_size - 2];
end = &chunk[chm->chunk_size - qr_size];
num_entries = EndGetI16(start);
qr_density = 1 + (1 << chm->density);
qr_entries = (num_entries + qr_density-1) / qr_density;
if (num_entries == 0) {
D(("chunk has no entries"))
return -1;
}
if (qr_size > chm->chunk_size) {
D(("quickref size > chunk size"))
return -1;
}
*result_end = end;
if (((int)qr_entries * 2) > (start - end)) {
D(("WARNING; more quickrefs than quickref space"))
qr_entries = 0; /* but we can live with it */
}
if (qr_entries > 0) {
L = 0;
R = qr_entries - 1;
do {
/* pick new midpoint */
M = (L + R) >> 1;
/* compare filename with entry QR points to */
p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)];
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
cmp = compare(filename, (char *)p, fname_len, name_len);
if (cmp == 0) break;
else if (cmp < 0) { if (M) R = M - 1; else return 0; }
else if (cmp > 0) L = M + 1;
} while (L <= R);
M = (L + R) >> 1;
if (cmp == 0) {
/* exact match! */
p += name_len;
*result = p;
return 1;
}
/* otherwise, read the group of entries for QR entry M */
p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)];
num_entries -= (M * qr_density);
if (num_entries > qr_density) num_entries = qr_density;
}
else {
p = &chunk[entries_off];
}
/* Step 2: linear search through the set of entries reached in step 1.
* - filename == any entry
* found entry
* - filename < all entries (PMGI) or any entry (PMGL)
* entry not found, stop now
* - filename > all entries
* entry not found (PMGL) / maybe found (PMGI)
* -
*/
*result = NULL;
while (num_entries-- > 0) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
cmp = compare(filename, (char *)p, fname_len, name_len);
p += name_len;
if (cmp == 0) {
/* entry found */
*result = p;
return 1;
}
if (cmp < 0) {
/* entry not found (PMGL) / maybe found (PMGI) */
break;
}
/* read and ignore the rest of this entry */
if (is_pmgl) {
READ_ENCINT(R); /* skip section */
READ_ENCINT(R); /* skip offset */
READ_ENCINT(R); /* skip length */
}
else {
*result = p; /* store potential final result */
READ_ENCINT(R); /* skip chunk number */
}
}
/* PMGL? not found. PMGI? maybe found */
return (is_pmgl) ? 0 : (*result ? 1 : 0);
chunk_end:
D(("reached end of chunk data while searching"))
return -1;
}
#if HAVE_TOWLOWER
# if HAVE_WCTYPE_H
# include <wctype.h>
# endif
# define TOLOWER(x) towlower(x)
#elif HAVE_TOLOWER
# if HAVE_CTYPE_H
# include <ctype.h>
# endif
# define TOLOWER(x) tolower(x)
#else
# define TOLOWER(x) (((x)<0||(x)>255)?(x):mspack_tolower_map[(x)])
/* Map of char -> lowercase char for the first 256 chars. Generated with:
* LC_CTYPE=en_GB.utf-8 perl -Mlocale -le 'print map{ord(lc chr).","} 0..255'
*/
static const unsigned char mspack_tolower_map[256] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,
28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,
53,54,55,56,57,58,59,60,61,62,63,64,97,98,99,100,101,102,103,104,105,106,
107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,
95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,
115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,
134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,
153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,
172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,
191,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,
242,243,244,245,246,215,248,249,250,251,252,253,254,223,224,225,226,227,228,
229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255
};
#endif
/* decodes a UTF-8 character from s[] into c. Will not read past e.
* doesn't test that extension bytes are %10xxxxxx.
* allows some overlong encodings.
*/
#define GET_UTF8_CHAR(s, e, c) do { \
unsigned char x = *s++; \
if (x < 0x80) c = x; \
else if (x >= 0xC2 && x < 0xE0 && s < e) { \
c = (x & 0x1F) << 6 | (*s++ & 0x3F); \
} \
else if (x >= 0xE0 && x < 0xF0 && s+1 < e) { \
c = (x & 0x0F) << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F); \
s += 2; \
} \
else if (x >= 0xF0 && x <= 0xF5 && s+2 < e) { \
c = (x & 0x07) << 18 | (s[0] & 0x3F) << 12 | \
(s[1] & 0x3F) << 6 | (s[2] & 0x3F); \
if (c > 0x10FFFF) c = 0xFFFD; \
s += 3; \
} \
else c = 0xFFFD; \
} while (0)
/* case-insensitively compares two UTF8 encoded strings. String length for
* both strings must be provided, null bytes are not terminators */
static inline int compare(const char *s1, const char *s2, int l1, int l2) {
register const unsigned char *p1 = (const unsigned char *) s1;
register const unsigned char *p2 = (const unsigned char *) s2;
register const unsigned char *e1 = p1 + l1, *e2 = p2 + l2;
int c1, c2;
while (p1 < e1 && p2 < e2) {
GET_UTF8_CHAR(p1, e1, c1);
GET_UTF8_CHAR(p2, e2, c2);
if (c1 == c2) continue;
c1 = TOLOWER(c1);
c2 = TOLOWER(c2);
if (c1 != c2) return c1 - c2;
}
return l1 - l2;
}
/***************************************
* CHMD_EXTRACT
***************************************
* extracts a file from a CHM helpfile
*/
static int chmd_extract(struct mschm_decompressor *base,
struct mschmd_file *file, const char *filename)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mspack_system *sys;
struct mschmd_header *chm;
struct mspack_file *fh;
off_t bytes;
if (!self) return MSPACK_ERR_ARGS;
if (!file || !file->section) return self->error = MSPACK_ERR_ARGS;
sys = self->system;
chm = file->section->chm;
/* create decompression state if it doesn't exist */
if (!self->d) {
self->d = (struct mschmd_decompress_state *) sys->alloc(sys, sizeof(struct mschmd_decompress_state));
if (!self->d) return self->error = MSPACK_ERR_NOMEMORY;
self->d->chm = chm;
self->d->offset = 0;
self->d->state = NULL;
self->d->sys = *sys;
self->d->sys.write = &chmd_sys_write;
self->d->infh = NULL;
self->d->outfh = NULL;
}
/* open input chm file if not open, or the open one is a different chm */
if (!self->d->infh || (self->d->chm != chm)) {
if (self->d->infh) sys->close(self->d->infh);
if (self->d->state) lzxd_free(self->d->state);
self->d->chm = chm;
self->d->offset = 0;
self->d->state = NULL;
self->d->infh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ);
if (!self->d->infh) return self->error = MSPACK_ERR_OPEN;
}
/* open file for output */
if (!(fh = sys->open(sys, filename, MSPACK_SYS_OPEN_WRITE))) {
return self->error = MSPACK_ERR_OPEN;
}
/* if file is empty, simply creating it is enough */
if (!file->length) {
sys->close(fh);
return self->error = MSPACK_ERR_OK;
}
self->error = MSPACK_ERR_OK;
switch (file->section->id) {
case 0: /* Uncompressed section file */
/* simple seek + copy */
if (sys->seek(self->d->infh, file->section->chm->sec0.offset
+ file->offset, MSPACK_SYS_SEEK_START))
{
self->error = MSPACK_ERR_SEEK;
}
else {
unsigned char buf[512];
off_t length = file->length;
while (length > 0) {
int run = sizeof(buf);
if ((off_t)run > length) run = (int)length;
if (sys->read(self->d->infh, &buf[0], run) != run) {
self->error = MSPACK_ERR_READ;
break;
}
if (sys->write(fh, &buf[0], run) != run) {
self->error = MSPACK_ERR_WRITE;
break;
}
length -= run;
}
}
break;
case 1: /* MSCompressed section file */
/* (re)initialise compression state if we it is not yet initialised,
* or we have advanced too far and have to backtrack
*/
if (!self->d->state || (file->offset < self->d->offset)) {
if (self->d->state) {
lzxd_free(self->d->state);
self->d->state = NULL;
}
if (chmd_init_decomp(self, file)) break;
}
/* seek to input data */
if (sys->seek(self->d->infh, self->d->inoffset, MSPACK_SYS_SEEK_START)) {
self->error = MSPACK_ERR_SEEK;
break;
}
/* get to correct offset. */
self->d->outfh = NULL;
if ((bytes = file->offset - self->d->offset)) {
self->error = lzxd_decompress(self->d->state, bytes);
}
/* if getting to the correct offset was error free, unpack file */
if (!self->error) {
self->d->outfh = fh;
self->error = lzxd_decompress(self->d->state, file->length);
}
/* save offset in input source stream, in case there is a section 0
* file between now and the next section 1 file extracted */
self->d->inoffset = sys->tell(self->d->infh);
/* if an LZX error occured, the LZX decompressor is now useless */
if (self->error) {
if (self->d->state) lzxd_free(self->d->state);
self->d->state = NULL;
}
break;
}
sys->close(fh);
return self->error;
}
/***************************************
* CHMD_SYS_WRITE
***************************************
* chmd_sys_write is the internal writer function which the decompressor
* uses. If either writes data to disk (self->d->outfh) with the real
* sys->write() function, or does nothing with the data when
* self->d->outfh == NULL. advances self->d->offset.
*/
static int chmd_sys_write(struct mspack_file *file, void *buffer, int bytes) {
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) file;
self->d->offset += bytes;
if (self->d->outfh) {
return self->system->write(self->d->outfh, buffer, bytes);
}
return bytes;
}
/***************************************
* CHMD_INIT_DECOMP
***************************************
* Initialises the LZX decompressor to decompress the compressed stream,
* from the nearest reset offset and length that is needed for the given
* file.
*/
static int chmd_init_decomp(struct mschm_decompressor_p *self,
struct mschmd_file *file)
{
int window_size, window_bits, reset_interval, entry, err;
struct mspack_system *sys = self->system;
struct mschmd_sec_mscompressed *sec;
unsigned char *data;
off_t length, offset;
sec = (struct mschmd_sec_mscompressed *) file->section;
/* ensure we have a mscompressed content section */
err = find_sys_file(self, sec, &sec->content, content_name);
if (err) return self->error = err;
/* ensure we have a ControlData file */
err = find_sys_file(self, sec, &sec->control, control_name);
if (err) return self->error = err;
/* read ControlData */
if (sec->control->length < lzxcd_SIZEOF) {
D(("ControlData file is too short"))
return self->error = MSPACK_ERR_DATAFORMAT;
}
if (!(data = read_sys_file(self, sec->control))) {
D(("can't read mscompressed control data file"))
return self->error;
}
/* check LZXC signature */
if (EndGetI32(&data[lzxcd_Signature]) != 0x43585A4C) {
sys->free(data);
return self->error = MSPACK_ERR_SIGNATURE;
}
/* read reset_interval and window_size and validate version number */
switch (EndGetI32(&data[lzxcd_Version])) {
case 1:
reset_interval = EndGetI32(&data[lzxcd_ResetInterval]);
window_size = EndGetI32(&data[lzxcd_WindowSize]);
break;
case 2:
reset_interval = EndGetI32(&data[lzxcd_ResetInterval]) * LZX_FRAME_SIZE;
window_size = EndGetI32(&data[lzxcd_WindowSize]) * LZX_FRAME_SIZE;
break;
default:
D(("bad controldata version"))
sys->free(data);
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* free ControlData */
sys->free(data);
/* find window_bits from window_size */
switch (window_size) {
case 0x008000: window_bits = 15; break;
case 0x010000: window_bits = 16; break;
case 0x020000: window_bits = 17; break;
case 0x040000: window_bits = 18; break;
case 0x080000: window_bits = 19; break;
case 0x100000: window_bits = 20; break;
case 0x200000: window_bits = 21; break;
default:
D(("bad controldata window size"))
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* validate reset_interval */
if (reset_interval == 0 || reset_interval % LZX_FRAME_SIZE) {
D(("bad controldata reset interval"))
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* which reset table entry would we like? */
entry = file->offset / reset_interval;
/* convert from reset interval multiple (usually 64k) to 32k frames */
entry *= reset_interval / LZX_FRAME_SIZE;
/* read the reset table entry */
if (read_reset_table(self, sec, entry, &length, &offset)) {
/* the uncompressed length given in the reset table is dishonest.
* the uncompressed data is always padded out from the given
* uncompressed length up to the next reset interval */
length += reset_interval - 1;
length &= -reset_interval;
}
else {
/* if we can't read the reset table entry, just start from
* the beginning. Use spaninfo to get the uncompressed length */
entry = 0;
offset = 0;
err = read_spaninfo(self, sec, &length);
}
if (err) return self->error = err;
/* get offset of compressed data stream:
* = offset of uncompressed section from start of file
* + offset of compressed stream from start of uncompressed section
* + offset of chosen reset interval from start of compressed stream */
self->d->inoffset = file->section->chm->sec0.offset + sec->content->offset + offset;
/* set start offset and overall remaining stream length */
self->d->offset = entry * LZX_FRAME_SIZE;
length -= self->d->offset;
/* initialise LZX stream */
self->d->state = lzxd_init(&self->d->sys, self->d->infh,
(struct mspack_file *) self, window_bits,
reset_interval / LZX_FRAME_SIZE,
4096, length, 0);
if (!self->d->state) self->error = MSPACK_ERR_NOMEMORY;
return self->error;
}
/***************************************
* READ_RESET_TABLE
***************************************
* Reads one entry out of the reset table. Also reads the uncompressed
* data length. Writes these to offset_ptr and length_ptr respectively.
* Returns non-zero for success, zero for failure.
*/
static int read_reset_table(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
int entry, off_t *length_ptr, off_t *offset_ptr)
{
struct mspack_system *sys = self->system;
unsigned char *data;
unsigned int pos, entrysize;
/* do we have a ResetTable file? */
int err = find_sys_file(self, sec, &sec->rtable, rtable_name);
if (err) return 0;
/* read ResetTable file */
if (sec->rtable->length < lzxrt_headerSIZEOF) {
D(("ResetTable file is too short"))
return 0;
}
if (!(data = read_sys_file(self, sec->rtable))) {
D(("can't read reset table"))
return 0;
}
/* check sanity of reset table */
if (EndGetI32(&data[lzxrt_FrameLen]) != LZX_FRAME_SIZE) {
D(("bad reset table frame length"))
sys->free(data);
return 0;
}
/* get the uncompressed length of the LZX stream */
if (read_off64(length_ptr, &data[lzxrt_UncompLen], sys, self->d->infh)) {
sys->free(data);
return 0;
}
entrysize = EndGetI32(&data[lzxrt_EntrySize]);
pos = EndGetI32(&data[lzxrt_TableOffset]) + (entry * entrysize);
/* ensure reset table entry for this offset exists */
if (entry < EndGetI32(&data[lzxrt_NumEntries]) &&
pos <= (sec->rtable->length - entrysize))
{
switch (entrysize) {
case 4:
*offset_ptr = EndGetI32(&data[pos]);
err = 0;
break;
case 8:
err = read_off64(offset_ptr, &data[pos], sys, self->d->infh);
break;
default:
D(("reset table entry size neither 4 nor 8"))
err = 1;
break;
}
}
else {
D(("bad reset interval"))
err = 1;
}
/* free the reset table */
sys->free(data);
/* return success */
return (err == 0);
}
/***************************************
* READ_SPANINFO
***************************************
* Reads the uncompressed data length from the spaninfo file.
* Returns zero for success or a non-zero error code for failure.
*/
static int read_spaninfo(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
off_t *length_ptr)
{
struct mspack_system *sys = self->system;
unsigned char *data;
/* find SpanInfo file */
int err = find_sys_file(self, sec, &sec->spaninfo, spaninfo_name);
if (err) return MSPACK_ERR_DATAFORMAT;
/* check it's large enough */
if (sec->spaninfo->length != 8) {
D(("SpanInfo file is wrong size"))
return MSPACK_ERR_DATAFORMAT;
}
/* read the SpanInfo file */
if (!(data = read_sys_file(self, sec->spaninfo))) {
D(("can't read SpanInfo file"))
return self->error;
}
/* get the uncompressed length of the LZX stream */
err = read_off64(length_ptr, data, sys, self->d->infh);
sys->free(data);
if (err) return MSPACK_ERR_DATAFORMAT;
if (*length_ptr <= 0) {
D(("output length is invalid"))
return MSPACK_ERR_DATAFORMAT;
}
return MSPACK_ERR_OK;
}
/***************************************
* FIND_SYS_FILE
***************************************
* Uses chmd_fast_find to locate a system file, and fills out that system
* file's entry and links it into the list of system files. Returns zero
* for success, non-zero for both failure and the file not existing.
*/
static int find_sys_file(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
struct mschmd_file **f_ptr, const char *name)
{
struct mspack_system *sys = self->system;
struct mschmd_file result;
/* already loaded */
if (*f_ptr) return MSPACK_ERR_OK;
/* try using fast_find to find the file - return DATAFORMAT error if
* it fails, or successfully doesn't find the file */
if (chmd_fast_find((struct mschm_decompressor *) self, sec->base.chm,
name, &result, (int)sizeof(result)) || !result.section)
{
return MSPACK_ERR_DATAFORMAT;
}
if (!(*f_ptr = (struct mschmd_file *) sys->alloc(sys, sizeof(result)))) {
return MSPACK_ERR_NOMEMORY;
}
/* copy result */
*(*f_ptr) = result;
(*f_ptr)->filename = (char *) name;
/* link file into sysfiles list */
(*f_ptr)->next = sec->base.chm->sysfiles;
sec->base.chm->sysfiles = *f_ptr;
return MSPACK_ERR_OK;
}
/***************************************
* READ_SYS_FILE
***************************************
* Allocates memory for a section 0 (uncompressed) file and reads it into
* memory.
*/
static unsigned char *read_sys_file(struct mschm_decompressor_p *self,
struct mschmd_file *file)
{
struct mspack_system *sys = self->system;
unsigned char *data = NULL;
int len;
if (!file || !file->section || (file->section->id != 0)) {
self->error = MSPACK_ERR_DATAFORMAT;
return NULL;
}
len = (int) file->length;
if (!(data = (unsigned char *) sys->alloc(sys, (size_t) len))) {
self->error = MSPACK_ERR_NOMEMORY;
return NULL;
}
if (sys->seek(self->d->infh, file->section->chm->sec0.offset
+ file->offset, MSPACK_SYS_SEEK_START))
{
self->error = MSPACK_ERR_SEEK;
sys->free(data);
return NULL;
}
if (sys->read(self->d->infh, data, len) != len) {
self->error = MSPACK_ERR_READ;
sys->free(data);
return NULL;
}
return data;
}
/***************************************
* CHMD_ERROR
***************************************
* returns the last error that occurred
*/
static int chmd_error(struct mschm_decompressor *base) {
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
return (self) ? self->error : MSPACK_ERR_ARGS;
}
/***************************************
* READ_OFF64
***************************************
* Reads a 64-bit signed integer from memory in Intel byte order.
* If running on a system with a 64-bit off_t, this is simply done.
* If running on a system with a 32-bit off_t, offsets up to 0x7FFFFFFF
* are accepted, offsets beyond that cause an error message.
*/
static int read_off64(off_t *var, unsigned char *mem,
struct mspack_system *sys, struct mspack_file *fh)
{
#if LARGEFILE_SUPPORT
*var = EndGetI64(mem);
#else
*var = EndGetI32(mem);
if ((*var & 0x80000000) || EndGetI32(mem+4)) {
sys->message(fh, (char *)largefile_msg);
return 1;
}
#endif
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_421_1 |
crossvul-cpp_data_good_2788_0 | /*
* Copyright (c) 2007-2010 Stefano Sabatini
*
* 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
* simple media prober based on the FFmpeg libraries
*/
#include "config.h"
#include "libavutil/ffversion.h"
#include <string.h>
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/display.h"
#include "libavutil/hash.h"
#include "libavutil/mastering_display_metadata.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "libavutil/spherical.h"
#include "libavutil/stereo3d.h"
#include "libavutil/dict.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/libm.h"
#include "libavutil/parseutils.h"
#include "libavutil/timecode.h"
#include "libavutil/timestamp.h"
#include "libavdevice/avdevice.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"
#include "libpostproc/postprocess.h"
#include "cmdutils.h"
#include "libavutil/thread.h"
#if !HAVE_THREADS
# ifdef pthread_mutex_lock
# undef pthread_mutex_lock
# endif
# define pthread_mutex_lock(a) do{}while(0)
# ifdef pthread_mutex_unlock
# undef pthread_mutex_unlock
# endif
# define pthread_mutex_unlock(a) do{}while(0)
#endif
typedef struct InputStream {
AVStream *st;
AVCodecContext *dec_ctx;
} InputStream;
typedef struct InputFile {
AVFormatContext *fmt_ctx;
InputStream *streams;
int nb_streams;
} InputFile;
const char program_name[] = "ffprobe";
const int program_birth_year = 2007;
static int do_bitexact = 0;
static int do_count_frames = 0;
static int do_count_packets = 0;
static int do_read_frames = 0;
static int do_read_packets = 0;
static int do_show_chapters = 0;
static int do_show_error = 0;
static int do_show_format = 0;
static int do_show_frames = 0;
static int do_show_packets = 0;
static int do_show_programs = 0;
static int do_show_streams = 0;
static int do_show_stream_disposition = 0;
static int do_show_data = 0;
static int do_show_program_version = 0;
static int do_show_library_versions = 0;
static int do_show_pixel_formats = 0;
static int do_show_pixel_format_flags = 0;
static int do_show_pixel_format_components = 0;
static int do_show_log = 0;
static int do_show_chapter_tags = 0;
static int do_show_format_tags = 0;
static int do_show_frame_tags = 0;
static int do_show_program_tags = 0;
static int do_show_stream_tags = 0;
static int do_show_packet_tags = 0;
static int show_value_unit = 0;
static int use_value_prefix = 0;
static int use_byte_value_binary_prefix = 0;
static int use_value_sexagesimal_format = 0;
static int show_private_data = 1;
static char *print_format;
static char *stream_specifier;
static char *show_data_hash;
typedef struct ReadInterval {
int id; ///< identifier
int64_t start, end; ///< start, end in second/AV_TIME_BASE units
int has_start, has_end;
int start_is_offset, end_is_offset;
int duration_frames;
} ReadInterval;
static ReadInterval *read_intervals;
static int read_intervals_nb = 0;
static int find_stream_info = 1;
/* section structure definition */
#define SECTION_MAX_NB_CHILDREN 10
struct section {
int id; ///< unique id identifying a section
const char *name;
#define SECTION_FLAG_IS_WRAPPER 1 ///< the section only contains other sections, but has no data at its own level
#define SECTION_FLAG_IS_ARRAY 2 ///< the section contains an array of elements of the same type
#define SECTION_FLAG_HAS_VARIABLE_FIELDS 4 ///< the section may contain a variable number of fields with variable keys.
/// For these sections the element_name field is mandatory.
int flags;
int children_ids[SECTION_MAX_NB_CHILDREN+1]; ///< list of children section IDS, terminated by -1
const char *element_name; ///< name of the contained element, if provided
const char *unique_name; ///< unique section name, in case the name is ambiguous
AVDictionary *entries_to_show;
int show_all_entries;
};
typedef enum {
SECTION_ID_NONE = -1,
SECTION_ID_CHAPTER,
SECTION_ID_CHAPTER_TAGS,
SECTION_ID_CHAPTERS,
SECTION_ID_ERROR,
SECTION_ID_FORMAT,
SECTION_ID_FORMAT_TAGS,
SECTION_ID_FRAME,
SECTION_ID_FRAMES,
SECTION_ID_FRAME_TAGS,
SECTION_ID_FRAME_SIDE_DATA_LIST,
SECTION_ID_FRAME_SIDE_DATA,
SECTION_ID_FRAME_LOG,
SECTION_ID_FRAME_LOGS,
SECTION_ID_LIBRARY_VERSION,
SECTION_ID_LIBRARY_VERSIONS,
SECTION_ID_PACKET,
SECTION_ID_PACKET_TAGS,
SECTION_ID_PACKETS,
SECTION_ID_PACKETS_AND_FRAMES,
SECTION_ID_PACKET_SIDE_DATA_LIST,
SECTION_ID_PACKET_SIDE_DATA,
SECTION_ID_PIXEL_FORMAT,
SECTION_ID_PIXEL_FORMAT_FLAGS,
SECTION_ID_PIXEL_FORMAT_COMPONENT,
SECTION_ID_PIXEL_FORMAT_COMPONENTS,
SECTION_ID_PIXEL_FORMATS,
SECTION_ID_PROGRAM_STREAM_DISPOSITION,
SECTION_ID_PROGRAM_STREAM_TAGS,
SECTION_ID_PROGRAM,
SECTION_ID_PROGRAM_STREAMS,
SECTION_ID_PROGRAM_STREAM,
SECTION_ID_PROGRAM_TAGS,
SECTION_ID_PROGRAM_VERSION,
SECTION_ID_PROGRAMS,
SECTION_ID_ROOT,
SECTION_ID_STREAM,
SECTION_ID_STREAM_DISPOSITION,
SECTION_ID_STREAMS,
SECTION_ID_STREAM_TAGS,
SECTION_ID_STREAM_SIDE_DATA_LIST,
SECTION_ID_STREAM_SIDE_DATA,
SECTION_ID_SUBTITLE,
} SectionID;
static struct section sections[] = {
[SECTION_ID_CHAPTERS] = { SECTION_ID_CHAPTERS, "chapters", SECTION_FLAG_IS_ARRAY, { SECTION_ID_CHAPTER, -1 } },
[SECTION_ID_CHAPTER] = { SECTION_ID_CHAPTER, "chapter", 0, { SECTION_ID_CHAPTER_TAGS, -1 } },
[SECTION_ID_CHAPTER_TAGS] = { SECTION_ID_CHAPTER_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "chapter_tags" },
[SECTION_ID_ERROR] = { SECTION_ID_ERROR, "error", 0, { -1 } },
[SECTION_ID_FORMAT] = { SECTION_ID_FORMAT, "format", 0, { SECTION_ID_FORMAT_TAGS, -1 } },
[SECTION_ID_FORMAT_TAGS] = { SECTION_ID_FORMAT_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "format_tags" },
[SECTION_ID_FRAMES] = { SECTION_ID_FRAMES, "frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME, SECTION_ID_SUBTITLE, -1 } },
[SECTION_ID_FRAME] = { SECTION_ID_FRAME, "frame", 0, { SECTION_ID_FRAME_TAGS, SECTION_ID_FRAME_SIDE_DATA_LIST, SECTION_ID_FRAME_LOGS, -1 } },
[SECTION_ID_FRAME_TAGS] = { SECTION_ID_FRAME_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "frame_tags" },
[SECTION_ID_FRAME_SIDE_DATA_LIST] ={ SECTION_ID_FRAME_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME_SIDE_DATA, -1 }, .element_name = "side_data", .unique_name = "frame_side_data_list" },
[SECTION_ID_FRAME_SIDE_DATA] = { SECTION_ID_FRAME_SIDE_DATA, "side_data", 0, { -1 } },
[SECTION_ID_FRAME_LOGS] = { SECTION_ID_FRAME_LOGS, "logs", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME_LOG, -1 } },
[SECTION_ID_FRAME_LOG] = { SECTION_ID_FRAME_LOG, "log", 0, { -1 }, },
[SECTION_ID_LIBRARY_VERSIONS] = { SECTION_ID_LIBRARY_VERSIONS, "library_versions", SECTION_FLAG_IS_ARRAY, { SECTION_ID_LIBRARY_VERSION, -1 } },
[SECTION_ID_LIBRARY_VERSION] = { SECTION_ID_LIBRARY_VERSION, "library_version", 0, { -1 } },
[SECTION_ID_PACKETS] = { SECTION_ID_PACKETS, "packets", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
[SECTION_ID_PACKETS_AND_FRAMES] = { SECTION_ID_PACKETS_AND_FRAMES, "packets_and_frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
[SECTION_ID_PACKET] = { SECTION_ID_PACKET, "packet", 0, { SECTION_ID_PACKET_TAGS, SECTION_ID_PACKET_SIDE_DATA_LIST, -1 } },
[SECTION_ID_PACKET_TAGS] = { SECTION_ID_PACKET_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "packet_tags" },
[SECTION_ID_PACKET_SIDE_DATA_LIST] ={ SECTION_ID_PACKET_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET_SIDE_DATA, -1 }, .element_name = "side_data", .unique_name = "packet_side_data_list" },
[SECTION_ID_PACKET_SIDE_DATA] = { SECTION_ID_PACKET_SIDE_DATA, "side_data", 0, { -1 } },
[SECTION_ID_PIXEL_FORMATS] = { SECTION_ID_PIXEL_FORMATS, "pixel_formats", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PIXEL_FORMAT, -1 } },
[SECTION_ID_PIXEL_FORMAT] = { SECTION_ID_PIXEL_FORMAT, "pixel_format", 0, { SECTION_ID_PIXEL_FORMAT_FLAGS, SECTION_ID_PIXEL_FORMAT_COMPONENTS, -1 } },
[SECTION_ID_PIXEL_FORMAT_FLAGS] = { SECTION_ID_PIXEL_FORMAT_FLAGS, "flags", 0, { -1 }, .unique_name = "pixel_format_flags" },
[SECTION_ID_PIXEL_FORMAT_COMPONENTS] = { SECTION_ID_PIXEL_FORMAT_COMPONENTS, "components", SECTION_FLAG_IS_ARRAY, {SECTION_ID_PIXEL_FORMAT_COMPONENT, -1 }, .unique_name = "pixel_format_components" },
[SECTION_ID_PIXEL_FORMAT_COMPONENT] = { SECTION_ID_PIXEL_FORMAT_COMPONENT, "component", 0, { -1 } },
[SECTION_ID_PROGRAM_STREAM_DISPOSITION] = { SECTION_ID_PROGRAM_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "program_stream_disposition" },
[SECTION_ID_PROGRAM_STREAM_TAGS] = { SECTION_ID_PROGRAM_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_stream_tags" },
[SECTION_ID_PROGRAM] = { SECTION_ID_PROGRAM, "program", 0, { SECTION_ID_PROGRAM_TAGS, SECTION_ID_PROGRAM_STREAMS, -1 } },
[SECTION_ID_PROGRAM_STREAMS] = { SECTION_ID_PROGRAM_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM_STREAM, -1 }, .unique_name = "program_streams" },
[SECTION_ID_PROGRAM_STREAM] = { SECTION_ID_PROGRAM_STREAM, "stream", 0, { SECTION_ID_PROGRAM_STREAM_DISPOSITION, SECTION_ID_PROGRAM_STREAM_TAGS, -1 }, .unique_name = "program_stream" },
[SECTION_ID_PROGRAM_TAGS] = { SECTION_ID_PROGRAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_tags" },
[SECTION_ID_PROGRAM_VERSION] = { SECTION_ID_PROGRAM_VERSION, "program_version", 0, { -1 } },
[SECTION_ID_PROGRAMS] = { SECTION_ID_PROGRAMS, "programs", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM, -1 } },
[SECTION_ID_ROOT] = { SECTION_ID_ROOT, "root", SECTION_FLAG_IS_WRAPPER,
{ SECTION_ID_CHAPTERS, SECTION_ID_FORMAT, SECTION_ID_FRAMES, SECTION_ID_PROGRAMS, SECTION_ID_STREAMS,
SECTION_ID_PACKETS, SECTION_ID_ERROR, SECTION_ID_PROGRAM_VERSION, SECTION_ID_LIBRARY_VERSIONS,
SECTION_ID_PIXEL_FORMATS, -1} },
[SECTION_ID_STREAMS] = { SECTION_ID_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_STREAM, -1 } },
[SECTION_ID_STREAM] = { SECTION_ID_STREAM, "stream", 0, { SECTION_ID_STREAM_DISPOSITION, SECTION_ID_STREAM_TAGS, SECTION_ID_STREAM_SIDE_DATA_LIST, -1 } },
[SECTION_ID_STREAM_DISPOSITION] = { SECTION_ID_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "stream_disposition" },
[SECTION_ID_STREAM_TAGS] = { SECTION_ID_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "stream_tags" },
[SECTION_ID_STREAM_SIDE_DATA_LIST] ={ SECTION_ID_STREAM_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_STREAM_SIDE_DATA, -1 }, .element_name = "side_data", .unique_name = "stream_side_data_list" },
[SECTION_ID_STREAM_SIDE_DATA] = { SECTION_ID_STREAM_SIDE_DATA, "side_data", 0, { -1 } },
[SECTION_ID_SUBTITLE] = { SECTION_ID_SUBTITLE, "subtitle", 0, { -1 } },
};
static const OptionDef *options;
/* FFprobe context */
static const char *input_filename;
static AVInputFormat *iformat = NULL;
static struct AVHashContext *hash;
static const struct {
double bin_val;
double dec_val;
const char *bin_str;
const char *dec_str;
} si_prefixes[] = {
{ 1.0, 1.0, "", "" },
{ 1.024e3, 1e3, "Ki", "K" },
{ 1.048576e6, 1e6, "Mi", "M" },
{ 1.073741824e9, 1e9, "Gi", "G" },
{ 1.099511627776e12, 1e12, "Ti", "T" },
{ 1.125899906842624e15, 1e15, "Pi", "P" },
};
static const char unit_second_str[] = "s" ;
static const char unit_hertz_str[] = "Hz" ;
static const char unit_byte_str[] = "byte" ;
static const char unit_bit_per_second_str[] = "bit/s";
static int nb_streams;
static uint64_t *nb_streams_packets;
static uint64_t *nb_streams_frames;
static int *selected_streams;
#if HAVE_THREADS
pthread_mutex_t log_mutex;
#endif
typedef struct LogBuffer {
char *context_name;
int log_level;
char *log_message;
AVClassCategory category;
char *parent_name;
AVClassCategory parent_category;
}LogBuffer;
static LogBuffer *log_buffer;
static int log_buffer_size;
static void log_callback(void *ptr, int level, const char *fmt, va_list vl)
{
AVClass* avc = ptr ? *(AVClass **) ptr : NULL;
va_list vl2;
char line[1024];
static int print_prefix = 1;
void *new_log_buffer;
va_copy(vl2, vl);
av_log_default_callback(ptr, level, fmt, vl);
av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
va_end(vl2);
#if HAVE_THREADS
pthread_mutex_lock(&log_mutex);
new_log_buffer = av_realloc_array(log_buffer, log_buffer_size + 1, sizeof(*log_buffer));
if (new_log_buffer) {
char *msg;
int i;
log_buffer = new_log_buffer;
memset(&log_buffer[log_buffer_size], 0, sizeof(log_buffer[log_buffer_size]));
log_buffer[log_buffer_size].context_name= avc ? av_strdup(avc->item_name(ptr)) : NULL;
if (avc) {
if (avc->get_category) log_buffer[log_buffer_size].category = avc->get_category(ptr);
else log_buffer[log_buffer_size].category = avc->category;
}
log_buffer[log_buffer_size].log_level = level;
msg = log_buffer[log_buffer_size].log_message = av_strdup(line);
for (i=strlen(msg) - 1; i>=0 && msg[i] == '\n'; i--) {
msg[i] = 0;
}
if (avc && avc->parent_log_context_offset) {
AVClass** parent = *(AVClass ***) (((uint8_t *) ptr) +
avc->parent_log_context_offset);
if (parent && *parent) {
log_buffer[log_buffer_size].parent_name = av_strdup((*parent)->item_name(parent));
log_buffer[log_buffer_size].parent_category =
(*parent)->get_category ? (*parent)->get_category(parent) :(*parent)->category;
}
}
log_buffer_size ++;
}
pthread_mutex_unlock(&log_mutex);
#endif
}
static void ffprobe_cleanup(int ret)
{
int i;
for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
av_dict_free(&(sections[i].entries_to_show));
#if HAVE_THREADS
pthread_mutex_destroy(&log_mutex);
#endif
}
struct unit_value {
union { double d; long long int i; } val;
const char *unit;
};
static char *value_string(char *buf, int buf_size, struct unit_value uv)
{
double vald;
long long int vali;
int show_float = 0;
if (uv.unit == unit_second_str) {
vald = uv.val.d;
show_float = 1;
} else {
vald = vali = uv.val.i;
}
if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
double secs;
int hours, mins;
secs = vald;
mins = (int)secs / 60;
secs = secs - mins * 60;
hours = mins / 60;
mins %= 60;
snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
} else {
const char *prefix_string = "";
if (use_value_prefix && vald > 1) {
long long int index;
if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
index = (long long int) (log2(vald)) / 10;
index = av_clip(index, 0, FF_ARRAY_ELEMS(si_prefixes) - 1);
vald /= si_prefixes[index].bin_val;
prefix_string = si_prefixes[index].bin_str;
} else {
index = (long long int) (log10(vald)) / 3;
index = av_clip(index, 0, FF_ARRAY_ELEMS(si_prefixes) - 1);
vald /= si_prefixes[index].dec_val;
prefix_string = si_prefixes[index].dec_str;
}
vali = vald;
}
if (show_float || (use_value_prefix && vald != (long long int)vald))
snprintf(buf, buf_size, "%f", vald);
else
snprintf(buf, buf_size, "%lld", vali);
av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
prefix_string, show_value_unit ? uv.unit : "");
}
return buf;
}
/* WRITERS API */
typedef struct WriterContext WriterContext;
#define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
#define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
typedef enum {
WRITER_STRING_VALIDATION_FAIL,
WRITER_STRING_VALIDATION_REPLACE,
WRITER_STRING_VALIDATION_IGNORE,
WRITER_STRING_VALIDATION_NB
} StringValidation;
typedef struct Writer {
const AVClass *priv_class; ///< private class of the writer, if any
int priv_size; ///< private size for the writer context
const char *name;
int (*init) (WriterContext *wctx);
void (*uninit)(WriterContext *wctx);
void (*print_section_header)(WriterContext *wctx);
void (*print_section_footer)(WriterContext *wctx);
void (*print_integer) (WriterContext *wctx, const char *, long long int);
void (*print_rational) (WriterContext *wctx, AVRational *q, char *sep);
void (*print_string) (WriterContext *wctx, const char *, const char *);
int flags; ///< a combination or WRITER_FLAG_*
} Writer;
#define SECTION_MAX_NB_LEVELS 10
struct WriterContext {
const AVClass *class; ///< class of the writer
const Writer *writer; ///< the Writer of which this is an instance
char *name; ///< name of this writer instance
void *priv; ///< private data for use by the filter
const struct section *sections; ///< array containing all sections
int nb_sections; ///< number of sections
int level; ///< current level, starting from 0
/** number of the item printed in the given section, starting from 0 */
unsigned int nb_item[SECTION_MAX_NB_LEVELS];
/** section per each level */
const struct section *section[SECTION_MAX_NB_LEVELS];
AVBPrint section_pbuf[SECTION_MAX_NB_LEVELS]; ///< generic print buffer dedicated to each section,
/// used by various writers
unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
unsigned int nb_section_frame; ///< number of the frame section in case we are in "packets_and_frames" section
unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
int string_validation;
char *string_validation_replacement;
unsigned int string_validation_utf8_flags;
};
static const char *writer_get_name(void *p)
{
WriterContext *wctx = p;
return wctx->writer->name;
}
#define OFFSET(x) offsetof(WriterContext, x)
static const AVOption writer_options[] = {
{ "string_validation", "set string validation mode",
OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
{ "sv", "set string validation mode",
OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
{ "ignore", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_IGNORE}, .unit = "sv" },
{ "replace", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_REPLACE}, .unit = "sv" },
{ "fail", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_FAIL}, .unit = "sv" },
{ "string_validation_replacement", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str=""}},
{ "svr", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str="\xEF\xBF\xBD"}},
{ NULL }
};
static void *writer_child_next(void *obj, void *prev)
{
WriterContext *ctx = obj;
if (!prev && ctx->writer && ctx->writer->priv_class && ctx->priv)
return ctx->priv;
return NULL;
}
static const AVClass writer_class = {
.class_name = "Writer",
.item_name = writer_get_name,
.option = writer_options,
.version = LIBAVUTIL_VERSION_INT,
.child_next = writer_child_next,
};
static void writer_close(WriterContext **wctx)
{
int i;
if (!*wctx)
return;
if ((*wctx)->writer->uninit)
(*wctx)->writer->uninit(*wctx);
for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
av_bprint_finalize(&(*wctx)->section_pbuf[i], NULL);
if ((*wctx)->writer->priv_class)
av_opt_free((*wctx)->priv);
av_freep(&((*wctx)->priv));
av_opt_free(*wctx);
av_freep(wctx);
}
static void bprint_bytes(AVBPrint *bp, const uint8_t *ubuf, size_t ubuf_size)
{
int i;
av_bprintf(bp, "0X");
for (i = 0; i < ubuf_size; i++)
av_bprintf(bp, "%02X", ubuf[i]);
}
static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,
const struct section *sections, int nb_sections)
{
int i, ret = 0;
if (!(*wctx = av_mallocz(sizeof(WriterContext)))) {
ret = AVERROR(ENOMEM);
goto fail;
}
if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
ret = AVERROR(ENOMEM);
goto fail;
}
(*wctx)->class = &writer_class;
(*wctx)->writer = writer;
(*wctx)->level = -1;
(*wctx)->sections = sections;
(*wctx)->nb_sections = nb_sections;
av_opt_set_defaults(*wctx);
if (writer->priv_class) {
void *priv_ctx = (*wctx)->priv;
*((const AVClass **)priv_ctx) = writer->priv_class;
av_opt_set_defaults(priv_ctx);
}
/* convert options to dictionary */
if (args) {
AVDictionary *opts = NULL;
AVDictionaryEntry *opt = NULL;
if ((ret = av_dict_parse_string(&opts, args, "=", ":", 0)) < 0) {
av_log(*wctx, AV_LOG_ERROR, "Failed to parse option string '%s' provided to writer context\n", args);
av_dict_free(&opts);
goto fail;
}
while ((opt = av_dict_get(opts, "", opt, AV_DICT_IGNORE_SUFFIX))) {
if ((ret = av_opt_set(*wctx, opt->key, opt->value, AV_OPT_SEARCH_CHILDREN)) < 0) {
av_log(*wctx, AV_LOG_ERROR, "Failed to set option '%s' with value '%s' provided to writer context\n",
opt->key, opt->value);
av_dict_free(&opts);
goto fail;
}
}
av_dict_free(&opts);
}
/* validate replace string */
{
const uint8_t *p = (*wctx)->string_validation_replacement;
const uint8_t *endp = p + strlen(p);
while (*p) {
const uint8_t *p0 = p;
int32_t code;
ret = av_utf8_decode(&code, &p, endp, (*wctx)->string_validation_utf8_flags);
if (ret < 0) {
AVBPrint bp;
av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
bprint_bytes(&bp, p0, p-p0),
av_log(wctx, AV_LOG_ERROR,
"Invalid UTF8 sequence %s found in string validation replace '%s'\n",
bp.str, (*wctx)->string_validation_replacement);
return ret;
}
}
}
for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
av_bprint_init(&(*wctx)->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);
if ((*wctx)->writer->init)
ret = (*wctx)->writer->init(*wctx);
if (ret < 0)
goto fail;
return 0;
fail:
writer_close(wctx);
return ret;
}
static inline void writer_print_section_header(WriterContext *wctx,
int section_id)
{
int parent_section_id;
wctx->level++;
av_assert0(wctx->level < SECTION_MAX_NB_LEVELS);
parent_section_id = wctx->level ?
(wctx->section[wctx->level-1])->id : SECTION_ID_NONE;
wctx->nb_item[wctx->level] = 0;
wctx->section[wctx->level] = &wctx->sections[section_id];
if (section_id == SECTION_ID_PACKETS_AND_FRAMES) {
wctx->nb_section_packet = wctx->nb_section_frame =
wctx->nb_section_packet_frame = 0;
} else if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
wctx->nb_section_packet_frame = section_id == SECTION_ID_PACKET ?
wctx->nb_section_packet : wctx->nb_section_frame;
}
if (wctx->writer->print_section_header)
wctx->writer->print_section_header(wctx);
}
static inline void writer_print_section_footer(WriterContext *wctx)
{
int section_id = wctx->section[wctx->level]->id;
int parent_section_id = wctx->level ?
wctx->section[wctx->level-1]->id : SECTION_ID_NONE;
if (parent_section_id != SECTION_ID_NONE)
wctx->nb_item[wctx->level-1]++;
if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
if (section_id == SECTION_ID_PACKET) wctx->nb_section_packet++;
else wctx->nb_section_frame++;
}
if (wctx->writer->print_section_footer)
wctx->writer->print_section_footer(wctx);
wctx->level--;
}
static inline void writer_print_integer(WriterContext *wctx,
const char *key, long long int val)
{
const struct section *section = wctx->section[wctx->level];
if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
wctx->writer->print_integer(wctx, key, val);
wctx->nb_item[wctx->level]++;
}
}
static inline int validate_string(WriterContext *wctx, char **dstp, const char *src)
{
const uint8_t *p, *endp;
AVBPrint dstbuf;
int invalid_chars_nb = 0, ret = 0;
av_bprint_init(&dstbuf, 0, AV_BPRINT_SIZE_UNLIMITED);
endp = src + strlen(src);
for (p = (uint8_t *)src; *p;) {
uint32_t code;
int invalid = 0;
const uint8_t *p0 = p;
if (av_utf8_decode(&code, &p, endp, wctx->string_validation_utf8_flags) < 0) {
AVBPrint bp;
av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
bprint_bytes(&bp, p0, p-p0);
av_log(wctx, AV_LOG_DEBUG,
"Invalid UTF-8 sequence %s found in string '%s'\n", bp.str, src);
invalid = 1;
}
if (invalid) {
invalid_chars_nb++;
switch (wctx->string_validation) {
case WRITER_STRING_VALIDATION_FAIL:
av_log(wctx, AV_LOG_ERROR,
"Invalid UTF-8 sequence found in string '%s'\n", src);
ret = AVERROR_INVALIDDATA;
goto end;
break;
case WRITER_STRING_VALIDATION_REPLACE:
av_bprintf(&dstbuf, "%s", wctx->string_validation_replacement);
break;
}
}
if (!invalid || wctx->string_validation == WRITER_STRING_VALIDATION_IGNORE)
av_bprint_append_data(&dstbuf, p0, p-p0);
}
if (invalid_chars_nb && wctx->string_validation == WRITER_STRING_VALIDATION_REPLACE) {
av_log(wctx, AV_LOG_WARNING,
"%d invalid UTF-8 sequence(s) found in string '%s', replaced with '%s'\n",
invalid_chars_nb, src, wctx->string_validation_replacement);
}
end:
av_bprint_finalize(&dstbuf, dstp);
return ret;
}
#define PRINT_STRING_OPT 1
#define PRINT_STRING_VALIDATE 2
static inline int writer_print_string(WriterContext *wctx,
const char *key, const char *val, int flags)
{
const struct section *section = wctx->section[wctx->level];
int ret = 0;
if ((flags & PRINT_STRING_OPT)
&& !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
return 0;
if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
if (flags & PRINT_STRING_VALIDATE) {
char *key1 = NULL, *val1 = NULL;
ret = validate_string(wctx, &key1, key);
if (ret < 0) goto end;
ret = validate_string(wctx, &val1, val);
if (ret < 0) goto end;
wctx->writer->print_string(wctx, key1, val1);
end:
if (ret < 0) {
av_log(wctx, AV_LOG_ERROR,
"Invalid key=value string combination %s=%s in section %s\n",
key, val, section->unique_name);
}
av_free(key1);
av_free(val1);
} else {
wctx->writer->print_string(wctx, key, val);
}
wctx->nb_item[wctx->level]++;
}
return ret;
}
static inline void writer_print_rational(WriterContext *wctx,
const char *key, AVRational q, char sep)
{
AVBPrint buf;
av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
writer_print_string(wctx, key, buf.str, 0);
}
static void writer_print_time(WriterContext *wctx, const char *key,
int64_t ts, const AVRational *time_base, int is_duration)
{
char buf[128];
if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
} else {
double d = ts * av_q2d(*time_base);
struct unit_value uv;
uv.val.d = d;
uv.unit = unit_second_str;
value_string(buf, sizeof(buf), uv);
writer_print_string(wctx, key, buf, 0);
}
}
static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
{
if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
} else {
writer_print_integer(wctx, key, ts);
}
}
static void writer_print_data(WriterContext *wctx, const char *name,
uint8_t *data, int size)
{
AVBPrint bp;
int offset = 0, l, i;
av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
av_bprintf(&bp, "\n");
while (size) {
av_bprintf(&bp, "%08x: ", offset);
l = FFMIN(size, 16);
for (i = 0; i < l; i++) {
av_bprintf(&bp, "%02x", data[i]);
if (i & 1)
av_bprintf(&bp, " ");
}
av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
for (i = 0; i < l; i++)
av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
av_bprintf(&bp, "\n");
offset += l;
data += l;
size -= l;
}
writer_print_string(wctx, name, bp.str, 0);
av_bprint_finalize(&bp, NULL);
}
static void writer_print_data_hash(WriterContext *wctx, const char *name,
uint8_t *data, int size)
{
char *p, buf[AV_HASH_MAX_SIZE * 2 + 64] = { 0 };
if (!hash)
return;
av_hash_init(hash);
av_hash_update(hash, data, size);
snprintf(buf, sizeof(buf), "%s:", av_hash_get_name(hash));
p = buf + strlen(buf);
av_hash_final_hex(hash, p, buf + sizeof(buf) - p);
writer_print_string(wctx, name, buf, 0);
}
static void writer_print_integers(WriterContext *wctx, const char *name,
uint8_t *data, int size, const char *format,
int columns, int bytes, int offset_add)
{
AVBPrint bp;
int offset = 0, l, i;
av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
av_bprintf(&bp, "\n");
while (size) {
av_bprintf(&bp, "%08x: ", offset);
l = FFMIN(size, columns);
for (i = 0; i < l; i++) {
if (bytes == 1) av_bprintf(&bp, format, *data);
else if (bytes == 2) av_bprintf(&bp, format, AV_RN16(data));
else if (bytes == 4) av_bprintf(&bp, format, AV_RN32(data));
data += bytes;
size --;
}
av_bprintf(&bp, "\n");
offset += offset_add;
}
writer_print_string(wctx, name, bp.str, 0);
av_bprint_finalize(&bp, NULL);
}
#define MAX_REGISTERED_WRITERS_NB 64
static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
static int writer_register(const Writer *writer)
{
static int next_registered_writer_idx = 0;
if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
return AVERROR(ENOMEM);
registered_writers[next_registered_writer_idx++] = writer;
return 0;
}
static const Writer *writer_get_by_name(const char *name)
{
int i;
for (i = 0; registered_writers[i]; i++)
if (!strcmp(registered_writers[i]->name, name))
return registered_writers[i];
return NULL;
}
/* WRITERS */
#define DEFINE_WRITER_CLASS(name) \
static const char *name##_get_name(void *ctx) \
{ \
return #name ; \
} \
static const AVClass name##_class = { \
.class_name = #name, \
.item_name = name##_get_name, \
.option = name##_options \
}
/* Default output */
typedef struct DefaultContext {
const AVClass *class;
int nokey;
int noprint_wrappers;
int nested_section[SECTION_MAX_NB_LEVELS];
} DefaultContext;
#undef OFFSET
#define OFFSET(x) offsetof(DefaultContext, x)
static const AVOption default_options[] = {
{ "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{ "nw", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{ "nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{ "nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(default);
/* lame uppercasing routine, assumes the string is lower case ASCII */
static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
{
int i;
for (i = 0; src[i] && i < dst_size-1; i++)
dst[i] = av_toupper(src[i]);
dst[i] = 0;
return dst;
}
static void default_print_section_header(WriterContext *wctx)
{
DefaultContext *def = wctx->priv;
char buf[32];
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
av_bprint_clear(&wctx->section_pbuf[wctx->level]);
if (parent_section &&
!(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
def->nested_section[wctx->level] = 1;
av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
wctx->section_pbuf[wctx->level-1].str,
upcase_string(buf, sizeof(buf),
av_x_if_null(section->element_name, section->name)));
}
if (def->noprint_wrappers || def->nested_section[wctx->level])
return;
if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
printf("[%s]\n", upcase_string(buf, sizeof(buf), section->name));
}
static void default_print_section_footer(WriterContext *wctx)
{
DefaultContext *def = wctx->priv;
const struct section *section = wctx->section[wctx->level];
char buf[32];
if (def->noprint_wrappers || def->nested_section[wctx->level])
return;
if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
printf("[/%s]\n", upcase_string(buf, sizeof(buf), section->name));
}
static void default_print_str(WriterContext *wctx, const char *key, const char *value)
{
DefaultContext *def = wctx->priv;
if (!def->nokey)
printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
printf("%s\n", value);
}
static void default_print_int(WriterContext *wctx, const char *key, long long int value)
{
DefaultContext *def = wctx->priv;
if (!def->nokey)
printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
printf("%lld\n", value);
}
static const Writer default_writer = {
.name = "default",
.priv_size = sizeof(DefaultContext),
.print_section_header = default_print_section_header,
.print_section_footer = default_print_section_footer,
.print_integer = default_print_int,
.print_string = default_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
.priv_class = &default_class,
};
/* Compact output */
/**
* Apply C-language-like string escaping.
*/
static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
{
const char *p;
for (p = src; *p; p++) {
switch (*p) {
case '\b': av_bprintf(dst, "%s", "\\b"); break;
case '\f': av_bprintf(dst, "%s", "\\f"); break;
case '\n': av_bprintf(dst, "%s", "\\n"); break;
case '\r': av_bprintf(dst, "%s", "\\r"); break;
case '\\': av_bprintf(dst, "%s", "\\\\"); break;
default:
if (*p == sep)
av_bprint_chars(dst, '\\', 1);
av_bprint_chars(dst, *p, 1);
}
}
return dst->str;
}
/**
* Quote fields containing special characters, check RFC4180.
*/
static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
{
char meta_chars[] = { sep, '"', '\n', '\r', '\0' };
int needs_quoting = !!src[strcspn(src, meta_chars)];
if (needs_quoting)
av_bprint_chars(dst, '"', 1);
for (; *src; src++) {
if (*src == '"')
av_bprint_chars(dst, '"', 1);
av_bprint_chars(dst, *src, 1);
}
if (needs_quoting)
av_bprint_chars(dst, '"', 1);
return dst->str;
}
static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
{
return src;
}
typedef struct CompactContext {
const AVClass *class;
char *item_sep_str;
char item_sep;
int nokey;
int print_section;
char *escape_mode_str;
const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
int nested_section[SECTION_MAX_NB_LEVELS];
int has_nested_elems[SECTION_MAX_NB_LEVELS];
int terminate_line[SECTION_MAX_NB_LEVELS];
} CompactContext;
#undef OFFSET
#define OFFSET(x) offsetof(CompactContext, x)
static const AVOption compact_options[]= {
{"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
{"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
{"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
{"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
{"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(compact);
static av_cold int compact_init(WriterContext *wctx)
{
CompactContext *compact = wctx->priv;
if (strlen(compact->item_sep_str) != 1) {
av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
compact->item_sep_str);
return AVERROR(EINVAL);
}
compact->item_sep = compact->item_sep_str[0];
if (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
else if (!strcmp(compact->escape_mode_str, "c" )) compact->escape_str = c_escape_str;
else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
else {
av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
return AVERROR(EINVAL);
}
return 0;
}
static void compact_print_section_header(WriterContext *wctx)
{
CompactContext *compact = wctx->priv;
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
compact->terminate_line[wctx->level] = 1;
compact->has_nested_elems[wctx->level] = 0;
av_bprint_clear(&wctx->section_pbuf[wctx->level]);
if (!(section->flags & SECTION_FLAG_IS_ARRAY) && parent_section &&
!(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
compact->nested_section[wctx->level] = 1;
compact->has_nested_elems[wctx->level-1] = 1;
av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
wctx->section_pbuf[wctx->level-1].str,
(char *)av_x_if_null(section->element_name, section->name));
wctx->nb_item[wctx->level] = wctx->nb_item[wctx->level-1];
} else {
if (parent_section && compact->has_nested_elems[wctx->level-1] &&
(section->flags & SECTION_FLAG_IS_ARRAY)) {
compact->terminate_line[wctx->level-1] = 0;
printf("\n");
}
if (compact->print_section &&
!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
printf("%s%c", section->name, compact->item_sep);
}
}
static void compact_print_section_footer(WriterContext *wctx)
{
CompactContext *compact = wctx->priv;
if (!compact->nested_section[wctx->level] &&
compact->terminate_line[wctx->level] &&
!(wctx->section[wctx->level]->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
printf("\n");
}
static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
{
CompactContext *compact = wctx->priv;
AVBPrint buf;
if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
if (!compact->nokey)
printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
av_bprint_finalize(&buf, NULL);
}
static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
{
CompactContext *compact = wctx->priv;
if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
if (!compact->nokey)
printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
printf("%lld", value);
}
static const Writer compact_writer = {
.name = "compact",
.priv_size = sizeof(CompactContext),
.init = compact_init,
.print_section_header = compact_print_section_header,
.print_section_footer = compact_print_section_footer,
.print_integer = compact_print_int,
.print_string = compact_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
.priv_class = &compact_class,
};
/* CSV output */
#undef OFFSET
#define OFFSET(x) offsetof(CompactContext, x)
static const AVOption csv_options[] = {
{"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, CHAR_MIN, CHAR_MAX },
{"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, CHAR_MIN, CHAR_MAX },
{"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
{"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
{"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(csv);
static const Writer csv_writer = {
.name = "csv",
.priv_size = sizeof(CompactContext),
.init = compact_init,
.print_section_header = compact_print_section_header,
.print_section_footer = compact_print_section_footer,
.print_integer = compact_print_int,
.print_string = compact_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
.priv_class = &csv_class,
};
/* Flat output */
typedef struct FlatContext {
const AVClass *class;
const char *sep_str;
char sep;
int hierarchical;
} FlatContext;
#undef OFFSET
#define OFFSET(x) offsetof(FlatContext, x)
static const AVOption flat_options[]= {
{"sep_char", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, CHAR_MIN, CHAR_MAX },
{"s", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, CHAR_MIN, CHAR_MAX },
{"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(flat);
static av_cold int flat_init(WriterContext *wctx)
{
FlatContext *flat = wctx->priv;
if (strlen(flat->sep_str) != 1) {
av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
flat->sep_str);
return AVERROR(EINVAL);
}
flat->sep = flat->sep_str[0];
return 0;
}
static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
{
const char *p;
for (p = src; *p; p++) {
if (!((*p >= '0' && *p <= '9') ||
(*p >= 'a' && *p <= 'z') ||
(*p >= 'A' && *p <= 'Z')))
av_bprint_chars(dst, '_', 1);
else
av_bprint_chars(dst, *p, 1);
}
return dst->str;
}
static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
{
const char *p;
for (p = src; *p; p++) {
switch (*p) {
case '\n': av_bprintf(dst, "%s", "\\n"); break;
case '\r': av_bprintf(dst, "%s", "\\r"); break;
case '\\': av_bprintf(dst, "%s", "\\\\"); break;
case '"': av_bprintf(dst, "%s", "\\\""); break;
case '`': av_bprintf(dst, "%s", "\\`"); break;
case '$': av_bprintf(dst, "%s", "\\$"); break;
default: av_bprint_chars(dst, *p, 1); break;
}
}
return dst->str;
}
static void flat_print_section_header(WriterContext *wctx)
{
FlatContext *flat = wctx->priv;
AVBPrint *buf = &wctx->section_pbuf[wctx->level];
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
/* build section header */
av_bprint_clear(buf);
if (!parent_section)
return;
av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
if (flat->hierarchical ||
!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
av_bprintf(buf, "%s%s", wctx->section[wctx->level]->name, flat->sep_str);
if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
av_bprintf(buf, "%d%s", n, flat->sep_str);
}
}
}
static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
{
printf("%s%s=%lld\n", wctx->section_pbuf[wctx->level].str, key, value);
}
static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
{
FlatContext *flat = wctx->priv;
AVBPrint buf;
printf("%s", wctx->section_pbuf[wctx->level].str);
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
av_bprint_clear(&buf);
printf("\"%s\"\n", flat_escape_value_str(&buf, value));
av_bprint_finalize(&buf, NULL);
}
static const Writer flat_writer = {
.name = "flat",
.priv_size = sizeof(FlatContext),
.init = flat_init,
.print_section_header = flat_print_section_header,
.print_integer = flat_print_int,
.print_string = flat_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
.priv_class = &flat_class,
};
/* INI format output */
typedef struct INIContext {
const AVClass *class;
int hierarchical;
} INIContext;
#undef OFFSET
#define OFFSET(x) offsetof(INIContext, x)
static const AVOption ini_options[] = {
{"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(ini);
static char *ini_escape_str(AVBPrint *dst, const char *src)
{
int i = 0;
char c = 0;
while (c = src[i++]) {
switch (c) {
case '\b': av_bprintf(dst, "%s", "\\b"); break;
case '\f': av_bprintf(dst, "%s", "\\f"); break;
case '\n': av_bprintf(dst, "%s", "\\n"); break;
case '\r': av_bprintf(dst, "%s", "\\r"); break;
case '\t': av_bprintf(dst, "%s", "\\t"); break;
case '\\':
case '#' :
case '=' :
case ':' : av_bprint_chars(dst, '\\', 1);
default:
if ((unsigned char)c < 32)
av_bprintf(dst, "\\x00%02x", c & 0xff);
else
av_bprint_chars(dst, c, 1);
break;
}
}
return dst->str;
}
static void ini_print_section_header(WriterContext *wctx)
{
INIContext *ini = wctx->priv;
AVBPrint *buf = &wctx->section_pbuf[wctx->level];
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
av_bprint_clear(buf);
if (!parent_section) {
printf("# ffprobe output\n\n");
return;
}
if (wctx->nb_item[wctx->level-1])
printf("\n");
av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
if (ini->hierarchical ||
!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
av_bprintf(buf, "%s%s", buf->str[0] ? "." : "", wctx->section[wctx->level]->name);
if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
av_bprintf(buf, ".%d", n);
}
}
if (!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
printf("[%s]\n", buf->str);
}
static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
{
AVBPrint buf;
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("%s=", ini_escape_str(&buf, key));
av_bprint_clear(&buf);
printf("%s\n", ini_escape_str(&buf, value));
av_bprint_finalize(&buf, NULL);
}
static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
{
printf("%s=%lld\n", key, value);
}
static const Writer ini_writer = {
.name = "ini",
.priv_size = sizeof(INIContext),
.print_section_header = ini_print_section_header,
.print_integer = ini_print_int,
.print_string = ini_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
.priv_class = &ini_class,
};
/* JSON output */
typedef struct JSONContext {
const AVClass *class;
int indent_level;
int compact;
const char *item_sep, *item_start_end;
} JSONContext;
#undef OFFSET
#define OFFSET(x) offsetof(JSONContext, x)
static const AVOption json_options[]= {
{ "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{ "c", "enable compact output", OFFSET(compact), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{ NULL }
};
DEFINE_WRITER_CLASS(json);
static av_cold int json_init(WriterContext *wctx)
{
JSONContext *json = wctx->priv;
json->item_sep = json->compact ? ", " : ",\n";
json->item_start_end = json->compact ? " " : "\n";
return 0;
}
static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
{
static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
const char *p;
for (p = src; *p; p++) {
char *s = strchr(json_escape, *p);
if (s) {
av_bprint_chars(dst, '\\', 1);
av_bprint_chars(dst, json_subst[s - json_escape], 1);
} else if ((unsigned char)*p < 32) {
av_bprintf(dst, "\\u00%02x", *p & 0xff);
} else {
av_bprint_chars(dst, *p, 1);
}
}
return dst->str;
}
#define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
static void json_print_section_header(WriterContext *wctx)
{
JSONContext *json = wctx->priv;
AVBPrint buf;
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
if (wctx->level && wctx->nb_item[wctx->level-1])
printf(",\n");
if (section->flags & SECTION_FLAG_IS_WRAPPER) {
printf("{\n");
json->indent_level++;
} else {
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
json_escape_str(&buf, section->name, wctx);
JSON_INDENT();
json->indent_level++;
if (section->flags & SECTION_FLAG_IS_ARRAY) {
printf("\"%s\": [\n", buf.str);
} else if (parent_section && !(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
printf("\"%s\": {%s", buf.str, json->item_start_end);
} else {
printf("{%s", json->item_start_end);
/* this is required so the parser can distinguish between packets and frames */
if (parent_section && parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
if (!json->compact)
JSON_INDENT();
printf("\"type\": \"%s\"%s", section->name, json->item_sep);
}
}
av_bprint_finalize(&buf, NULL);
}
}
static void json_print_section_footer(WriterContext *wctx)
{
JSONContext *json = wctx->priv;
const struct section *section = wctx->section[wctx->level];
if (wctx->level == 0) {
json->indent_level--;
printf("\n}\n");
} else if (section->flags & SECTION_FLAG_IS_ARRAY) {
printf("\n");
json->indent_level--;
JSON_INDENT();
printf("]");
} else {
printf("%s", json->item_start_end);
json->indent_level--;
if (!json->compact)
JSON_INDENT();
printf("}");
}
}
static inline void json_print_item_str(WriterContext *wctx,
const char *key, const char *value)
{
AVBPrint buf;
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("\"%s\":", json_escape_str(&buf, key, wctx));
av_bprint_clear(&buf);
printf(" \"%s\"", json_escape_str(&buf, value, wctx));
av_bprint_finalize(&buf, NULL);
}
static void json_print_str(WriterContext *wctx, const char *key, const char *value)
{
JSONContext *json = wctx->priv;
if (wctx->nb_item[wctx->level])
printf("%s", json->item_sep);
if (!json->compact)
JSON_INDENT();
json_print_item_str(wctx, key, value);
}
static void json_print_int(WriterContext *wctx, const char *key, long long int value)
{
JSONContext *json = wctx->priv;
AVBPrint buf;
if (wctx->nb_item[wctx->level])
printf("%s", json->item_sep);
if (!json->compact)
JSON_INDENT();
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
av_bprint_finalize(&buf, NULL);
}
static const Writer json_writer = {
.name = "json",
.priv_size = sizeof(JSONContext),
.init = json_init,
.print_section_header = json_print_section_header,
.print_section_footer = json_print_section_footer,
.print_integer = json_print_int,
.print_string = json_print_str,
.flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
.priv_class = &json_class,
};
/* XML output */
typedef struct XMLContext {
const AVClass *class;
int within_tag;
int indent_level;
int fully_qualified;
int xsd_strict;
} XMLContext;
#undef OFFSET
#define OFFSET(x) offsetof(XMLContext, x)
static const AVOption xml_options[] = {
{"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{"q", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{"xsd_strict", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{"x", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(xml);
static av_cold int xml_init(WriterContext *wctx)
{
XMLContext *xml = wctx->priv;
if (xml->xsd_strict) {
xml->fully_qualified = 1;
#define CHECK_COMPLIANCE(opt, opt_name) \
if (opt) { \
av_log(wctx, AV_LOG_ERROR, \
"XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
"You need to disable such option with '-no%s'\n", opt_name, opt_name); \
return AVERROR(EINVAL); \
}
CHECK_COMPLIANCE(show_private_data, "private");
CHECK_COMPLIANCE(show_value_unit, "unit");
CHECK_COMPLIANCE(use_value_prefix, "prefix");
if (do_show_frames && do_show_packets) {
av_log(wctx, AV_LOG_ERROR,
"Interleaved frames and packets are not allowed in XSD. "
"Select only one between the -show_frames and the -show_packets options.\n");
return AVERROR(EINVAL);
}
}
return 0;
}
static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
{
const char *p;
for (p = src; *p; p++) {
switch (*p) {
case '&' : av_bprintf(dst, "%s", "&"); break;
case '<' : av_bprintf(dst, "%s", "<"); break;
case '>' : av_bprintf(dst, "%s", ">"); break;
case '"' : av_bprintf(dst, "%s", """); break;
case '\'': av_bprintf(dst, "%s", "'"); break;
default: av_bprint_chars(dst, *p, 1);
}
}
return dst->str;
}
#define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
static void xml_print_section_header(WriterContext *wctx)
{
XMLContext *xml = wctx->priv;
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
if (wctx->level == 0) {
const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
"xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
"xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
printf("<%sffprobe%s>\n",
xml->fully_qualified ? "ffprobe:" : "",
xml->fully_qualified ? qual : "");
return;
}
if (xml->within_tag) {
xml->within_tag = 0;
printf(">\n");
}
if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
xml->indent_level++;
} else {
if (parent_section && (parent_section->flags & SECTION_FLAG_IS_WRAPPER) &&
wctx->level && wctx->nb_item[wctx->level-1])
printf("\n");
xml->indent_level++;
if (section->flags & SECTION_FLAG_IS_ARRAY) {
XML_INDENT(); printf("<%s>\n", section->name);
} else {
XML_INDENT(); printf("<%s ", section->name);
xml->within_tag = 1;
}
}
}
static void xml_print_section_footer(WriterContext *wctx)
{
XMLContext *xml = wctx->priv;
const struct section *section = wctx->section[wctx->level];
if (wctx->level == 0) {
printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
} else if (xml->within_tag) {
xml->within_tag = 0;
printf("/>\n");
xml->indent_level--;
} else if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
xml->indent_level--;
} else {
XML_INDENT(); printf("</%s>\n", section->name);
xml->indent_level--;
}
}
static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
{
AVBPrint buf;
XMLContext *xml = wctx->priv;
const struct section *section = wctx->section[wctx->level];
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
XML_INDENT();
printf("<%s key=\"%s\"",
section->element_name, xml_escape_str(&buf, key, wctx));
av_bprint_clear(&buf);
printf(" value=\"%s\"/>\n", xml_escape_str(&buf, value, wctx));
} else {
if (wctx->nb_item[wctx->level])
printf(" ");
printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
}
av_bprint_finalize(&buf, NULL);
}
static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
{
if (wctx->nb_item[wctx->level])
printf(" ");
printf("%s=\"%lld\"", key, value);
}
static Writer xml_writer = {
.name = "xml",
.priv_size = sizeof(XMLContext),
.init = xml_init,
.print_section_header = xml_print_section_header,
.print_section_footer = xml_print_section_footer,
.print_integer = xml_print_int,
.print_string = xml_print_str,
.flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
.priv_class = &xml_class,
};
static void writer_register_all(void)
{
static int initialized;
if (initialized)
return;
initialized = 1;
writer_register(&default_writer);
writer_register(&compact_writer);
writer_register(&csv_writer);
writer_register(&flat_writer);
writer_register(&ini_writer);
writer_register(&json_writer);
writer_register(&xml_writer);
}
#define print_fmt(k, f, ...) do { \
av_bprint_clear(&pbuf); \
av_bprintf(&pbuf, f, __VA_ARGS__); \
writer_print_string(w, k, pbuf.str, 0); \
} while (0)
#define print_int(k, v) writer_print_integer(w, k, v)
#define print_q(k, v, s) writer_print_rational(w, k, v, s)
#define print_str(k, v) writer_print_string(w, k, v, 0)
#define print_str_opt(k, v) writer_print_string(w, k, v, PRINT_STRING_OPT)
#define print_str_validate(k, v) writer_print_string(w, k, v, PRINT_STRING_VALIDATE)
#define print_time(k, v, tb) writer_print_time(w, k, v, tb, 0)
#define print_ts(k, v) writer_print_ts(w, k, v, 0)
#define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
#define print_duration_ts(k, v) writer_print_ts(w, k, v, 1)
#define print_val(k, v, u) do { \
struct unit_value uv; \
uv.val.i = v; \
uv.unit = u; \
writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
} while (0)
#define print_section_header(s) writer_print_section_header(w, s)
#define print_section_footer(s) writer_print_section_footer(w, s)
#define REALLOCZ_ARRAY_STREAM(ptr, cur_n, new_n) \
{ \
ret = av_reallocp_array(&(ptr), (new_n), sizeof(*(ptr))); \
if (ret < 0) \
goto end; \
memset( (ptr) + (cur_n), 0, ((new_n) - (cur_n)) * sizeof(*(ptr)) ); \
}
static inline int show_tags(WriterContext *w, AVDictionary *tags, int section_id)
{
AVDictionaryEntry *tag = NULL;
int ret = 0;
if (!tags)
return 0;
writer_print_section_header(w, section_id);
while ((tag = av_dict_get(tags, "", tag, AV_DICT_IGNORE_SUFFIX))) {
if ((ret = print_str_validate(tag->key, tag->value)) < 0)
break;
}
writer_print_section_footer(w);
return ret;
}
static void print_pkt_side_data(WriterContext *w,
AVCodecParameters *par,
const AVPacketSideData *side_data,
int nb_side_data,
SectionID id_data_list,
SectionID id_data)
{
int i;
writer_print_section_header(w, id_data_list);
for (i = 0; i < nb_side_data; i++) {
const AVPacketSideData *sd = &side_data[i];
const char *name = av_packet_side_data_name(sd->type);
writer_print_section_header(w, id_data);
print_str("side_data_type", name ? name : "unknown");
if (sd->type == AV_PKT_DATA_DISPLAYMATRIX && sd->size >= 9*4) {
writer_print_integers(w, "displaymatrix", sd->data, 9, " %11d", 3, 4, 1);
print_int("rotation", av_display_rotation_get((int32_t *)sd->data));
} else if (sd->type == AV_PKT_DATA_STEREO3D) {
const AVStereo3D *stereo = (AVStereo3D *)sd->data;
print_str("type", av_stereo3d_type_name(stereo->type));
print_int("inverted", !!(stereo->flags & AV_STEREO3D_FLAG_INVERT));
} else if (sd->type == AV_PKT_DATA_SPHERICAL) {
const AVSphericalMapping *spherical = (AVSphericalMapping *)sd->data;
print_str("projection", av_spherical_projection_name(spherical->projection));
if (spherical->projection == AV_SPHERICAL_CUBEMAP) {
print_int("padding", spherical->padding);
} else if (spherical->projection == AV_SPHERICAL_EQUIRECTANGULAR_TILE) {
size_t l, t, r, b;
av_spherical_tile_bounds(spherical, par->width, par->height,
&l, &t, &r, &b);
print_int("bound_left", l);
print_int("bound_top", t);
print_int("bound_right", r);
print_int("bound_bottom", b);
}
print_int("yaw", (double) spherical->yaw / (1 << 16));
print_int("pitch", (double) spherical->pitch / (1 << 16));
print_int("roll", (double) spherical->roll / (1 << 16));
} else if (sd->type == AV_PKT_DATA_SKIP_SAMPLES && sd->size == 10) {
print_int("skip_samples", AV_RL32(sd->data));
print_int("discard_padding", AV_RL32(sd->data + 4));
print_int("skip_reason", AV_RL8(sd->data + 8));
print_int("discard_reason", AV_RL8(sd->data + 9));
} else if (sd->type == AV_PKT_DATA_MASTERING_DISPLAY_METADATA) {
AVMasteringDisplayMetadata *metadata = (AVMasteringDisplayMetadata *)sd->data;
if (metadata->has_primaries) {
print_q("red_x", metadata->display_primaries[0][0], '/');
print_q("red_y", metadata->display_primaries[0][1], '/');
print_q("green_x", metadata->display_primaries[1][0], '/');
print_q("green_y", metadata->display_primaries[1][1], '/');
print_q("blue_x", metadata->display_primaries[2][0], '/');
print_q("blue_y", metadata->display_primaries[2][1], '/');
print_q("white_point_x", metadata->white_point[0], '/');
print_q("white_point_y", metadata->white_point[1], '/');
}
if (metadata->has_luminance) {
print_q("min_luminance", metadata->min_luminance, '/');
print_q("max_luminance", metadata->max_luminance, '/');
}
} else if (sd->type == AV_PKT_DATA_CONTENT_LIGHT_LEVEL) {
AVContentLightMetadata *metadata = (AVContentLightMetadata *)sd->data;
print_int("max_content", metadata->MaxCLL);
print_int("max_average", metadata->MaxFALL);
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
static void print_primaries(WriterContext *w, enum AVColorPrimaries color_primaries)
{
const char *val = av_color_primaries_name(color_primaries);
if (!val || color_primaries == AVCOL_PRI_UNSPECIFIED) {
print_str_opt("color_primaries", "unknown");
} else {
print_str("color_primaries", val);
}
}
static void clear_log(int need_lock)
{
int i;
if (need_lock)
pthread_mutex_lock(&log_mutex);
for (i=0; i<log_buffer_size; i++) {
av_freep(&log_buffer[i].context_name);
av_freep(&log_buffer[i].parent_name);
av_freep(&log_buffer[i].log_message);
}
log_buffer_size = 0;
if(need_lock)
pthread_mutex_unlock(&log_mutex);
}
static int show_log(WriterContext *w, int section_ids, int section_id, int log_level)
{
int i;
pthread_mutex_lock(&log_mutex);
if (!log_buffer_size) {
pthread_mutex_unlock(&log_mutex);
return 0;
}
writer_print_section_header(w, section_ids);
for (i=0; i<log_buffer_size; i++) {
if (log_buffer[i].log_level <= log_level) {
writer_print_section_header(w, section_id);
print_str("context", log_buffer[i].context_name);
print_int("level", log_buffer[i].log_level);
print_int("category", log_buffer[i].category);
if (log_buffer[i].parent_name) {
print_str("parent_context", log_buffer[i].parent_name);
print_int("parent_category", log_buffer[i].parent_category);
} else {
print_str_opt("parent_context", "N/A");
print_str_opt("parent_category", "N/A");
}
print_str("message", log_buffer[i].log_message);
writer_print_section_footer(w);
}
}
clear_log(0);
pthread_mutex_unlock(&log_mutex);
writer_print_section_footer(w);
return 0;
}
static void show_packet(WriterContext *w, InputFile *ifile, AVPacket *pkt, int packet_idx)
{
char val_str[128];
AVStream *st = ifile->streams[pkt->stream_index].st;
AVBPrint pbuf;
const char *s;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, SECTION_ID_PACKET);
s = av_get_media_type_string(st->codecpar->codec_type);
if (s) print_str ("codec_type", s);
else print_str_opt("codec_type", "unknown");
print_int("stream_index", pkt->stream_index);
print_ts ("pts", pkt->pts);
print_time("pts_time", pkt->pts, &st->time_base);
print_ts ("dts", pkt->dts);
print_time("dts_time", pkt->dts, &st->time_base);
print_duration_ts("duration", pkt->duration);
print_duration_time("duration_time", pkt->duration, &st->time_base);
print_duration_ts("convergence_duration", pkt->convergence_duration);
print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
print_val("size", pkt->size, unit_byte_str);
if (pkt->pos != -1) print_fmt ("pos", "%"PRId64, pkt->pos);
else print_str_opt("pos", "N/A");
print_fmt("flags", "%c%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_',
pkt->flags & AV_PKT_FLAG_DISCARD ? 'D' : '_');
if (pkt->side_data_elems) {
int size;
const uint8_t *side_metadata;
side_metadata = av_packet_get_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, &size);
if (side_metadata && size && do_show_packet_tags) {
AVDictionary *dict = NULL;
if (av_packet_unpack_dictionary(side_metadata, size, &dict) >= 0)
show_tags(w, dict, SECTION_ID_PACKET_TAGS);
av_dict_free(&dict);
}
print_pkt_side_data(w, st->codecpar, pkt->side_data, pkt->side_data_elems,
SECTION_ID_PACKET_SIDE_DATA_LIST,
SECTION_ID_PACKET_SIDE_DATA);
}
if (do_show_data)
writer_print_data(w, "data", pkt->data, pkt->size);
writer_print_data_hash(w, "data_hash", pkt->data, pkt->size);
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
fflush(stdout);
}
static void show_subtitle(WriterContext *w, AVSubtitle *sub, AVStream *stream,
AVFormatContext *fmt_ctx)
{
AVBPrint pbuf;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, SECTION_ID_SUBTITLE);
print_str ("media_type", "subtitle");
print_ts ("pts", sub->pts);
print_time("pts_time", sub->pts, &AV_TIME_BASE_Q);
print_int ("format", sub->format);
print_int ("start_display_time", sub->start_display_time);
print_int ("end_display_time", sub->end_display_time);
print_int ("num_rects", sub->num_rects);
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
fflush(stdout);
}
static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
AVFormatContext *fmt_ctx)
{
AVBPrint pbuf;
char val_str[128];
const char *s;
int i;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, SECTION_ID_FRAME);
s = av_get_media_type_string(stream->codecpar->codec_type);
if (s) print_str ("media_type", s);
else print_str_opt("media_type", "unknown");
print_int("stream_index", stream->index);
print_int("key_frame", frame->key_frame);
print_ts ("pkt_pts", frame->pts);
print_time("pkt_pts_time", frame->pts, &stream->time_base);
print_ts ("pkt_dts", frame->pkt_dts);
print_time("pkt_dts_time", frame->pkt_dts, &stream->time_base);
print_ts ("best_effort_timestamp", frame->best_effort_timestamp);
print_time("best_effort_timestamp_time", frame->best_effort_timestamp, &stream->time_base);
print_duration_ts ("pkt_duration", frame->pkt_duration);
print_duration_time("pkt_duration_time", frame->pkt_duration, &stream->time_base);
if (frame->pkt_pos != -1) print_fmt ("pkt_pos", "%"PRId64, frame->pkt_pos);
else print_str_opt("pkt_pos", "N/A");
if (frame->pkt_size != -1) print_val ("pkt_size", frame->pkt_size, unit_byte_str);
else print_str_opt("pkt_size", "N/A");
switch (stream->codecpar->codec_type) {
AVRational sar;
case AVMEDIA_TYPE_VIDEO:
print_int("width", frame->width);
print_int("height", frame->height);
s = av_get_pix_fmt_name(frame->format);
if (s) print_str ("pix_fmt", s);
else print_str_opt("pix_fmt", "unknown");
sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
if (sar.num) {
print_q("sample_aspect_ratio", sar, ':');
} else {
print_str_opt("sample_aspect_ratio", "N/A");
}
print_fmt("pict_type", "%c", av_get_picture_type_char(frame->pict_type));
print_int("coded_picture_number", frame->coded_picture_number);
print_int("display_picture_number", frame->display_picture_number);
print_int("interlaced_frame", frame->interlaced_frame);
print_int("top_field_first", frame->top_field_first);
print_int("repeat_pict", frame->repeat_pict);
if (frame->color_range != AVCOL_RANGE_UNSPECIFIED)
print_str("color_range", av_color_range_name(frame->color_range));
else
print_str_opt("color_range", av_color_range_name(frame->color_range));
if (frame->colorspace != AVCOL_SPC_UNSPECIFIED)
print_str("color_space", av_color_space_name(frame->colorspace));
else
print_str_opt("color_space", av_color_space_name(frame->colorspace));
print_primaries(w, frame->color_primaries);
if (frame->color_trc != AVCOL_TRC_UNSPECIFIED)
print_str("color_transfer", av_color_transfer_name(frame->color_trc));
else
print_str_opt("color_transfer", av_color_transfer_name(frame->color_trc));
if (frame->chroma_location != AVCHROMA_LOC_UNSPECIFIED)
print_str("chroma_location", av_chroma_location_name(frame->chroma_location));
else
print_str_opt("chroma_location", av_chroma_location_name(frame->chroma_location));
break;
case AVMEDIA_TYPE_AUDIO:
s = av_get_sample_fmt_name(frame->format);
if (s) print_str ("sample_fmt", s);
else print_str_opt("sample_fmt", "unknown");
print_int("nb_samples", frame->nb_samples);
print_int("channels", frame->channels);
if (frame->channel_layout) {
av_bprint_clear(&pbuf);
av_bprint_channel_layout(&pbuf, frame->channels,
frame->channel_layout);
print_str ("channel_layout", pbuf.str);
} else
print_str_opt("channel_layout", "unknown");
break;
}
if (do_show_frame_tags)
show_tags(w, frame->metadata, SECTION_ID_FRAME_TAGS);
if (do_show_log)
show_log(w, SECTION_ID_FRAME_LOGS, SECTION_ID_FRAME_LOG, do_show_log);
if (frame->nb_side_data) {
writer_print_section_header(w, SECTION_ID_FRAME_SIDE_DATA_LIST);
for (i = 0; i < frame->nb_side_data; i++) {
AVFrameSideData *sd = frame->side_data[i];
const char *name;
writer_print_section_header(w, SECTION_ID_FRAME_SIDE_DATA);
name = av_frame_side_data_name(sd->type);
print_str("side_data_type", name ? name : "unknown");
if (sd->type == AV_FRAME_DATA_DISPLAYMATRIX && sd->size >= 9*4) {
writer_print_integers(w, "displaymatrix", sd->data, 9, " %11d", 3, 4, 1);
print_int("rotation", av_display_rotation_get((int32_t *)sd->data));
} else if (sd->type == AV_FRAME_DATA_GOP_TIMECODE && sd->size >= 8) {
char tcbuf[AV_TIMECODE_STR_SIZE];
av_timecode_make_mpeg_tc_string(tcbuf, *(int64_t *)(sd->data));
print_str("timecode", tcbuf);
} else if (sd->type == AV_FRAME_DATA_MASTERING_DISPLAY_METADATA) {
AVMasteringDisplayMetadata *metadata = (AVMasteringDisplayMetadata *)sd->data;
if (metadata->has_primaries) {
print_q("red_x", metadata->display_primaries[0][0], '/');
print_q("red_y", metadata->display_primaries[0][1], '/');
print_q("green_x", metadata->display_primaries[1][0], '/');
print_q("green_y", metadata->display_primaries[1][1], '/');
print_q("blue_x", metadata->display_primaries[2][0], '/');
print_q("blue_y", metadata->display_primaries[2][1], '/');
print_q("white_point_x", metadata->white_point[0], '/');
print_q("white_point_y", metadata->white_point[1], '/');
}
if (metadata->has_luminance) {
print_q("min_luminance", metadata->min_luminance, '/');
print_q("max_luminance", metadata->max_luminance, '/');
}
} else if (sd->type == AV_FRAME_DATA_CONTENT_LIGHT_LEVEL) {
AVContentLightMetadata *metadata = (AVContentLightMetadata *)sd->data;
print_int("max_content", metadata->MaxCLL);
print_int("max_average", metadata->MaxFALL);
} else if (sd->type == AV_FRAME_DATA_ICC_PROFILE) {
AVDictionaryEntry *tag = av_dict_get(sd->metadata, "name", NULL, AV_DICT_MATCH_CASE);
if (tag)
print_str(tag->key, tag->value);
print_int("size", sd->size);
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
fflush(stdout);
}
static av_always_inline int process_frame(WriterContext *w,
InputFile *ifile,
AVFrame *frame, AVPacket *pkt,
int *packet_new)
{
AVFormatContext *fmt_ctx = ifile->fmt_ctx;
AVCodecContext *dec_ctx = ifile->streams[pkt->stream_index].dec_ctx;
AVCodecParameters *par = ifile->streams[pkt->stream_index].st->codecpar;
AVSubtitle sub;
int ret = 0, got_frame = 0;
clear_log(1);
if (dec_ctx && dec_ctx->codec) {
switch (par->codec_type) {
case AVMEDIA_TYPE_VIDEO:
case AVMEDIA_TYPE_AUDIO:
if (*packet_new) {
ret = avcodec_send_packet(dec_ctx, pkt);
if (ret == AVERROR(EAGAIN)) {
ret = 0;
} else if (ret >= 0 || ret == AVERROR_EOF) {
ret = 0;
*packet_new = 0;
}
}
if (ret >= 0) {
ret = avcodec_receive_frame(dec_ctx, frame);
if (ret >= 0) {
got_frame = 1;
} else if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
ret = 0;
}
}
break;
case AVMEDIA_TYPE_SUBTITLE:
ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_frame, pkt);
*packet_new = 0;
break;
default:
*packet_new = 0;
}
} else {
*packet_new = 0;
}
if (ret < 0)
return ret;
if (got_frame) {
int is_sub = (par->codec_type == AVMEDIA_TYPE_SUBTITLE);
nb_streams_frames[pkt->stream_index]++;
if (do_show_frames)
if (is_sub)
show_subtitle(w, &sub, ifile->streams[pkt->stream_index].st, fmt_ctx);
else
show_frame(w, frame, ifile->streams[pkt->stream_index].st, fmt_ctx);
if (is_sub)
avsubtitle_free(&sub);
}
return got_frame || *packet_new;
}
static void log_read_interval(const ReadInterval *interval, void *log_ctx, int log_level)
{
av_log(log_ctx, log_level, "id:%d", interval->id);
if (interval->has_start) {
av_log(log_ctx, log_level, " start:%s%s", interval->start_is_offset ? "+" : "",
av_ts2timestr(interval->start, &AV_TIME_BASE_Q));
} else {
av_log(log_ctx, log_level, " start:N/A");
}
if (interval->has_end) {
av_log(log_ctx, log_level, " end:%s", interval->end_is_offset ? "+" : "");
if (interval->duration_frames)
av_log(log_ctx, log_level, "#%"PRId64, interval->end);
else
av_log(log_ctx, log_level, "%s", av_ts2timestr(interval->end, &AV_TIME_BASE_Q));
} else {
av_log(log_ctx, log_level, " end:N/A");
}
av_log(log_ctx, log_level, "\n");
}
static int read_interval_packets(WriterContext *w, InputFile *ifile,
const ReadInterval *interval, int64_t *cur_ts)
{
AVFormatContext *fmt_ctx = ifile->fmt_ctx;
AVPacket pkt;
AVFrame *frame = NULL;
int ret = 0, i = 0, frame_count = 0;
int64_t start = -INT64_MAX, end = interval->end;
int has_start = 0, has_end = interval->has_end && !interval->end_is_offset;
av_init_packet(&pkt);
av_log(NULL, AV_LOG_VERBOSE, "Processing read interval ");
log_read_interval(interval, NULL, AV_LOG_VERBOSE);
if (interval->has_start) {
int64_t target;
if (interval->start_is_offset) {
if (*cur_ts == AV_NOPTS_VALUE) {
av_log(NULL, AV_LOG_ERROR,
"Could not seek to relative position since current "
"timestamp is not defined\n");
ret = AVERROR(EINVAL);
goto end;
}
target = *cur_ts + interval->start;
} else {
target = interval->start;
}
av_log(NULL, AV_LOG_VERBOSE, "Seeking to read interval start point %s\n",
av_ts2timestr(target, &AV_TIME_BASE_Q));
if ((ret = avformat_seek_file(fmt_ctx, -1, -INT64_MAX, target, INT64_MAX, 0)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Could not seek to position %"PRId64": %s\n",
interval->start, av_err2str(ret));
goto end;
}
}
frame = av_frame_alloc();
if (!frame) {
ret = AVERROR(ENOMEM);
goto end;
}
while (!av_read_frame(fmt_ctx, &pkt)) {
if (ifile->nb_streams > nb_streams) {
REALLOCZ_ARRAY_STREAM(nb_streams_frames, nb_streams, fmt_ctx->nb_streams);
REALLOCZ_ARRAY_STREAM(nb_streams_packets, nb_streams, fmt_ctx->nb_streams);
REALLOCZ_ARRAY_STREAM(selected_streams, nb_streams, fmt_ctx->nb_streams);
nb_streams = ifile->nb_streams;
}
if (selected_streams[pkt.stream_index]) {
AVRational tb = ifile->streams[pkt.stream_index].st->time_base;
if (pkt.pts != AV_NOPTS_VALUE)
*cur_ts = av_rescale_q(pkt.pts, tb, AV_TIME_BASE_Q);
if (!has_start && *cur_ts != AV_NOPTS_VALUE) {
start = *cur_ts;
has_start = 1;
}
if (has_start && !has_end && interval->end_is_offset) {
end = start + interval->end;
has_end = 1;
}
if (interval->end_is_offset && interval->duration_frames) {
if (frame_count >= interval->end)
break;
} else if (has_end && *cur_ts != AV_NOPTS_VALUE && *cur_ts >= end) {
break;
}
frame_count++;
if (do_read_packets) {
if (do_show_packets)
show_packet(w, ifile, &pkt, i++);
nb_streams_packets[pkt.stream_index]++;
}
if (do_read_frames) {
int packet_new = 1;
while (process_frame(w, ifile, frame, &pkt, &packet_new) > 0);
}
}
av_packet_unref(&pkt);
}
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
//Flush remaining frames that are cached in the decoder
for (i = 0; i < fmt_ctx->nb_streams; i++) {
pkt.stream_index = i;
if (do_read_frames)
while (process_frame(w, ifile, frame, &pkt, &(int){1}) > 0);
}
end:
av_frame_free(&frame);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Could not read packets in interval ");
log_read_interval(interval, NULL, AV_LOG_ERROR);
}
return ret;
}
static int read_packets(WriterContext *w, InputFile *ifile)
{
AVFormatContext *fmt_ctx = ifile->fmt_ctx;
int i, ret = 0;
int64_t cur_ts = fmt_ctx->start_time;
if (read_intervals_nb == 0) {
ReadInterval interval = (ReadInterval) { .has_start = 0, .has_end = 0 };
ret = read_interval_packets(w, ifile, &interval, &cur_ts);
} else {
for (i = 0; i < read_intervals_nb; i++) {
ret = read_interval_packets(w, ifile, &read_intervals[i], &cur_ts);
if (ret < 0)
break;
}
}
return ret;
}
static int show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx, InputStream *ist, int in_program)
{
AVStream *stream = ist->st;
AVCodecParameters *par;
AVCodecContext *dec_ctx;
char val_str[128];
const char *s;
AVRational sar, dar;
AVBPrint pbuf;
const AVCodecDescriptor *cd;
int ret = 0;
const char *profile = NULL;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM : SECTION_ID_STREAM);
print_int("index", stream->index);
par = stream->codecpar;
dec_ctx = ist->dec_ctx;
if (cd = avcodec_descriptor_get(par->codec_id)) {
print_str("codec_name", cd->name);
if (!do_bitexact) {
print_str("codec_long_name",
cd->long_name ? cd->long_name : "unknown");
}
} else {
print_str_opt("codec_name", "unknown");
if (!do_bitexact) {
print_str_opt("codec_long_name", "unknown");
}
}
if (!do_bitexact && (profile = avcodec_profile_name(par->codec_id, par->profile)))
print_str("profile", profile);
else {
if (par->profile != FF_PROFILE_UNKNOWN) {
char profile_num[12];
snprintf(profile_num, sizeof(profile_num), "%d", par->profile);
print_str("profile", profile_num);
} else
print_str_opt("profile", "unknown");
}
s = av_get_media_type_string(par->codec_type);
if (s) print_str ("codec_type", s);
else print_str_opt("codec_type", "unknown");
#if FF_API_LAVF_AVCTX
if (dec_ctx)
print_q("codec_time_base", dec_ctx->time_base, '/');
#endif
/* print AVI/FourCC tag */
print_str("codec_tag_string", av_fourcc2str(par->codec_tag));
print_fmt("codec_tag", "0x%04"PRIx32, par->codec_tag);
switch (par->codec_type) {
case AVMEDIA_TYPE_VIDEO:
print_int("width", par->width);
print_int("height", par->height);
if (dec_ctx) {
print_int("coded_width", dec_ctx->coded_width);
print_int("coded_height", dec_ctx->coded_height);
}
print_int("has_b_frames", par->video_delay);
sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
if (sar.den) {
print_q("sample_aspect_ratio", sar, ':');
av_reduce(&dar.num, &dar.den,
par->width * sar.num,
par->height * sar.den,
1024*1024);
print_q("display_aspect_ratio", dar, ':');
} else {
print_str_opt("sample_aspect_ratio", "N/A");
print_str_opt("display_aspect_ratio", "N/A");
}
s = av_get_pix_fmt_name(par->format);
if (s) print_str ("pix_fmt", s);
else print_str_opt("pix_fmt", "unknown");
print_int("level", par->level);
if (par->color_range != AVCOL_RANGE_UNSPECIFIED)
print_str ("color_range", av_color_range_name(par->color_range));
else
print_str_opt("color_range", "N/A");
if (par->color_space != AVCOL_SPC_UNSPECIFIED)
print_str("color_space", av_color_space_name(par->color_space));
else
print_str_opt("color_space", av_color_space_name(par->color_space));
if (par->color_trc != AVCOL_TRC_UNSPECIFIED)
print_str("color_transfer", av_color_transfer_name(par->color_trc));
else
print_str_opt("color_transfer", av_color_transfer_name(par->color_trc));
print_primaries(w, par->color_primaries);
if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED)
print_str("chroma_location", av_chroma_location_name(par->chroma_location));
else
print_str_opt("chroma_location", av_chroma_location_name(par->chroma_location));
if (par->field_order == AV_FIELD_PROGRESSIVE)
print_str("field_order", "progressive");
else if (par->field_order == AV_FIELD_TT)
print_str("field_order", "tt");
else if (par->field_order == AV_FIELD_BB)
print_str("field_order", "bb");
else if (par->field_order == AV_FIELD_TB)
print_str("field_order", "tb");
else if (par->field_order == AV_FIELD_BT)
print_str("field_order", "bt");
else
print_str_opt("field_order", "unknown");
#if FF_API_PRIVATE_OPT
if (dec_ctx && dec_ctx->timecode_frame_start >= 0) {
char tcbuf[AV_TIMECODE_STR_SIZE];
av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
print_str("timecode", tcbuf);
} else {
print_str_opt("timecode", "N/A");
}
#endif
if (dec_ctx)
print_int("refs", dec_ctx->refs);
break;
case AVMEDIA_TYPE_AUDIO:
s = av_get_sample_fmt_name(par->format);
if (s) print_str ("sample_fmt", s);
else print_str_opt("sample_fmt", "unknown");
print_val("sample_rate", par->sample_rate, unit_hertz_str);
print_int("channels", par->channels);
if (par->channel_layout) {
av_bprint_clear(&pbuf);
av_bprint_channel_layout(&pbuf, par->channels, par->channel_layout);
print_str ("channel_layout", pbuf.str);
} else {
print_str_opt("channel_layout", "unknown");
}
print_int("bits_per_sample", av_get_bits_per_sample(par->codec_id));
break;
case AVMEDIA_TYPE_SUBTITLE:
if (par->width)
print_int("width", par->width);
else
print_str_opt("width", "N/A");
if (par->height)
print_int("height", par->height);
else
print_str_opt("height", "N/A");
break;
}
if (dec_ctx && dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
const AVOption *opt = NULL;
while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
uint8_t *str;
if (opt->flags) continue;
if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
print_str(opt->name, str);
av_free(str);
}
}
}
if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt ("id", "0x%x", stream->id);
else print_str_opt("id", "N/A");
print_q("r_frame_rate", stream->r_frame_rate, '/');
print_q("avg_frame_rate", stream->avg_frame_rate, '/');
print_q("time_base", stream->time_base, '/');
print_ts ("start_pts", stream->start_time);
print_time("start_time", stream->start_time, &stream->time_base);
print_ts ("duration_ts", stream->duration);
print_time("duration", stream->duration, &stream->time_base);
if (par->bit_rate > 0) print_val ("bit_rate", par->bit_rate, unit_bit_per_second_str);
else print_str_opt("bit_rate", "N/A");
#if FF_API_LAVF_AVCTX
if (stream->codec->rc_max_rate > 0) print_val ("max_bit_rate", stream->codec->rc_max_rate, unit_bit_per_second_str);
else print_str_opt("max_bit_rate", "N/A");
#endif
if (dec_ctx && dec_ctx->bits_per_raw_sample > 0) print_fmt("bits_per_raw_sample", "%d", dec_ctx->bits_per_raw_sample);
else print_str_opt("bits_per_raw_sample", "N/A");
if (stream->nb_frames) print_fmt ("nb_frames", "%"PRId64, stream->nb_frames);
else print_str_opt("nb_frames", "N/A");
if (nb_streams_frames[stream_idx]) print_fmt ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
else print_str_opt("nb_read_frames", "N/A");
if (nb_streams_packets[stream_idx]) print_fmt ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
else print_str_opt("nb_read_packets", "N/A");
if (do_show_data)
writer_print_data(w, "extradata", par->extradata,
par->extradata_size);
writer_print_data_hash(w, "extradata_hash", par->extradata,
par->extradata_size);
/* Print disposition information */
#define PRINT_DISPOSITION(flagname, name) do { \
print_int(name, !!(stream->disposition & AV_DISPOSITION_##flagname)); \
} while (0)
if (do_show_stream_disposition) {
writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM_DISPOSITION : SECTION_ID_STREAM_DISPOSITION);
PRINT_DISPOSITION(DEFAULT, "default");
PRINT_DISPOSITION(DUB, "dub");
PRINT_DISPOSITION(ORIGINAL, "original");
PRINT_DISPOSITION(COMMENT, "comment");
PRINT_DISPOSITION(LYRICS, "lyrics");
PRINT_DISPOSITION(KARAOKE, "karaoke");
PRINT_DISPOSITION(FORCED, "forced");
PRINT_DISPOSITION(HEARING_IMPAIRED, "hearing_impaired");
PRINT_DISPOSITION(VISUAL_IMPAIRED, "visual_impaired");
PRINT_DISPOSITION(CLEAN_EFFECTS, "clean_effects");
PRINT_DISPOSITION(ATTACHED_PIC, "attached_pic");
PRINT_DISPOSITION(TIMED_THUMBNAILS, "timed_thumbnails");
writer_print_section_footer(w);
}
if (do_show_stream_tags)
ret = show_tags(w, stream->metadata, in_program ? SECTION_ID_PROGRAM_STREAM_TAGS : SECTION_ID_STREAM_TAGS);
if (stream->nb_side_data) {
print_pkt_side_data(w, stream->codecpar, stream->side_data, stream->nb_side_data,
SECTION_ID_STREAM_SIDE_DATA_LIST,
SECTION_ID_STREAM_SIDE_DATA);
}
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
fflush(stdout);
return ret;
}
static int show_streams(WriterContext *w, InputFile *ifile)
{
AVFormatContext *fmt_ctx = ifile->fmt_ctx;
int i, ret = 0;
writer_print_section_header(w, SECTION_ID_STREAMS);
for (i = 0; i < ifile->nb_streams; i++)
if (selected_streams[i]) {
ret = show_stream(w, fmt_ctx, i, &ifile->streams[i], 0);
if (ret < 0)
break;
}
writer_print_section_footer(w);
return ret;
}
static int show_program(WriterContext *w, InputFile *ifile, AVProgram *program)
{
AVFormatContext *fmt_ctx = ifile->fmt_ctx;
int i, ret = 0;
writer_print_section_header(w, SECTION_ID_PROGRAM);
print_int("program_id", program->id);
print_int("program_num", program->program_num);
print_int("nb_streams", program->nb_stream_indexes);
print_int("pmt_pid", program->pmt_pid);
print_int("pcr_pid", program->pcr_pid);
print_ts("start_pts", program->start_time);
print_time("start_time", program->start_time, &AV_TIME_BASE_Q);
print_ts("end_pts", program->end_time);
print_time("end_time", program->end_time, &AV_TIME_BASE_Q);
if (do_show_program_tags)
ret = show_tags(w, program->metadata, SECTION_ID_PROGRAM_TAGS);
if (ret < 0)
goto end;
writer_print_section_header(w, SECTION_ID_PROGRAM_STREAMS);
for (i = 0; i < program->nb_stream_indexes; i++) {
if (selected_streams[program->stream_index[i]]) {
ret = show_stream(w, fmt_ctx, program->stream_index[i], &ifile->streams[program->stream_index[i]], 1);
if (ret < 0)
break;
}
}
writer_print_section_footer(w);
end:
writer_print_section_footer(w);
return ret;
}
static int show_programs(WriterContext *w, InputFile *ifile)
{
AVFormatContext *fmt_ctx = ifile->fmt_ctx;
int i, ret = 0;
writer_print_section_header(w, SECTION_ID_PROGRAMS);
for (i = 0; i < fmt_ctx->nb_programs; i++) {
AVProgram *program = fmt_ctx->programs[i];
if (!program)
continue;
ret = show_program(w, ifile, program);
if (ret < 0)
break;
}
writer_print_section_footer(w);
return ret;
}
static int show_chapters(WriterContext *w, InputFile *ifile)
{
AVFormatContext *fmt_ctx = ifile->fmt_ctx;
int i, ret = 0;
writer_print_section_header(w, SECTION_ID_CHAPTERS);
for (i = 0; i < fmt_ctx->nb_chapters; i++) {
AVChapter *chapter = fmt_ctx->chapters[i];
writer_print_section_header(w, SECTION_ID_CHAPTER);
print_int("id", chapter->id);
print_q ("time_base", chapter->time_base, '/');
print_int("start", chapter->start);
print_time("start_time", chapter->start, &chapter->time_base);
print_int("end", chapter->end);
print_time("end_time", chapter->end, &chapter->time_base);
if (do_show_chapter_tags)
ret = show_tags(w, chapter->metadata, SECTION_ID_CHAPTER_TAGS);
writer_print_section_footer(w);
}
writer_print_section_footer(w);
return ret;
}
static int show_format(WriterContext *w, InputFile *ifile)
{
AVFormatContext *fmt_ctx = ifile->fmt_ctx;
char val_str[128];
int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
int ret = 0;
writer_print_section_header(w, SECTION_ID_FORMAT);
print_str_validate("filename", fmt_ctx->filename);
print_int("nb_streams", fmt_ctx->nb_streams);
print_int("nb_programs", fmt_ctx->nb_programs);
print_str("format_name", fmt_ctx->iformat->name);
if (!do_bitexact) {
if (fmt_ctx->iformat->long_name) print_str ("format_long_name", fmt_ctx->iformat->long_name);
else print_str_opt("format_long_name", "unknown");
}
print_time("start_time", fmt_ctx->start_time, &AV_TIME_BASE_Q);
print_time("duration", fmt_ctx->duration, &AV_TIME_BASE_Q);
if (size >= 0) print_val ("size", size, unit_byte_str);
else print_str_opt("size", "N/A");
if (fmt_ctx->bit_rate > 0) print_val ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
else print_str_opt("bit_rate", "N/A");
print_int("probe_score", av_format_get_probe_score(fmt_ctx));
if (do_show_format_tags)
ret = show_tags(w, fmt_ctx->metadata, SECTION_ID_FORMAT_TAGS);
writer_print_section_footer(w);
fflush(stdout);
return ret;
}
static void show_error(WriterContext *w, int err)
{
char errbuf[128];
const char *errbuf_ptr = errbuf;
if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
errbuf_ptr = strerror(AVUNERROR(err));
writer_print_section_header(w, SECTION_ID_ERROR);
print_int("code", err);
print_str("string", errbuf_ptr);
writer_print_section_footer(w);
}
static int open_input_file(InputFile *ifile, const char *filename)
{
int err, i;
AVFormatContext *fmt_ctx = NULL;
AVDictionaryEntry *t;
int scan_all_pmts_set = 0;
fmt_ctx = avformat_alloc_context();
if (!fmt_ctx) {
print_error(filename, AVERROR(ENOMEM));
exit_program(1);
}
fmt_ctx->flags |= AVFMT_FLAG_KEEP_SIDE_DATA;
if (!av_dict_get(format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
av_dict_set(&format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
scan_all_pmts_set = 1;
}
if ((err = avformat_open_input(&fmt_ctx, filename,
iformat, &format_opts)) < 0) {
print_error(filename, err);
return err;
}
ifile->fmt_ctx = fmt_ctx;
if (scan_all_pmts_set)
av_dict_set(&format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
return AVERROR_OPTION_NOT_FOUND;
}
if (find_stream_info) {
AVDictionary **opts = setup_find_stream_info_opts(fmt_ctx, codec_opts);
int orig_nb_streams = fmt_ctx->nb_streams;
err = avformat_find_stream_info(fmt_ctx, opts);
for (i = 0; i < orig_nb_streams; i++)
av_dict_free(&opts[i]);
av_freep(&opts);
if (err < 0) {
print_error(filename, err);
return err;
}
}
av_dump_format(fmt_ctx, 0, filename, 0);
ifile->streams = av_mallocz_array(fmt_ctx->nb_streams,
sizeof(*ifile->streams));
if (!ifile->streams)
exit(1);
ifile->nb_streams = fmt_ctx->nb_streams;
/* bind a decoder to each input stream */
for (i = 0; i < fmt_ctx->nb_streams; i++) {
InputStream *ist = &ifile->streams[i];
AVStream *stream = fmt_ctx->streams[i];
AVCodec *codec;
ist->st = stream;
if (stream->codecpar->codec_id == AV_CODEC_ID_PROBE) {
av_log(NULL, AV_LOG_WARNING,
"Failed to probe codec for input stream %d\n",
stream->index);
continue;
}
codec = avcodec_find_decoder(stream->codecpar->codec_id);
if (!codec) {
av_log(NULL, AV_LOG_WARNING,
"Unsupported codec with id %d for input stream %d\n",
stream->codecpar->codec_id, stream->index);
continue;
}
{
AVDictionary *opts = filter_codec_opts(codec_opts, stream->codecpar->codec_id,
fmt_ctx, stream, codec);
ist->dec_ctx = avcodec_alloc_context3(codec);
if (!ist->dec_ctx)
exit(1);
err = avcodec_parameters_to_context(ist->dec_ctx, stream->codecpar);
if (err < 0)
exit(1);
if (do_show_log) {
// For loging it is needed to disable at least frame threads as otherwise
// the log information would need to be reordered and matches up to contexts and frames
// That is in fact possible but not trivial
av_dict_set(&codec_opts, "threads", "1", 0);
}
av_codec_set_pkt_timebase(ist->dec_ctx, stream->time_base);
ist->dec_ctx->framerate = stream->avg_frame_rate;
if (avcodec_open2(ist->dec_ctx, codec, &opts) < 0) {
av_log(NULL, AV_LOG_WARNING, "Could not open codec for input stream %d\n",
stream->index);
exit(1);
}
if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
av_log(NULL, AV_LOG_ERROR, "Option %s for input stream %d not found\n",
t->key, stream->index);
return AVERROR_OPTION_NOT_FOUND;
}
}
}
ifile->fmt_ctx = fmt_ctx;
return 0;
}
static void close_input_file(InputFile *ifile)
{
int i;
/* close decoder for each stream */
for (i = 0; i < ifile->nb_streams; i++)
if (ifile->streams[i].st->codecpar->codec_id != AV_CODEC_ID_NONE)
avcodec_free_context(&ifile->streams[i].dec_ctx);
av_freep(&ifile->streams);
ifile->nb_streams = 0;
avformat_close_input(&ifile->fmt_ctx);
}
static int probe_file(WriterContext *wctx, const char *filename)
{
InputFile ifile = { 0 };
int ret, i;
int section_id;
do_read_frames = do_show_frames || do_count_frames;
do_read_packets = do_show_packets || do_count_packets;
ret = open_input_file(&ifile, filename);
if (ret < 0)
goto end;
#define CHECK_END if (ret < 0) goto end
nb_streams = ifile.fmt_ctx->nb_streams;
REALLOCZ_ARRAY_STREAM(nb_streams_frames,0,ifile.fmt_ctx->nb_streams);
REALLOCZ_ARRAY_STREAM(nb_streams_packets,0,ifile.fmt_ctx->nb_streams);
REALLOCZ_ARRAY_STREAM(selected_streams,0,ifile.fmt_ctx->nb_streams);
for (i = 0; i < ifile.fmt_ctx->nb_streams; i++) {
if (stream_specifier) {
ret = avformat_match_stream_specifier(ifile.fmt_ctx,
ifile.fmt_ctx->streams[i],
stream_specifier);
CHECK_END;
else
selected_streams[i] = ret;
ret = 0;
} else {
selected_streams[i] = 1;
}
if (!selected_streams[i])
ifile.fmt_ctx->streams[i]->discard = AVDISCARD_ALL;
}
if (do_read_frames || do_read_packets) {
if (do_show_frames && do_show_packets &&
wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
section_id = SECTION_ID_PACKETS_AND_FRAMES;
else if (do_show_packets && !do_show_frames)
section_id = SECTION_ID_PACKETS;
else // (!do_show_packets && do_show_frames)
section_id = SECTION_ID_FRAMES;
if (do_show_frames || do_show_packets)
writer_print_section_header(wctx, section_id);
ret = read_packets(wctx, &ifile);
if (do_show_frames || do_show_packets)
writer_print_section_footer(wctx);
CHECK_END;
}
if (do_show_programs) {
ret = show_programs(wctx, &ifile);
CHECK_END;
}
if (do_show_streams) {
ret = show_streams(wctx, &ifile);
CHECK_END;
}
if (do_show_chapters) {
ret = show_chapters(wctx, &ifile);
CHECK_END;
}
if (do_show_format) {
ret = show_format(wctx, &ifile);
CHECK_END;
}
end:
if (ifile.fmt_ctx)
close_input_file(&ifile);
av_freep(&nb_streams_frames);
av_freep(&nb_streams_packets);
av_freep(&selected_streams);
return ret;
}
static void show_usage(void)
{
av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
av_log(NULL, AV_LOG_INFO, "\n");
}
static void ffprobe_show_program_version(WriterContext *w)
{
AVBPrint pbuf;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, SECTION_ID_PROGRAM_VERSION);
print_str("version", FFMPEG_VERSION);
print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
program_birth_year, CONFIG_THIS_YEAR);
print_str("compiler_ident", CC_IDENT);
print_str("configuration", FFMPEG_CONFIGURATION);
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
}
#define SHOW_LIB_VERSION(libname, LIBNAME) \
do { \
if (CONFIG_##LIBNAME) { \
unsigned int version = libname##_version(); \
writer_print_section_header(w, SECTION_ID_LIBRARY_VERSION); \
print_str("name", "lib" #libname); \
print_int("major", LIB##LIBNAME##_VERSION_MAJOR); \
print_int("minor", LIB##LIBNAME##_VERSION_MINOR); \
print_int("micro", LIB##LIBNAME##_VERSION_MICRO); \
print_int("version", version); \
print_str("ident", LIB##LIBNAME##_IDENT); \
writer_print_section_footer(w); \
} \
} while (0)
static void ffprobe_show_library_versions(WriterContext *w)
{
writer_print_section_header(w, SECTION_ID_LIBRARY_VERSIONS);
SHOW_LIB_VERSION(avutil, AVUTIL);
SHOW_LIB_VERSION(avcodec, AVCODEC);
SHOW_LIB_VERSION(avformat, AVFORMAT);
SHOW_LIB_VERSION(avdevice, AVDEVICE);
SHOW_LIB_VERSION(avfilter, AVFILTER);
SHOW_LIB_VERSION(swscale, SWSCALE);
SHOW_LIB_VERSION(swresample, SWRESAMPLE);
SHOW_LIB_VERSION(postproc, POSTPROC);
writer_print_section_footer(w);
}
#define PRINT_PIX_FMT_FLAG(flagname, name) \
do { \
print_int(name, !!(pixdesc->flags & AV_PIX_FMT_FLAG_##flagname)); \
} while (0)
static void ffprobe_show_pixel_formats(WriterContext *w)
{
const AVPixFmtDescriptor *pixdesc = NULL;
int i, n;
writer_print_section_header(w, SECTION_ID_PIXEL_FORMATS);
while (pixdesc = av_pix_fmt_desc_next(pixdesc)) {
writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT);
print_str("name", pixdesc->name);
print_int("nb_components", pixdesc->nb_components);
if ((pixdesc->nb_components >= 3) && !(pixdesc->flags & AV_PIX_FMT_FLAG_RGB)) {
print_int ("log2_chroma_w", pixdesc->log2_chroma_w);
print_int ("log2_chroma_h", pixdesc->log2_chroma_h);
} else {
print_str_opt("log2_chroma_w", "N/A");
print_str_opt("log2_chroma_h", "N/A");
}
n = av_get_bits_per_pixel(pixdesc);
if (n) print_int ("bits_per_pixel", n);
else print_str_opt("bits_per_pixel", "N/A");
if (do_show_pixel_format_flags) {
writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT_FLAGS);
PRINT_PIX_FMT_FLAG(BE, "big_endian");
PRINT_PIX_FMT_FLAG(PAL, "palette");
PRINT_PIX_FMT_FLAG(BITSTREAM, "bitstream");
PRINT_PIX_FMT_FLAG(HWACCEL, "hwaccel");
PRINT_PIX_FMT_FLAG(PLANAR, "planar");
PRINT_PIX_FMT_FLAG(RGB, "rgb");
PRINT_PIX_FMT_FLAG(PSEUDOPAL, "pseudopal");
PRINT_PIX_FMT_FLAG(ALPHA, "alpha");
writer_print_section_footer(w);
}
if (do_show_pixel_format_components && (pixdesc->nb_components > 0)) {
writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT_COMPONENTS);
for (i = 0; i < pixdesc->nb_components; i++) {
writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT_COMPONENT);
print_int("index", i + 1);
print_int("bit_depth", pixdesc->comp[i].depth);
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
static int opt_format(void *optctx, const char *opt, const char *arg)
{
iformat = av_find_input_format(arg);
if (!iformat) {
av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
return AVERROR(EINVAL);
}
return 0;
}
static inline void mark_section_show_entries(SectionID section_id,
int show_all_entries, AVDictionary *entries)
{
struct section *section = §ions[section_id];
section->show_all_entries = show_all_entries;
if (show_all_entries) {
SectionID *id;
for (id = section->children_ids; *id != -1; id++)
mark_section_show_entries(*id, show_all_entries, entries);
} else {
av_dict_copy(§ion->entries_to_show, entries, 0);
}
}
static int match_section(const char *section_name,
int show_all_entries, AVDictionary *entries)
{
int i, ret = 0;
for (i = 0; i < FF_ARRAY_ELEMS(sections); i++) {
const struct section *section = §ions[i];
if (!strcmp(section_name, section->name) ||
(section->unique_name && !strcmp(section_name, section->unique_name))) {
av_log(NULL, AV_LOG_DEBUG,
"'%s' matches section with unique name '%s'\n", section_name,
(char *)av_x_if_null(section->unique_name, section->name));
ret++;
mark_section_show_entries(section->id, show_all_entries, entries);
}
}
return ret;
}
static int opt_show_entries(void *optctx, const char *opt, const char *arg)
{
const char *p = arg;
int ret = 0;
while (*p) {
AVDictionary *entries = NULL;
char *section_name = av_get_token(&p, "=:");
int show_all_entries = 0;
if (!section_name) {
av_log(NULL, AV_LOG_ERROR,
"Missing section name for option '%s'\n", opt);
return AVERROR(EINVAL);
}
if (*p == '=') {
p++;
while (*p && *p != ':') {
char *entry = av_get_token(&p, ",:");
if (!entry)
break;
av_log(NULL, AV_LOG_VERBOSE,
"Adding '%s' to the entries to show in section '%s'\n",
entry, section_name);
av_dict_set(&entries, entry, "", AV_DICT_DONT_STRDUP_KEY);
if (*p == ',')
p++;
}
} else {
show_all_entries = 1;
}
ret = match_section(section_name, show_all_entries, entries);
if (ret == 0) {
av_log(NULL, AV_LOG_ERROR, "No match for section '%s'\n", section_name);
ret = AVERROR(EINVAL);
}
av_dict_free(&entries);
av_free(section_name);
if (ret <= 0)
break;
if (*p)
p++;
}
return ret;
}
static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
{
char *buf = av_asprintf("format=%s", arg);
int ret;
if (!buf)
return AVERROR(ENOMEM);
av_log(NULL, AV_LOG_WARNING,
"Option '%s' is deprecated, use '-show_entries format=%s' instead\n",
opt, arg);
ret = opt_show_entries(optctx, opt, buf);
av_free(buf);
return ret;
}
static void opt_input_file(void *optctx, const char *arg)
{
if (input_filename) {
av_log(NULL, AV_LOG_ERROR,
"Argument '%s' provided as input filename, but '%s' was already specified.\n",
arg, input_filename);
exit_program(1);
}
if (!strcmp(arg, "-"))
arg = "pipe:";
input_filename = arg;
}
static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
{
opt_input_file(optctx, arg);
return 0;
}
void show_help_default(const char *opt, const char *arg)
{
av_log_set_callback(log_callback_help);
show_usage();
show_help_options(options, "Main options:", 0, 0, 0);
printf("\n");
show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
show_help_children(avcodec_get_class(), AV_OPT_FLAG_DECODING_PARAM);
}
/**
* Parse interval specification, according to the format:
* INTERVAL ::= [START|+START_OFFSET][%[END|+END_OFFSET]]
* INTERVALS ::= INTERVAL[,INTERVALS]
*/
static int parse_read_interval(const char *interval_spec,
ReadInterval *interval)
{
int ret = 0;
char *next, *p, *spec = av_strdup(interval_spec);
if (!spec)
return AVERROR(ENOMEM);
if (!*spec) {
av_log(NULL, AV_LOG_ERROR, "Invalid empty interval specification\n");
ret = AVERROR(EINVAL);
goto end;
}
p = spec;
next = strchr(spec, '%');
if (next)
*next++ = 0;
/* parse first part */
if (*p) {
interval->has_start = 1;
if (*p == '+') {
interval->start_is_offset = 1;
p++;
} else {
interval->start_is_offset = 0;
}
ret = av_parse_time(&interval->start, p, 1);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Invalid interval start specification '%s'\n", p);
goto end;
}
} else {
interval->has_start = 0;
}
/* parse second part */
p = next;
if (p && *p) {
int64_t us;
interval->has_end = 1;
if (*p == '+') {
interval->end_is_offset = 1;
p++;
} else {
interval->end_is_offset = 0;
}
if (interval->end_is_offset && *p == '#') {
long long int lli;
char *tail;
interval->duration_frames = 1;
p++;
lli = strtoll(p, &tail, 10);
if (*tail || lli < 0) {
av_log(NULL, AV_LOG_ERROR,
"Invalid or negative value '%s' for duration number of frames\n", p);
goto end;
}
interval->end = lli;
} else {
interval->duration_frames = 0;
ret = av_parse_time(&us, p, 1);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Invalid interval end/duration specification '%s'\n", p);
goto end;
}
interval->end = us;
}
} else {
interval->has_end = 0;
}
end:
av_free(spec);
return ret;
}
static int parse_read_intervals(const char *intervals_spec)
{
int ret, n, i;
char *p, *spec = av_strdup(intervals_spec);
if (!spec)
return AVERROR(ENOMEM);
/* preparse specification, get number of intervals */
for (n = 0, p = spec; *p; p++)
if (*p == ',')
n++;
n++;
read_intervals = av_malloc_array(n, sizeof(*read_intervals));
if (!read_intervals) {
ret = AVERROR(ENOMEM);
goto end;
}
read_intervals_nb = n;
/* parse intervals */
p = spec;
for (i = 0; p; i++) {
char *next;
av_assert0(i < read_intervals_nb);
next = strchr(p, ',');
if (next)
*next++ = 0;
read_intervals[i].id = i;
ret = parse_read_interval(p, &read_intervals[i]);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error parsing read interval #%d '%s'\n",
i, p);
goto end;
}
av_log(NULL, AV_LOG_VERBOSE, "Parsed log interval ");
log_read_interval(&read_intervals[i], NULL, AV_LOG_VERBOSE);
p = next;
}
av_assert0(i == read_intervals_nb);
end:
av_free(spec);
return ret;
}
static int opt_read_intervals(void *optctx, const char *opt, const char *arg)
{
return parse_read_intervals(arg);
}
static int opt_pretty(void *optctx, const char *opt, const char *arg)
{
show_value_unit = 1;
use_value_prefix = 1;
use_byte_value_binary_prefix = 1;
use_value_sexagesimal_format = 1;
return 0;
}
static void print_section(SectionID id, int level)
{
const SectionID *pid;
const struct section *section = §ions[id];
printf("%c%c%c",
section->flags & SECTION_FLAG_IS_WRAPPER ? 'W' : '.',
section->flags & SECTION_FLAG_IS_ARRAY ? 'A' : '.',
section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS ? 'V' : '.');
printf("%*c %s", level * 4, ' ', section->name);
if (section->unique_name)
printf("/%s", section->unique_name);
printf("\n");
for (pid = section->children_ids; *pid != -1; pid++)
print_section(*pid, level+1);
}
static int opt_sections(void *optctx, const char *opt, const char *arg)
{
printf("Sections:\n"
"W.. = Section is a wrapper (contains other sections, no local entries)\n"
".A. = Section contains an array of elements of the same type\n"
"..V = Section may contain a variable number of fields with variable keys\n"
"FLAGS NAME/UNIQUE_NAME\n"
"---\n");
print_section(SECTION_ID_ROOT, 0);
return 0;
}
static int opt_show_versions(const char *opt, const char *arg)
{
mark_section_show_entries(SECTION_ID_PROGRAM_VERSION, 1, NULL);
mark_section_show_entries(SECTION_ID_LIBRARY_VERSION, 1, NULL);
return 0;
}
#define DEFINE_OPT_SHOW_SECTION(section, target_section_id) \
static int opt_show_##section(const char *opt, const char *arg) \
{ \
mark_section_show_entries(SECTION_ID_##target_section_id, 1, NULL); \
return 0; \
}
DEFINE_OPT_SHOW_SECTION(chapters, CHAPTERS)
DEFINE_OPT_SHOW_SECTION(error, ERROR)
DEFINE_OPT_SHOW_SECTION(format, FORMAT)
DEFINE_OPT_SHOW_SECTION(frames, FRAMES)
DEFINE_OPT_SHOW_SECTION(library_versions, LIBRARY_VERSIONS)
DEFINE_OPT_SHOW_SECTION(packets, PACKETS)
DEFINE_OPT_SHOW_SECTION(pixel_formats, PIXEL_FORMATS)
DEFINE_OPT_SHOW_SECTION(program_version, PROGRAM_VERSION)
DEFINE_OPT_SHOW_SECTION(streams, STREAMS)
DEFINE_OPT_SHOW_SECTION(programs, PROGRAMS)
static const OptionDef real_options[] = {
CMDUTILS_COMMON_OPTIONS
{ "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
{ "unit", OPT_BOOL, {&show_value_unit}, "show unit of the displayed values" },
{ "prefix", OPT_BOOL, {&use_value_prefix}, "use SI prefixes for the displayed values" },
{ "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
"use binary prefixes for byte units" },
{ "sexagesimal", OPT_BOOL, {&use_value_sexagesimal_format},
"use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
{ "pretty", 0, {.func_arg = opt_pretty},
"prettify the format of displayed values, make it more human readable" },
{ "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
"set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
{ "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
{ "select_streams", OPT_STRING | HAS_ARG, {(void*)&stream_specifier}, "select the specified streams", "stream_specifier" },
{ "sections", OPT_EXIT, {.func_arg = opt_sections}, "print sections structure and section information, and exit" },
{ "show_data", OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
{ "show_data_hash", OPT_STRING | HAS_ARG, {(void*)&show_data_hash}, "show packets data hash" },
{ "show_error", 0, {(void*)&opt_show_error}, "show probing error" },
{ "show_format", 0, {(void*)&opt_show_format}, "show format/container info" },
{ "show_frames", 0, {(void*)&opt_show_frames}, "show frames info" },
{ "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
"show a particular entry from the format/container info", "entry" },
{ "show_entries", HAS_ARG, {.func_arg = opt_show_entries},
"show a set of specified entries", "entry_list" },
#if HAVE_THREADS
{ "show_log", OPT_INT|HAS_ARG, {(void*)&do_show_log}, "show log" },
#endif
{ "show_packets", 0, {(void*)&opt_show_packets}, "show packets info" },
{ "show_programs", 0, {(void*)&opt_show_programs}, "show programs info" },
{ "show_streams", 0, {(void*)&opt_show_streams}, "show streams info" },
{ "show_chapters", 0, {(void*)&opt_show_chapters}, "show chapters info" },
{ "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
{ "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
{ "show_program_version", 0, {(void*)&opt_show_program_version}, "show ffprobe version" },
{ "show_library_versions", 0, {(void*)&opt_show_library_versions}, "show library versions" },
{ "show_versions", 0, {(void*)&opt_show_versions}, "show program and library versions" },
{ "show_pixel_formats", 0, {(void*)&opt_show_pixel_formats}, "show pixel format descriptions" },
{ "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
{ "private", OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
{ "bitexact", OPT_BOOL, {&do_bitexact}, "force bitexact output" },
{ "read_intervals", HAS_ARG, {.func_arg = opt_read_intervals}, "set read intervals", "read_intervals" },
{ "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default}, "generic catch all option", "" },
{ "i", HAS_ARG, {.func_arg = opt_input_file_i}, "read specified file", "input_file"},
{ "find_stream_info", OPT_BOOL | OPT_INPUT | OPT_EXPERT, { &find_stream_info },
"read and decode the streams to fill missing information with heuristics" },
{ NULL, },
};
static inline int check_section_show_entries(int section_id)
{
int *id;
struct section *section = §ions[section_id];
if (sections[section_id].show_all_entries || sections[section_id].entries_to_show)
return 1;
for (id = section->children_ids; *id != -1; id++)
if (check_section_show_entries(*id))
return 1;
return 0;
}
#define SET_DO_SHOW(id, varname) do { \
if (check_section_show_entries(SECTION_ID_##id)) \
do_show_##varname = 1; \
} while (0)
int main(int argc, char **argv)
{
const Writer *w;
WriterContext *wctx;
char *buf;
char *w_name = NULL, *w_args = NULL;
int ret, i;
init_dynload();
#if HAVE_THREADS
ret = pthread_mutex_init(&log_mutex, NULL);
if (ret != 0) {
goto end;
}
#endif
av_log_set_flags(AV_LOG_SKIP_REPEATED);
register_exit(ffprobe_cleanup);
options = real_options;
parse_loglevel(argc, argv, options);
av_register_all();
avformat_network_init();
init_opts();
#if CONFIG_AVDEVICE
avdevice_register_all();
#endif
show_banner(argc, argv, options);
parse_options(NULL, argc, argv, options, opt_input_file);
if (do_show_log)
av_log_set_callback(log_callback);
/* mark things to show, based on -show_entries */
SET_DO_SHOW(CHAPTERS, chapters);
SET_DO_SHOW(ERROR, error);
SET_DO_SHOW(FORMAT, format);
SET_DO_SHOW(FRAMES, frames);
SET_DO_SHOW(LIBRARY_VERSIONS, library_versions);
SET_DO_SHOW(PACKETS, packets);
SET_DO_SHOW(PIXEL_FORMATS, pixel_formats);
SET_DO_SHOW(PIXEL_FORMAT_FLAGS, pixel_format_flags);
SET_DO_SHOW(PIXEL_FORMAT_COMPONENTS, pixel_format_components);
SET_DO_SHOW(PROGRAM_VERSION, program_version);
SET_DO_SHOW(PROGRAMS, programs);
SET_DO_SHOW(STREAMS, streams);
SET_DO_SHOW(STREAM_DISPOSITION, stream_disposition);
SET_DO_SHOW(PROGRAM_STREAM_DISPOSITION, stream_disposition);
SET_DO_SHOW(CHAPTER_TAGS, chapter_tags);
SET_DO_SHOW(FORMAT_TAGS, format_tags);
SET_DO_SHOW(FRAME_TAGS, frame_tags);
SET_DO_SHOW(PROGRAM_TAGS, program_tags);
SET_DO_SHOW(STREAM_TAGS, stream_tags);
SET_DO_SHOW(PROGRAM_STREAM_TAGS, stream_tags);
SET_DO_SHOW(PACKET_TAGS, packet_tags);
if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
av_log(NULL, AV_LOG_ERROR,
"-bitexact and -show_program_version or -show_library_versions "
"options are incompatible\n");
ret = AVERROR(EINVAL);
goto end;
}
writer_register_all();
if (!print_format)
print_format = av_strdup("default");
if (!print_format) {
ret = AVERROR(ENOMEM);
goto end;
}
w_name = av_strtok(print_format, "=", &buf);
if (!w_name) {
av_log(NULL, AV_LOG_ERROR,
"No name specified for the output format\n");
ret = AVERROR(EINVAL);
goto end;
}
w_args = buf;
if (show_data_hash) {
if ((ret = av_hash_alloc(&hash, show_data_hash)) < 0) {
if (ret == AVERROR(EINVAL)) {
const char *n;
av_log(NULL, AV_LOG_ERROR,
"Unknown hash algorithm '%s'\nKnown algorithms:",
show_data_hash);
for (i = 0; (n = av_hash_names(i)); i++)
av_log(NULL, AV_LOG_ERROR, " %s", n);
av_log(NULL, AV_LOG_ERROR, "\n");
}
goto end;
}
}
w = writer_get_by_name(w_name);
if (!w) {
av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
ret = AVERROR(EINVAL);
goto end;
}
if ((ret = writer_open(&wctx, w, w_args,
sections, FF_ARRAY_ELEMS(sections))) >= 0) {
if (w == &xml_writer)
wctx->string_validation_utf8_flags |= AV_UTF8_FLAG_EXCLUDE_XML_INVALID_CONTROL_CODES;
writer_print_section_header(wctx, SECTION_ID_ROOT);
if (do_show_program_version)
ffprobe_show_program_version(wctx);
if (do_show_library_versions)
ffprobe_show_library_versions(wctx);
if (do_show_pixel_formats)
ffprobe_show_pixel_formats(wctx);
if (!input_filename &&
((do_show_format || do_show_programs || do_show_streams || do_show_chapters || do_show_packets || do_show_error) ||
(!do_show_program_version && !do_show_library_versions && !do_show_pixel_formats))) {
show_usage();
av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
ret = AVERROR(EINVAL);
} else if (input_filename) {
ret = probe_file(wctx, input_filename);
if (ret < 0 && do_show_error)
show_error(wctx, ret);
}
writer_print_section_footer(wctx);
writer_close(&wctx);
}
end:
av_freep(&print_format);
av_freep(&read_intervals);
av_hash_freep(&hash);
uninit_opts();
for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
av_dict_free(&(sections[i].entries_to_show));
avformat_network_deinit();
return ret < 0;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_2788_0 |
crossvul-cpp_data_bad_2903_0 | /* radare - LGPL - Copyright 2008-2017 - nibble, pancake, alvaro_fe */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <r_types.h>
#include <r_util.h>
#include "elf.h"
#ifdef IFDBG
#undef IFDBG
#endif
#define DO_THE_DBG 0
#define IFDBG if (DO_THE_DBG)
#define IFINT if (0)
#define ELF_PAGE_MASK 0xFFFFFFFFFFFFF000LL
#define ELF_PAGE_SIZE 12
#define R_ELF_NO_RELRO 0
#define R_ELF_PART_RELRO 1
#define R_ELF_FULL_RELRO 2
#define bprintf if(bin->verbose)eprintf
#define READ8(x, i) r_read_ble8(x + i); i += 1;
#define READ16(x, i) r_read_ble16(x + i, bin->endian); i += 2;
#define READ32(x, i) r_read_ble32(x + i, bin->endian); i += 4;
#define READ64(x, i) r_read_ble64(x + i, bin->endian); i += 8;
#define GROWTH_FACTOR (1.5)
static inline int __strnlen(const char *str, int len) {
int l = 0;
while (IS_PRINTABLE (*str) && --len) {
if (((ut8)*str) == 0xff) {
break;
}
str++;
l++;
}
return l + 1;
}
static int handle_e_ident(ELFOBJ *bin) {
return !strncmp ((char *)bin->ehdr.e_ident, ELFMAG, SELFMAG) ||
!strncmp ((char *)bin->ehdr.e_ident, CGCMAG, SCGCMAG);
}
static int init_ehdr(ELFOBJ *bin) {
ut8 e_ident[EI_NIDENT];
ut8 ehdr[sizeof (Elf_(Ehdr))] = {0};
int i, len;
if (r_buf_read_at (bin->b, 0, e_ident, EI_NIDENT) == -1) {
bprintf ("Warning: read (magic)\n");
return false;
}
sdb_set (bin->kv, "elf_type.cparse", "enum elf_type { ET_NONE=0, ET_REL=1,"
" ET_EXEC=2, ET_DYN=3, ET_CORE=4, ET_LOOS=0xfe00, ET_HIOS=0xfeff,"
" ET_LOPROC=0xff00, ET_HIPROC=0xffff };", 0);
sdb_set (bin->kv, "elf_machine.cparse", "enum elf_machine{EM_NONE=0, EM_M32=1,"
" EM_SPARC=2, EM_386=3, EM_68K=4, EM_88K=5, EM_486=6, "
" EM_860=7, EM_MIPS=8, EM_S370=9, EM_MIPS_RS3_LE=10, EM_RS6000=11,"
" EM_UNKNOWN12=12, EM_UNKNOWN13=13, EM_UNKNOWN14=14, "
" EM_PA_RISC=15, EM_PARISC=EM_PA_RISC, EM_nCUBE=16, EM_VPP500=17,"
" EM_SPARC32PLUS=18, EM_960=19, EM_PPC=20, EM_PPC64=21, "
" EM_S390=22, EM_UNKNOWN22=EM_S390, EM_UNKNOWN23=23, EM_UNKNOWN24=24,"
" EM_UNKNOWN25=25, EM_UNKNOWN26=26, EM_UNKNOWN27=27, EM_UNKNOWN28=28,"
" EM_UNKNOWN29=29, EM_UNKNOWN30=30, EM_UNKNOWN31=31, EM_UNKNOWN32=32,"
" EM_UNKNOWN33=33, EM_UNKNOWN34=34, EM_UNKNOWN35=35, EM_V800=36,"
" EM_FR20=37, EM_RH32=38, EM_RCE=39, EM_ARM=40, EM_ALPHA=41, EM_SH=42,"
" EM_SPARCV9=43, EM_TRICORE=44, EM_ARC=45, EM_H8_300=46, EM_H8_300H=47,"
" EM_H8S=48, EM_H8_500=49, EM_IA_64=50, EM_MIPS_X=51, EM_COLDFIRE=52,"
" EM_68HC12=53, EM_MMA=54, EM_PCP=55, EM_NCPU=56, EM_NDR1=57,"
" EM_STARCORE=58, EM_ME16=59, EM_ST100=60, EM_TINYJ=61, EM_AMD64=62,"
" EM_X86_64=EM_AMD64, EM_PDSP=63, EM_UNKNOWN64=64, EM_UNKNOWN65=65,"
" EM_FX66=66, EM_ST9PLUS=67, EM_ST7=68, EM_68HC16=69, EM_68HC11=70,"
" EM_68HC08=71, EM_68HC05=72, EM_SVX=73, EM_ST19=74, EM_VAX=75, "
" EM_CRIS=76, EM_JAVELIN=77, EM_FIREPATH=78, EM_ZSP=79, EM_MMIX=80,"
" EM_HUANY=81, EM_PRISM=82, EM_AVR=83, EM_FR30=84, EM_D10V=85, EM_D30V=86,"
" EM_V850=87, EM_M32R=88, EM_MN10300=89, EM_MN10200=90, EM_PJ=91,"
" EM_OPENRISC=92, EM_ARC_A5=93, EM_XTENSA=94, EM_NUM=95};", 0);
sdb_num_set (bin->kv, "elf_header.offset", 0, 0);
sdb_num_set (bin->kv, "elf_header.size", sizeof (Elf_(Ehdr)), 0);
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exqqqxwwwwww"
" ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize"
" phentsize phnum shentsize shnum shstrndx", 0);
#else
sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exxxxxwwwwww"
" ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize"
" phentsize phnum shentsize shnum shstrndx", 0);
#endif
bin->endian = (e_ident[EI_DATA] == ELFDATA2MSB)? 1: 0;
memset (&bin->ehdr, 0, sizeof (Elf_(Ehdr)));
len = r_buf_read_at (bin->b, 0, ehdr, sizeof (Elf_(Ehdr)));
if (len < 1) {
bprintf ("Warning: read (ehdr)\n");
return false;
}
memcpy (&bin->ehdr.e_ident, ehdr, 16);
i = 16;
bin->ehdr.e_type = READ16 (ehdr, i)
bin->ehdr.e_machine = READ16 (ehdr, i)
bin->ehdr.e_version = READ32 (ehdr, i)
#if R_BIN_ELF64
bin->ehdr.e_entry = READ64 (ehdr, i)
bin->ehdr.e_phoff = READ64 (ehdr, i)
bin->ehdr.e_shoff = READ64 (ehdr, i)
#else
bin->ehdr.e_entry = READ32 (ehdr, i)
bin->ehdr.e_phoff = READ32 (ehdr, i)
bin->ehdr.e_shoff = READ32 (ehdr, i)
#endif
bin->ehdr.e_flags = READ32 (ehdr, i)
bin->ehdr.e_ehsize = READ16 (ehdr, i)
bin->ehdr.e_phentsize = READ16 (ehdr, i)
bin->ehdr.e_phnum = READ16 (ehdr, i)
bin->ehdr.e_shentsize = READ16 (ehdr, i)
bin->ehdr.e_shnum = READ16 (ehdr, i)
bin->ehdr.e_shstrndx = READ16 (ehdr, i)
return handle_e_ident (bin);
// Usage example:
// > td `k bin/cur/info/elf_type.cparse`; td `k bin/cur/info/elf_machine.cparse`
// > pf `k bin/cur/info/elf_header.format` @ `k bin/cur/info/elf_header.offset`
}
static int init_phdr(ELFOBJ *bin) {
ut32 phdr_size;
ut8 phdr[sizeof (Elf_(Phdr))] = {0};
int i, j, len;
if (!bin->ehdr.e_phnum) {
return false;
}
if (bin->phdr) {
return true;
}
if (!UT32_MUL (&phdr_size, (ut32)bin->ehdr.e_phnum, sizeof (Elf_(Phdr)))) {
return false;
}
if (!phdr_size) {
return false;
}
if (phdr_size > bin->size) {
return false;
}
if (phdr_size > (ut32)bin->size) {
return false;
}
if (bin->ehdr.e_phoff > bin->size) {
return false;
}
if (bin->ehdr.e_phoff + phdr_size > bin->size) {
return false;
}
if (!(bin->phdr = calloc (phdr_size, 1))) {
perror ("malloc (phdr)");
return false;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
j = 0;
len = r_buf_read_at (bin->b, bin->ehdr.e_phoff + i * sizeof (Elf_(Phdr)), phdr, sizeof (Elf_(Phdr)));
if (len < 1) {
bprintf ("Warning: read (phdr)\n");
R_FREE (bin->phdr);
return false;
}
bin->phdr[i].p_type = READ32 (phdr, j)
#if R_BIN_ELF64
bin->phdr[i].p_flags = READ32 (phdr, j)
bin->phdr[i].p_offset = READ64 (phdr, j)
bin->phdr[i].p_vaddr = READ64 (phdr, j)
bin->phdr[i].p_paddr = READ64 (phdr, j)
bin->phdr[i].p_filesz = READ64 (phdr, j)
bin->phdr[i].p_memsz = READ64 (phdr, j)
bin->phdr[i].p_align = READ64 (phdr, j)
#else
bin->phdr[i].p_offset = READ32 (phdr, j)
bin->phdr[i].p_vaddr = READ32 (phdr, j)
bin->phdr[i].p_paddr = READ32 (phdr, j)
bin->phdr[i].p_filesz = READ32 (phdr, j)
bin->phdr[i].p_memsz = READ32 (phdr, j)
bin->phdr[i].p_flags = READ32 (phdr, j)
bin->phdr[i].p_align = READ32 (phdr, j)
#endif
}
sdb_num_set (bin->kv, "elf_phdr.offset", bin->ehdr.e_phoff, 0);
sdb_num_set (bin->kv, "elf_phdr.size", sizeof (Elf_(Phdr)), 0);
sdb_set (bin->kv, "elf_p_type.cparse", "enum elf_p_type {PT_NULL=0,PT_LOAD=1,PT_DYNAMIC=2,"
"PT_INTERP=3,PT_NOTE=4,PT_SHLIB=5,PT_PHDR=6,PT_LOOS=0x60000000,"
"PT_HIOS=0x6fffffff,PT_LOPROC=0x70000000,PT_HIPROC=0x7fffffff};", 0);
sdb_set (bin->kv, "elf_p_flags.cparse", "enum elf_p_flags {PF_None=0,PF_Exec=1,"
"PF_Write=2,PF_Write_Exec=3,PF_Read=4,PF_Read_Exec=5,PF_Read_Write=6,"
"PF_Read_Write_Exec=7};", 0);
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_phdr.format", "[4]E[4]Eqqqqqq (elf_p_type)type (elf_p_flags)flags"
" offset vaddr paddr filesz memsz align", 0);
#else
sdb_set (bin->kv, "elf_phdr.format", "[4]Exxxxx[4]Ex (elf_p_type)type offset vaddr paddr"
" filesz memsz (elf_p_flags)flags align", 0);
#endif
return true;
// Usage example:
// > td `k bin/cur/info/elf_p_type.cparse`; td `k bin/cur/info/elf_p_flags.cparse`
// > pf `k bin/cur/info/elf_phdr.format` @ `k bin/cur/info/elf_phdr.offset`
}
static int init_shdr(ELFOBJ *bin) {
ut32 shdr_size;
ut8 shdr[sizeof (Elf_(Shdr))] = {0};
int i, j, len;
if (!bin || bin->shdr) {
return true;
}
if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) {
return false;
}
if (shdr_size < 1) {
return false;
}
if (shdr_size > bin->size) {
return false;
}
if (bin->ehdr.e_shoff > bin->size) {
return false;
}
if (bin->ehdr.e_shoff + shdr_size > bin->size) {
return false;
}
if (!(bin->shdr = calloc (1, shdr_size + 1))) {
perror ("malloc (shdr)");
return false;
}
sdb_num_set (bin->kv, "elf_shdr.offset", bin->ehdr.e_shoff, 0);
sdb_num_set (bin->kv, "elf_shdr.size", sizeof (Elf_(Shdr)), 0);
sdb_set (bin->kv, "elf_s_type.cparse", "enum elf_s_type {SHT_NULL=0,SHT_PROGBITS=1,"
"SHT_SYMTAB=2,SHT_STRTAB=3,SHT_RELA=4,SHT_HASH=5,SHT_DYNAMIC=6,SHT_NOTE=7,"
"SHT_NOBITS=8,SHT_REL=9,SHT_SHLIB=10,SHT_DYNSYM=11,SHT_LOOS=0x60000000,"
"SHT_HIOS=0x6fffffff,SHT_LOPROC=0x70000000,SHT_HIPROC=0x7fffffff};", 0);
for (i = 0; i < bin->ehdr.e_shnum; i++) {
j = 0;
len = r_buf_read_at (bin->b, bin->ehdr.e_shoff + i * sizeof (Elf_(Shdr)), shdr, sizeof (Elf_(Shdr)));
if (len < 1) {
bprintf ("Warning: read (shdr) at 0x%"PFMT64x"\n", (ut64) bin->ehdr.e_shoff);
R_FREE (bin->shdr);
return false;
}
bin->shdr[i].sh_name = READ32 (shdr, j)
bin->shdr[i].sh_type = READ32 (shdr, j)
#if R_BIN_ELF64
bin->shdr[i].sh_flags = READ64 (shdr, j)
bin->shdr[i].sh_addr = READ64 (shdr, j)
bin->shdr[i].sh_offset = READ64 (shdr, j)
bin->shdr[i].sh_size = READ64 (shdr, j)
bin->shdr[i].sh_link = READ32 (shdr, j)
bin->shdr[i].sh_info = READ32 (shdr, j)
bin->shdr[i].sh_addralign = READ64 (shdr, j)
bin->shdr[i].sh_entsize = READ64 (shdr, j)
#else
bin->shdr[i].sh_flags = READ32 (shdr, j)
bin->shdr[i].sh_addr = READ32 (shdr, j)
bin->shdr[i].sh_offset = READ32 (shdr, j)
bin->shdr[i].sh_size = READ32 (shdr, j)
bin->shdr[i].sh_link = READ32 (shdr, j)
bin->shdr[i].sh_info = READ32 (shdr, j)
bin->shdr[i].sh_addralign = READ32 (shdr, j)
bin->shdr[i].sh_entsize = READ32 (shdr, j)
#endif
}
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_s_flags_64.cparse", "enum elf_s_flags_64 {SF64_None=0,SF64_Exec=1,"
"SF64_Alloc=2,SF64_Alloc_Exec=3,SF64_Write=4,SF64_Write_Exec=5,"
"SF64_Write_Alloc=6,SF64_Write_Alloc_Exec=7};", 0);
sdb_set (bin->kv, "elf_shdr.format", "x[4]E[8]Eqqqxxqq name (elf_s_type)type"
" (elf_s_flags_64)flags addr offset size link info addralign entsize", 0);
#else
sdb_set (bin->kv, "elf_s_flags_32.cparse", "enum elf_s_flags_32 {SF32_None=0,SF32_Exec=1,"
"SF32_Alloc=2,SF32_Alloc_Exec=3,SF32_Write=4,SF32_Write_Exec=5,"
"SF32_Write_Alloc=6,SF32_Write_Alloc_Exec=7};", 0);
sdb_set (bin->kv, "elf_shdr.format", "x[4]E[4]Exxxxxxx name (elf_s_type)type"
" (elf_s_flags_32)flags addr offset size link info addralign entsize", 0);
#endif
return true;
// Usage example:
// > td `k bin/cur/info/elf_s_type.cparse`; td `k bin/cur/info/elf_s_flags_64.cparse`
// > pf `k bin/cur/info/elf_shdr.format` @ `k bin/cur/info/elf_shdr.offset`
}
static int init_strtab(ELFOBJ *bin) {
if (bin->strtab || !bin->shdr) {
return false;
}
if (bin->ehdr.e_shstrndx != SHN_UNDEF &&
(bin->ehdr.e_shstrndx >= bin->ehdr.e_shnum ||
(bin->ehdr.e_shstrndx >= SHN_LORESERVE &&
bin->ehdr.e_shstrndx < SHN_HIRESERVE)))
return false;
/* sh_size must be lower than UT32_MAX and not equal to zero, to avoid bugs on malloc() */
if (bin->shdr[bin->ehdr.e_shstrndx].sh_size > UT32_MAX) {
return false;
}
if (!bin->shdr[bin->ehdr.e_shstrndx].sh_size) {
return false;
}
bin->shstrtab_section = bin->strtab_section = &bin->shdr[bin->ehdr.e_shstrndx];
bin->shstrtab_size = bin->strtab_section->sh_size;
if (bin->shstrtab_size > bin->size) {
return false;
}
if (!(bin->shstrtab = calloc (1, bin->shstrtab_size + 1))) {
perror ("malloc");
bin->shstrtab = NULL;
return false;
}
if (bin->shstrtab_section->sh_offset > bin->size) {
R_FREE (bin->shstrtab);
return false;
}
if (bin->shstrtab_section->sh_offset +
bin->shstrtab_section->sh_size > bin->size) {
R_FREE (bin->shstrtab);
return false;
}
if (r_buf_read_at (bin->b, bin->shstrtab_section->sh_offset, (ut8*)bin->shstrtab,
bin->shstrtab_section->sh_size + 1) < 1) {
bprintf ("Warning: read (shstrtab) at 0x%"PFMT64x"\n",
(ut64) bin->shstrtab_section->sh_offset);
R_FREE (bin->shstrtab);
return false;
}
bin->shstrtab[bin->shstrtab_section->sh_size] = '\0';
sdb_num_set (bin->kv, "elf_shstrtab.offset", bin->shstrtab_section->sh_offset, 0);
sdb_num_set (bin->kv, "elf_shstrtab.size", bin->shstrtab_section->sh_size, 0);
return true;
}
static int init_dynamic_section(struct Elf_(r_bin_elf_obj_t) *bin) {
Elf_(Dyn) *dyn = NULL;
Elf_(Dyn) d = {0};
Elf_(Addr) strtabaddr = 0;
ut64 offset = 0;
char *strtab = NULL;
size_t relentry = 0, strsize = 0;
int entries;
int i, j, len, r;
ut8 sdyn[sizeof (Elf_(Dyn))] = {0};
ut32 dyn_size = 0;
if (!bin || !bin->phdr || !bin->ehdr.e_phnum) {
return false;
}
for (i = 0; i < bin->ehdr.e_phnum ; i++) {
if (bin->phdr[i].p_type == PT_DYNAMIC) {
dyn_size = bin->phdr[i].p_filesz;
break;
}
}
if (i == bin->ehdr.e_phnum) {
return false;
}
if (bin->phdr[i].p_filesz > bin->size) {
return false;
}
if (bin->phdr[i].p_offset > bin->size) {
return false;
}
if (bin->phdr[i].p_offset + sizeof(Elf_(Dyn)) > bin->size) {
return false;
}
for (entries = 0; entries < (dyn_size / sizeof (Elf_(Dyn))); entries++) {
j = 0;
len = r_buf_read_at (bin->b, bin->phdr[i].p_offset + entries * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn)));
if (len < 1) {
goto beach;
}
#if R_BIN_ELF64
d.d_tag = READ64 (sdyn, j)
#else
d.d_tag = READ32 (sdyn, j)
#endif
if (d.d_tag == DT_NULL) {
break;
}
}
if (entries < 1) {
return false;
}
dyn = (Elf_(Dyn)*)calloc (entries, sizeof (Elf_(Dyn)));
if (!dyn) {
return false;
}
if (!UT32_MUL (&dyn_size, entries, sizeof (Elf_(Dyn)))) {
goto beach;
}
if (!dyn_size) {
goto beach;
}
offset = Elf_(r_bin_elf_v2p) (bin, bin->phdr[i].p_vaddr);
if (offset > bin->size || offset + dyn_size > bin->size) {
goto beach;
}
for (i = 0; i < entries; i++) {
j = 0;
r_buf_read_at (bin->b, offset + i * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn)));
if (len < 1) {
bprintf("Warning: read (dyn)\n");
}
#if R_BIN_ELF64
dyn[i].d_tag = READ64 (sdyn, j)
dyn[i].d_un.d_ptr = READ64 (sdyn, j)
#else
dyn[i].d_tag = READ32 (sdyn, j)
dyn[i].d_un.d_ptr = READ32 (sdyn, j)
#endif
switch (dyn[i].d_tag) {
case DT_STRTAB: strtabaddr = Elf_(r_bin_elf_v2p) (bin, dyn[i].d_un.d_ptr); break;
case DT_STRSZ: strsize = dyn[i].d_un.d_val; break;
case DT_PLTREL: bin->is_rela = dyn[i].d_un.d_val; break;
case DT_RELAENT: relentry = dyn[i].d_un.d_val; break;
default:
if ((dyn[i].d_tag >= DT_VERSYM) && (dyn[i].d_tag <= DT_VERNEEDNUM)) {
bin->version_info[DT_VERSIONTAGIDX (dyn[i].d_tag)] = dyn[i].d_un.d_val;
}
break;
}
}
if (!bin->is_rela) {
bin->is_rela = sizeof (Elf_(Rela)) == relentry? DT_RELA : DT_REL;
}
if (!strtabaddr || strtabaddr > bin->size || strsize > ST32_MAX || !strsize || strsize > bin->size) {
if (!strtabaddr) {
bprintf ("Warning: section.shstrtab not found or invalid\n");
}
goto beach;
}
strtab = (char *)calloc (1, strsize + 1);
if (!strtab) {
goto beach;
}
if (strtabaddr + strsize > bin->size) {
free (strtab);
goto beach;
}
r = r_buf_read_at (bin->b, strtabaddr, (ut8 *)strtab, strsize);
if (r < 1) {
free (strtab);
goto beach;
}
bin->dyn_buf = dyn;
bin->dyn_entries = entries;
bin->strtab = strtab;
bin->strtab_size = strsize;
r = Elf_(r_bin_elf_has_relro)(bin);
switch (r) {
case R_ELF_FULL_RELRO:
sdb_set (bin->kv, "elf.relro", "full", 0);
break;
case R_ELF_PART_RELRO:
sdb_set (bin->kv, "elf.relro", "partial", 0);
break;
default:
sdb_set (bin->kv, "elf.relro", "no", 0);
break;
}
sdb_num_set (bin->kv, "elf_strtab.offset", strtabaddr, 0);
sdb_num_set (bin->kv, "elf_strtab.size", strsize, 0);
return true;
beach:
free (dyn);
return false;
}
static RBinElfSection* get_section_by_name(ELFOBJ *bin, const char *section_name) {
int i;
if (!bin->g_sections) {
return NULL;
}
for (i = 0; !bin->g_sections[i].last; i++) {
if (!strncmp (bin->g_sections[i].name, section_name, ELF_STRING_LENGTH-1)) {
return &bin->g_sections[i];
}
}
return NULL;
}
static char *get_ver_flags(ut32 flags) {
static char buff[32];
buff[0] = 0;
if (!flags) {
return "none";
}
if (flags & VER_FLG_BASE) {
strcpy (buff, "BASE ");
}
if (flags & VER_FLG_WEAK) {
if (flags & VER_FLG_BASE) {
strcat (buff, "| ");
}
strcat (buff, "WEAK ");
}
if (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)) {
strcat (buff, "| <unknown>");
}
return buff;
}
static Sdb *store_versioninfo_gnu_versym(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
int i;
const ut64 num_entries = sz / sizeof (Elf_(Versym));
const char *section_name = "";
const char *link_section_name = "";
Elf_(Shdr) *link_shdr = NULL;
Sdb *sdb = sdb_new0();
if (!sdb) {
return NULL;
}
if (!bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]) {
sdb_free (sdb);
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
sdb_free (sdb);
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
ut8 *edata = (ut8*) calloc (R_MAX (1, num_entries), sizeof (ut16));
if (!edata) {
sdb_free (sdb);
return NULL;
}
ut16 *data = (ut16*) calloc (R_MAX (1, num_entries), sizeof (ut16));
if (!data) {
free (edata);
sdb_free (sdb);
return NULL;
}
ut64 off = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]);
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
r_buf_read_at (bin->b, off, edata, sizeof (ut16) * num_entries);
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", num_entries, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (i = num_entries; i--;) {
data[i] = r_read_ble16 (&edata[i * sizeof (ut16)], bin->endian);
}
R_FREE (edata);
for (i = 0; i < num_entries; i += 4) {
int j;
int check_def;
char key[32] = {0};
Sdb *sdb_entry = sdb_new0 ();
snprintf (key, sizeof (key), "entry%d", i / 4);
sdb_ns_set (sdb, key, sdb_entry);
sdb_num_set (sdb_entry, "idx", i, 0);
for (j = 0; (j < 4) && (i + j) < num_entries; ++j) {
int k;
char *tmp_val = NULL;
snprintf (key, sizeof (key), "value%d", j);
switch (data[i + j]) {
case 0:
sdb_set (sdb_entry, key, "0 (*local*)", 0);
break;
case 1:
sdb_set (sdb_entry, key, "1 (*global*)", 0);
break;
default:
tmp_val = sdb_fmt (0, "%x ", data[i+j] & 0x7FFF);
check_def = true;
if (bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]) {
Elf_(Verneed) vn;
ut8 svn[sizeof (Elf_(Verneed))] = {0};
ut64 offset = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]);
do {
Elf_(Vernaux) vna;
ut8 svna[sizeof (Elf_(Vernaux))] = {0};
ut64 a_off;
if (offset > bin->size || offset + sizeof (vn) > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, offset, svn, sizeof (svn)) < 0) {
bprintf ("Warning: Cannot read Verneed for Versym\n");
goto beach;
}
k = 0;
vn.vn_version = READ16 (svn, k)
vn.vn_cnt = READ16 (svn, k)
vn.vn_file = READ32 (svn, k)
vn.vn_aux = READ32 (svn, k)
vn.vn_next = READ32 (svn, k)
a_off = offset + vn.vn_aux;
do {
if (a_off > bin->size || a_off + sizeof (vna) > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, a_off, svna, sizeof (svna)) < 0) {
bprintf ("Warning: Cannot read Vernaux for Versym\n");
goto beach;
}
k = 0;
vna.vna_hash = READ32 (svna, k)
vna.vna_flags = READ16 (svna, k)
vna.vna_other = READ16 (svna, k)
vna.vna_name = READ32 (svna, k)
vna.vna_next = READ32 (svna, k)
a_off += vna.vna_next;
} while (vna.vna_other != data[i + j] && vna.vna_next != 0);
if (vna.vna_other == data[i + j]) {
if (vna.vna_name > bin->strtab_size) {
goto beach;
}
sdb_set (sdb_entry, key, sdb_fmt (0, "%s(%s)", tmp_val, bin->strtab + vna.vna_name), 0);
check_def = false;
break;
}
offset += vn.vn_next;
} while (vn.vn_next);
}
ut64 vinfoaddr = bin->version_info[DT_VERSIONTAGIDX (DT_VERDEF)];
if (check_def && data[i + j] != 0x8001 && vinfoaddr) {
Elf_(Verdef) vd;
ut8 svd[sizeof (Elf_(Verdef))] = {0};
ut64 offset = Elf_(r_bin_elf_v2p) (bin, vinfoaddr);
if (offset > bin->size || offset + sizeof (vd) > bin->size) {
goto beach;
}
do {
if (r_buf_read_at (bin->b, offset, svd, sizeof (svd)) < 0) {
bprintf ("Warning: Cannot read Verdef for Versym\n");
goto beach;
}
k = 0;
vd.vd_version = READ16 (svd, k)
vd.vd_flags = READ16 (svd, k)
vd.vd_ndx = READ16 (svd, k)
vd.vd_cnt = READ16 (svd, k)
vd.vd_hash = READ32 (svd, k)
vd.vd_aux = READ32 (svd, k)
vd.vd_next = READ32 (svd, k)
offset += vd.vd_next;
} while (vd.vd_ndx != (data[i + j] & 0x7FFF) && vd.vd_next != 0);
if (vd.vd_ndx == (data[i + j] & 0x7FFF)) {
Elf_(Verdaux) vda;
ut8 svda[sizeof (Elf_(Verdaux))] = {0};
ut64 off_vda = offset - vd.vd_next + vd.vd_aux;
if (off_vda > bin->size || off_vda + sizeof (vda) > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, off_vda, svda, sizeof (svda)) < 0) {
bprintf ("Warning: Cannot read Verdaux for Versym\n");
goto beach;
}
k = 0;
vda.vda_name = READ32 (svda, k)
vda.vda_next = READ32 (svda, k)
if (vda.vda_name > bin->strtab_size) {
goto beach;
}
const char *name = bin->strtab + vda.vda_name;
sdb_set (sdb_entry, key, sdb_fmt (0,"%s(%s%-*s)", tmp_val, name, (int)(12 - strlen (name)),")") , 0);
}
}
}
}
}
beach:
free (data);
return sdb;
}
static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if ((int)shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1 || vstart + vdaux < vstart) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
ut8 *end, *need = NULL;
const char *section_name = "";
Elf_(Shdr) *link_shdr = NULL;
const char *link_section_name = "";
Sdb *sdb_vernaux = NULL;
Sdb *sdb_version = NULL;
Sdb *sdb = NULL;
int i, cnt;
if (!bin || !bin->dynstr) {
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
return NULL;
}
if ((int)shdr->sh_size < 1) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) {
bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n");
goto beach;
}
end = need + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) {
goto beach;
}
if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) {
goto beach;
}
i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size);
if (i < 0)
goto beach;
//XXX we should use DT_VERNEEDNUM instead of sh_info
//TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html
for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) {
int j, isum;
ut8 *vstart = need + i;
Elf_(Verneed) vvn = {0};
if (vstart + sizeof (Elf_(Verneed)) > end) {
goto beach;
}
Elf_(Verneed) *entry = &vvn;
char key[32] = {0};
sdb_version = sdb_new0 ();
if (!sdb_version) {
goto beach;
}
j = 0;
vvn.vn_version = READ16 (vstart, j)
vvn.vn_cnt = READ16 (vstart, j)
vvn.vn_file = READ32 (vstart, j)
vvn.vn_aux = READ32 (vstart, j)
vvn.vn_next = READ32 (vstart, j)
sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0);
sdb_num_set (sdb_version, "idx", i, 0);
if (entry->vn_file > bin->dynstr_size) {
goto beach;
}
{
char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16);
sdb_set (sdb_version, "file_name", s, 0);
free (s);
}
sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0);
st32 vnaux = entry->vn_aux;
if (vnaux < 1) {
goto beach;
}
vstart += vnaux;
for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) {
int k;
Elf_(Vernaux) * aux = NULL;
Elf_(Vernaux) vaux = {0};
sdb_vernaux = sdb_new0 ();
if (!sdb_vernaux) {
goto beach;
}
aux = (Elf_(Vernaux)*)&vaux;
k = 0;
vaux.vna_hash = READ32 (vstart, k)
vaux.vna_flags = READ16 (vstart, k)
vaux.vna_other = READ16 (vstart, k)
vaux.vna_name = READ32 (vstart, k)
vaux.vna_next = READ32 (vstart, k)
if (aux->vna_name > bin->dynstr_size) {
goto beach;
}
sdb_num_set (sdb_vernaux, "idx", isum, 0);
if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) {
char name [16];
strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1);
name[sizeof(name)-1] = 0;
sdb_set (sdb_vernaux, "name", name, 0);
}
sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0);
sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0);
isum += aux->vna_next;
vstart += aux->vna_next;
snprintf (key, sizeof (key), "vernaux%d", j);
sdb_ns_set (sdb_version, key, sdb_vernaux);
}
if ((int)entry->vn_next < 0) {
bprintf ("Invalid vn_next\n");
break;
}
i += entry->vn_next;
snprintf (key, sizeof (key), "version%d", cnt );
sdb_ns_set (sdb, key, sdb_version);
//if entry->vn_next is 0 it iterate infinitely
if (!entry->vn_next) {
break;
}
}
free (need);
return sdb;
beach:
free (need);
sdb_free (sdb_vernaux);
sdb_free (sdb_version);
sdb_free (sdb);
return NULL;
}
static Sdb *store_versioninfo(ELFOBJ *bin) {
Sdb *sdb_versioninfo = NULL;
int num_verdef = 0;
int num_verneed = 0;
int num_versym = 0;
int i;
if (!bin || !bin->shdr) {
return NULL;
}
if (!(sdb_versioninfo = sdb_new0 ())) {
return NULL;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
Sdb *sdb = NULL;
char key[32] = {0};
int size = bin->shdr[i].sh_size;
if (size - (i*sizeof(Elf_(Shdr)) > bin->size)) {
size = bin->size - (i*sizeof(Elf_(Shdr)));
}
int left = size - (i * sizeof (Elf_(Shdr)));
left = R_MIN (left, bin->shdr[i].sh_size);
if (left < 0) {
break;
}
switch (bin->shdr[i].sh_type) {
case SHT_GNU_verdef:
sdb = store_versioninfo_gnu_verdef (bin, &bin->shdr[i], left);
snprintf (key, sizeof (key), "verdef%d", num_verdef++);
sdb_ns_set (sdb_versioninfo, key, sdb);
break;
case SHT_GNU_verneed:
sdb = store_versioninfo_gnu_verneed (bin, &bin->shdr[i], left);
snprintf (key, sizeof (key), "verneed%d", num_verneed++);
sdb_ns_set (sdb_versioninfo, key, sdb);
break;
case SHT_GNU_versym:
sdb = store_versioninfo_gnu_versym (bin, &bin->shdr[i], left);
snprintf (key, sizeof (key), "versym%d", num_versym++);
sdb_ns_set (sdb_versioninfo, key, sdb);
break;
}
}
return sdb_versioninfo;
}
static bool init_dynstr(ELFOBJ *bin) {
int i, r;
const char *section_name = NULL;
if (!bin || !bin->shdr) {
return false;
}
if (!bin->shstrtab) {
return false;
}
for (i = 0; i < bin->ehdr.e_shnum; ++i) {
if (bin->shdr[i].sh_name > bin->shstrtab_size) {
return false;
}
section_name = &bin->shstrtab[bin->shdr[i].sh_name];
if (bin->shdr[i].sh_type == SHT_STRTAB && !strcmp (section_name, ".dynstr")) {
if (!(bin->dynstr = (char*) calloc (bin->shdr[i].sh_size + 1, sizeof (char)))) {
bprintf("Warning: Cannot allocate memory for dynamic strings\n");
return false;
}
if (bin->shdr[i].sh_offset > bin->size) {
return false;
}
if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size > bin->size) {
return false;
}
if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size < bin->shdr[i].sh_size) {
return false;
}
r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset, (ut8*)bin->dynstr, bin->shdr[i].sh_size);
if (r < 1) {
R_FREE (bin->dynstr);
bin->dynstr_size = 0;
return false;
}
bin->dynstr_size = bin->shdr[i].sh_size;
return true;
}
}
return false;
}
static int elf_init(ELFOBJ *bin) {
bin->phdr = NULL;
bin->shdr = NULL;
bin->strtab = NULL;
bin->shstrtab = NULL;
bin->strtab_size = 0;
bin->strtab_section = NULL;
bin->dyn_buf = NULL;
bin->dynstr = NULL;
ZERO_FILL (bin->version_info);
bin->g_sections = NULL;
bin->g_symbols = NULL;
bin->g_imports = NULL;
/* bin is not an ELF */
if (!init_ehdr (bin)) {
return false;
}
if (!init_phdr (bin)) {
bprintf ("Warning: Cannot initialize program headers\n");
}
if (!init_shdr (bin)) {
bprintf ("Warning: Cannot initialize section headers\n");
}
if (!init_strtab (bin)) {
bprintf ("Warning: Cannot initialize strings table\n");
}
if (!init_dynstr (bin)) {
bprintf ("Warning: Cannot initialize dynamic strings\n");
}
bin->baddr = Elf_(r_bin_elf_get_baddr) (bin);
if (!init_dynamic_section (bin) && !Elf_(r_bin_elf_get_static)(bin))
bprintf ("Warning: Cannot initialize dynamic section\n");
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
bin->symbols_by_ord_size = 0;
bin->symbols_by_ord = NULL;
bin->g_sections = Elf_(r_bin_elf_get_sections) (bin);
bin->boffset = Elf_(r_bin_elf_get_boffset) (bin);
sdb_ns_set (bin->kv, "versioninfo", store_versioninfo (bin));
return true;
}
ut64 Elf_(r_bin_elf_get_section_offset)(ELFOBJ *bin, const char *section_name) {
RBinElfSection *section = get_section_by_name (bin, section_name);
if (!section) return UT64_MAX;
return section->offset;
}
ut64 Elf_(r_bin_elf_get_section_addr)(ELFOBJ *bin, const char *section_name) {
RBinElfSection *section = get_section_by_name (bin, section_name);
return section? section->rva: UT64_MAX;
}
ut64 Elf_(r_bin_elf_get_section_addr_end)(ELFOBJ *bin, const char *section_name) {
RBinElfSection *section = get_section_by_name (bin, section_name);
return section? section->rva + section->size: UT64_MAX;
}
#define REL (is_rela ? (void*)rela : (void*)rel)
#define REL_BUF is_rela ? (ut8*)(&rela[k]) : (ut8*)(&rel[k])
#define REL_OFFSET is_rela ? rela[k].r_offset : rel[k].r_offset
#define REL_TYPE is_rela ? rela[k].r_info : rel[k].r_info
static ut64 get_import_addr(ELFOBJ *bin, int sym) {
Elf_(Rel) *rel = NULL;
Elf_(Rela) *rela = NULL;
ut8 rl[sizeof (Elf_(Rel))] = {0};
ut8 rla[sizeof (Elf_(Rela))] = {0};
RBinElfSection *rel_sec = NULL;
Elf_(Addr) plt_sym_addr = -1;
ut64 got_addr, got_offset;
ut64 plt_addr;
int j, k, tsize, len, nrel;
bool is_rela = false;
const char *rel_sect[] = { ".rel.plt", ".rela.plt", ".rel.dyn", ".rela.dyn", NULL };
const char *rela_sect[] = { ".rela.plt", ".rel.plt", ".rela.dyn", ".rel.dyn", NULL };
if ((!bin->shdr || !bin->strtab) && !bin->phdr) {
return -1;
}
if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) == -1 &&
(got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) == -1) {
return -1;
}
if ((got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got")) == -1 &&
(got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.plt")) == -1) {
return -1;
}
if (bin->is_rela == DT_REL) {
j = 0;
while (!rel_sec && rel_sect[j]) {
rel_sec = get_section_by_name (bin, rel_sect[j++]);
}
tsize = sizeof (Elf_(Rel));
} else if (bin->is_rela == DT_RELA) {
j = 0;
while (!rel_sec && rela_sect[j]) {
rel_sec = get_section_by_name (bin, rela_sect[j++]);
}
is_rela = true;
tsize = sizeof (Elf_(Rela));
}
if (!rel_sec) {
return -1;
}
if (rel_sec->size < 1) {
return -1;
}
nrel = (ut32)((int)rel_sec->size / (int)tsize);
if (nrel < 1) {
return -1;
}
if (is_rela) {
rela = calloc (nrel, tsize);
if (!rela) {
return -1;
}
} else {
rel = calloc (nrel, tsize);
if (!rel) {
return -1;
}
}
for (j = k = 0; j < rel_sec->size && k < nrel; j += tsize, k++) {
int l = 0;
if (rel_sec->offset + j > bin->size) {
goto out;
}
if (rel_sec->offset + j + tsize > bin->size) {
goto out;
}
len = r_buf_read_at (
bin->b, rel_sec->offset + j, is_rela ? rla : rl,
is_rela ? sizeof (Elf_ (Rela)) : sizeof (Elf_ (Rel)));
if (len < 1) {
goto out;
}
#if R_BIN_ELF64
if (is_rela) {
rela[k].r_offset = READ64 (rla, l)
rela[k].r_info = READ64 (rla, l)
rela[k].r_addend = READ64 (rla, l)
} else {
rel[k].r_offset = READ64 (rl, l)
rel[k].r_info = READ64 (rl, l)
}
#else
if (is_rela) {
rela[k].r_offset = READ32 (rla, l)
rela[k].r_info = READ32 (rla, l)
rela[k].r_addend = READ32 (rla, l)
} else {
rel[k].r_offset = READ32 (rl, l)
rel[k].r_info = READ32 (rl, l)
}
#endif
int reloc_type = ELF_R_TYPE (REL_TYPE);
int reloc_sym = ELF_R_SYM (REL_TYPE);
if (reloc_sym == sym) {
int of = REL_OFFSET;
of = of - got_addr + got_offset;
switch (bin->ehdr.e_machine) {
case EM_PPC:
case EM_PPC64:
{
RBinElfSection *s = get_section_by_name (bin, ".plt");
if (s) {
ut8 buf[4];
ut64 base;
len = r_buf_read_at (bin->b, s->offset, buf, sizeof (buf));
if (len < 4) {
goto out;
}
base = r_read_be32 (buf);
base -= (nrel * 16);
base += (k * 16);
plt_addr = base;
free (REL);
return plt_addr;
}
}
break;
case EM_SPARC:
case EM_SPARCV9:
case EM_SPARC32PLUS:
plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt");
if (plt_addr == -1) {
free (rela);
return -1;
}
if (reloc_type == R_386_PC16) {
plt_addr += k * 12 + 20;
// thumb symbol
if (plt_addr & 1) {
plt_addr--;
}
free (REL);
return plt_addr;
} else {
bprintf ("Unknown sparc reloc type %d\n", reloc_type);
}
/* SPARC */
break;
case EM_ARM:
case EM_AARCH64:
plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt");
if (plt_addr == -1) {
free (rela);
return UT32_MAX;
}
switch (reloc_type) {
case R_386_8:
{
plt_addr += k * 12 + 20;
// thumb symbol
if (plt_addr & 1) {
plt_addr--;
}
free (REL);
return plt_addr;
}
break;
case 1026: // arm64 aarch64
plt_sym_addr = plt_addr + k * 16 + 32;
goto done;
default:
bprintf ("Unsupported relocation type for imports %d\n", reloc_type);
break;
}
break;
case EM_386:
case EM_X86_64:
switch (reloc_type) {
case 1: // unknown relocs found in voidlinux for x86-64
// break;
case R_386_GLOB_DAT:
case R_386_JMP_SLOT:
{
ut8 buf[8];
if (of + sizeof(Elf_(Addr)) < bin->size) {
// ONLY FOR X86
if (of > bin->size || of + sizeof (Elf_(Addr)) > bin->size) {
goto out;
}
len = r_buf_read_at (bin->b, of, buf, sizeof (Elf_(Addr)));
if (len < -1) {
goto out;
}
plt_sym_addr = sizeof (Elf_(Addr)) == 4
? r_read_le32 (buf)
: r_read_le64 (buf);
if (!plt_sym_addr) {
//XXX HACK ALERT!!!! full relro?? try to fix it
//will there always be .plt.got, what would happen if is .got.plt?
RBinElfSection *s = get_section_by_name (bin, ".plt.got");
if (Elf_(r_bin_elf_has_relro)(bin) < R_ELF_PART_RELRO || !s) {
goto done;
}
plt_addr = s->offset;
of = of + got_addr - got_offset;
while (plt_addr + 2 + 4 < s->offset + s->size) {
/*we try to locate the plt entry that correspond with the relocation
since got does not point back to .plt. In this case it has the following
form
ff253a152000 JMP QWORD [RIP + 0x20153A]
6690 NOP
----
ff25ec9f0408 JMP DWORD [reloc.puts_236]
plt_addr + 2 to remove jmp opcode and get the imm reading 4
and if RIP (plt_addr + 6) + imm == rel->offset
return plt_addr, that will be our sym addr
perhaps this hack doesn't work on 32 bits
*/
len = r_buf_read_at (bin->b, plt_addr + 2, buf, 4);
if (len < -1) {
goto out;
}
plt_sym_addr = sizeof (Elf_(Addr)) == 4
? r_read_le32 (buf)
: r_read_le64 (buf);
//relative address
if ((plt_addr + 6 + Elf_(r_bin_elf_v2p) (bin, plt_sym_addr)) == of) {
plt_sym_addr = plt_addr;
goto done;
} else if (plt_sym_addr == of) {
plt_sym_addr = plt_addr;
goto done;
}
plt_addr += 8;
}
} else {
plt_sym_addr -= 6;
}
goto done;
}
break;
}
default:
bprintf ("Unsupported relocation type for imports %d\n", reloc_type);
free (REL);
return of;
break;
}
break;
case 8:
// MIPS32 BIG ENDIAN relocs
{
RBinElfSection *s = get_section_by_name (bin, ".rela.plt");
if (s) {
ut8 buf[1024];
const ut8 *base;
plt_addr = s->rva + s->size;
len = r_buf_read_at (bin->b, s->offset + s->size, buf, sizeof (buf));
if (len != sizeof (buf)) {
// oops
}
base = r_mem_mem_aligned (buf, sizeof (buf), (const ut8*)"\x3c\x0f\x00", 3, 4);
if (base) {
plt_addr += (int)(size_t)(base - buf);
} else {
plt_addr += 108 + 8; // HARDCODED HACK
}
plt_addr += k * 16;
free (REL);
return plt_addr;
}
}
break;
default:
bprintf ("Unsupported relocs type %d for arch %d\n",
reloc_type, bin->ehdr.e_machine);
break;
}
}
}
done:
free (REL);
return plt_sym_addr;
out:
free (REL);
return -1;
}
int Elf_(r_bin_elf_has_nx)(ELFOBJ *bin) {
int i;
if (bin && bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_GNU_STACK) {
return (!(bin->phdr[i].p_flags & 1))? 1: 0;
}
}
}
return 0;
}
int Elf_(r_bin_elf_has_relro)(ELFOBJ *bin) {
int i;
bool haveBindNow = false;
bool haveGnuRelro = false;
if (bin && bin->dyn_buf) {
for (i = 0; i < bin->dyn_entries; i++) {
switch (bin->dyn_buf[i].d_tag) {
case DT_BIND_NOW:
haveBindNow = true;
break;
case DT_FLAGS:
for (i++; i < bin->dyn_entries ; i++) {
ut32 dTag = bin->dyn_buf[i].d_tag;
if (!dTag) {
break;
}
switch (dTag) {
case DT_FLAGS_1:
if (bin->dyn_buf[i].d_un.d_val & DF_1_NOW) {
haveBindNow = true;
break;
}
}
}
break;
}
}
}
if (bin && bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_GNU_RELRO) {
haveGnuRelro = true;
break;
}
}
}
if (haveGnuRelro) {
if (haveBindNow) {
return R_ELF_FULL_RELRO;
}
return R_ELF_PART_RELRO;
}
return R_ELF_NO_RELRO;
}
/*
To compute the base address, one determines the memory
address associated with the lowest p_vaddr value for a
PT_LOAD segment. One then obtains the base address by
truncating the memory address to the nearest multiple
of the maximum page size
*/
ut64 Elf_(r_bin_elf_get_baddr)(ELFOBJ *bin) {
int i;
ut64 tmp, base = UT64_MAX;
if (!bin) {
return 0;
}
if (bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_LOAD) {
tmp = (ut64)bin->phdr[i].p_vaddr & ELF_PAGE_MASK;
tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE));
if (tmp < base) {
base = tmp;
}
}
}
}
if (base == UT64_MAX && bin->ehdr.e_type == ET_REL) {
//we return our own base address for ET_REL type
//we act as a loader for ELF
return 0x08000000;
}
return base == UT64_MAX ? 0 : base;
}
ut64 Elf_(r_bin_elf_get_boffset)(ELFOBJ *bin) {
int i;
ut64 tmp, base = UT64_MAX;
if (bin && bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_LOAD) {
tmp = (ut64)bin->phdr[i].p_offset & ELF_PAGE_MASK;
tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE));
if (tmp < base) {
base = tmp;
}
}
}
}
return base == UT64_MAX ? 0 : base;
}
ut64 Elf_(r_bin_elf_get_init_offset)(ELFOBJ *bin) {
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
ut8 buf[512];
if (!bin) {
return 0LL;
}
if (r_buf_read_at (bin->b, entry + 16, buf, sizeof (buf)) < 1) {
bprintf ("Warning: read (init_offset)\n");
return 0;
}
if (buf[0] == 0x68) { // push // x86 only
ut64 addr;
memmove (buf, buf+1, 4);
addr = (ut64)r_read_le32 (buf);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
return 0;
}
ut64 Elf_(r_bin_elf_get_fini_offset)(ELFOBJ *bin) {
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
ut8 buf[512];
if (!bin) {
return 0LL;
}
if (r_buf_read_at (bin->b, entry+11, buf, sizeof (buf)) == -1) {
bprintf ("Warning: read (get_fini)\n");
return 0;
}
if (*buf == 0x68) { // push // x86/32 only
ut64 addr;
memmove (buf, buf+1, 4);
addr = (ut64)r_read_le32 (buf);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
return 0;
}
ut64 Elf_(r_bin_elf_get_entry_offset)(ELFOBJ *bin) {
ut64 entry;
if (!bin) {
return 0LL;
}
entry = bin->ehdr.e_entry;
if (!entry) {
entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init.text");
if (entry != UT64_MAX) {
return entry;
}
entry = Elf_(r_bin_elf_get_section_offset)(bin, ".text");
if (entry != UT64_MAX) {
return entry;
}
entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init");
if (entry != UT64_MAX) {
return entry;
}
if (entry == UT64_MAX) {
return 0;
}
}
return Elf_(r_bin_elf_v2p) (bin, entry);
}
static ut64 getmainsymbol(ELFOBJ *bin) {
struct r_bin_elf_symbol_t *symbol;
int i;
if (!(symbol = Elf_(r_bin_elf_get_symbols) (bin))) {
return UT64_MAX;
}
for (i = 0; !symbol[i].last; i++) {
if (!strcmp (symbol[i].name, "main")) {
ut64 paddr = symbol[i].offset;
return Elf_(r_bin_elf_p2v) (bin, paddr);
}
}
return UT64_MAX;
}
ut64 Elf_(r_bin_elf_get_main_offset)(ELFOBJ *bin) {
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
ut8 buf[512];
if (!bin) {
return 0LL;
}
if (entry > bin->size || (entry + sizeof (buf)) > bin->size) {
return 0;
}
if (r_buf_read_at (bin->b, entry, buf, sizeof (buf)) < 1) {
bprintf ("Warning: read (main)\n");
return 0;
}
// ARM64
if (buf[0x18+3] == 0x58 && buf[0x2f] == 0x00) {
ut32 entry_vaddr = Elf_(r_bin_elf_p2v) (bin, entry);
ut32 main_addr = r_read_le32 (&buf[0x30]);
if ((main_addr >> 16) == (entry_vaddr >> 16)) {
return Elf_(r_bin_elf_v2p) (bin, main_addr);
}
}
// TODO: Use arch to identify arch before memcmp's
// ARM
ut64 text = Elf_(r_bin_elf_get_section_offset)(bin, ".text");
ut64 text_end = text + bin->size;
// ARM-Thumb-Linux
if (entry & 1 && !memcmp (buf, "\xf0\x00\x0b\x4f\xf0\x00", 6)) {
ut32 * ptr = (ut32*)(buf+40-1);
if (*ptr &1) {
return Elf_(r_bin_elf_v2p) (bin, *ptr -1);
}
}
if (!memcmp (buf, "\x00\xb0\xa0\xe3\x00\xe0\xa0\xe3", 8)) {
// endian stuff here
ut32 *addr = (ut32*)(buf+0x34);
/*
0x00012000 00b0a0e3 mov fp, 0
0x00012004 00e0a0e3 mov lr, 0
*/
if (*addr > text && *addr < (text_end)) {
return Elf_(r_bin_elf_v2p) (bin, *addr);
}
}
// MIPS
/* get .got, calculate offset of main symbol */
if (!memcmp (buf, "\x21\x00\xe0\x03\x01\x00\x11\x04", 8)) {
/*
assuming the startup code looks like
got = gp-0x7ff0
got[index__libc_start_main] ( got[index_main] );
looking for the instruction generating the first argument to find main
lw a0, offset(gp)
*/
ut64 got_offset;
if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) != -1 ||
(got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) != -1)
{
const ut64 gp = got_offset + 0x7ff0;
unsigned i;
for (i = 0; i < sizeof(buf) / sizeof(buf[0]); i += 4) {
const ut32 instr = r_read_le32 (&buf[i]);
if ((instr & 0xffff0000) == 0x8f840000) { // lw a0, offset(gp)
const short delta = instr & 0x0000ffff;
r_buf_read_at (bin->b, /* got_entry_offset = */ gp + delta, buf, 4);
return Elf_(r_bin_elf_v2p) (bin, r_read_le32 (&buf[0]));
}
}
}
return 0;
}
// ARM
if (!memcmp (buf, "\x24\xc0\x9f\xe5\x00\xb0\xa0\xe3", 8)) {
ut64 addr = r_read_le32 (&buf[48]);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
// X86-CGC
if (buf[0] == 0xe8 && !memcmp (buf + 5, "\x50\xe8\x00\x00\x00\x00\xb8\x01\x00\x00\x00\x53", 12)) {
size_t SIZEOF_CALL = 5;
ut64 rel_addr = (ut64)((int)(buf[1] + (buf[2] << 8) + (buf[3] << 16) + (buf[4] << 24)));
ut64 addr = Elf_(r_bin_elf_p2v)(bin, entry + SIZEOF_CALL);
addr += rel_addr;
return Elf_(r_bin_elf_v2p) (bin, addr);
}
// X86-PIE
if (buf[0x00] == 0x48 && buf[0x1e] == 0x8d && buf[0x11] == 0xe8) {
ut32 *pmain = (ut32*)(buf + 0x30);
ut64 vmain = Elf_(r_bin_elf_p2v) (bin, (ut64)*pmain);
ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry);
if (vmain >> 16 == ventry >> 16) {
return (ut64)vmain;
}
}
// X86-PIE
if (buf[0x1d] == 0x48 && buf[0x1e] == 0x8b) {
if (!memcmp (buf, "\x31\xed\x49\x89", 4)) {// linux
ut64 maddr, baddr;
ut8 n32s[sizeof (ut32)] = {0};
maddr = entry + 0x24 + r_read_le32 (buf + 0x20);
if (r_buf_read_at (bin->b, maddr, n32s, sizeof (ut32)) == -1) {
bprintf ("Warning: read (maddr) 2\n");
return 0;
}
maddr = (ut64)r_read_le32 (&n32s[0]);
baddr = (bin->ehdr.e_entry >> 16) << 16;
if (bin->phdr) {
baddr = Elf_(r_bin_elf_get_baddr) (bin);
}
maddr += baddr;
return maddr;
}
}
// X86-NONPIE
#if R_BIN_ELF64
if (!memcmp (buf, "\x49\x89\xd9", 3) && buf[156] == 0xe8) { // openbsd
return r_read_le32 (&buf[157]) + entry + 156 + 5;
}
if (!memcmp (buf+29, "\x48\xc7\xc7", 3)) { // linux
ut64 addr = (ut64)r_read_le32 (&buf[29 + 3]);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
#else
if (buf[23] == '\x68') {
ut64 addr = (ut64)r_read_le32 (&buf[23 + 1]);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
#endif
/* linux64 pie main -- probably buggy in some cases */
if (buf[29] == 0x48 && buf[30] == 0x8d) { // lea rdi, qword [rip-0x21c4]
ut8 *p = buf + 32;
st32 maindelta = (st32)r_read_le32 (p);
ut64 vmain = (ut64)(entry + 29 + maindelta) + 7;
ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry);
if (vmain>>16 == ventry>>16) {
return (ut64)vmain;
}
}
/* find sym.main if possible */
{
ut64 m = getmainsymbol (bin);
if (m != UT64_MAX) return m;
}
return UT64_MAX;
}
int Elf_(r_bin_elf_get_stripped)(ELFOBJ *bin) {
int i;
if (!bin->shdr) {
return false;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
if (bin->shdr[i].sh_type == SHT_SYMTAB) {
return false;
}
}
return true;
}
char *Elf_(r_bin_elf_intrp)(ELFOBJ *bin) {
int i;
if (!bin || !bin->phdr) {
return NULL;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_INTERP) {
char *str = NULL;
ut64 addr = bin->phdr[i].p_offset;
int sz = bin->phdr[i].p_memsz;
sdb_num_set (bin->kv, "elf_header.intrp_addr", addr, 0);
sdb_num_set (bin->kv, "elf_header.intrp_size", sz, 0);
if (sz < 1) {
return NULL;
}
str = malloc (sz + 1);
if (!str) {
return NULL;
}
if (r_buf_read_at (bin->b, addr, (ut8*)str, sz) < 1) {
bprintf ("Warning: read (main)\n");
return 0;
}
str[sz] = 0;
sdb_set (bin->kv, "elf_header.intrp", str, 0);
return str;
}
}
return NULL;
}
int Elf_(r_bin_elf_get_static)(ELFOBJ *bin) {
int i;
if (!bin->phdr) {
return false;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_INTERP) {
return false;
}
}
return true;
}
char* Elf_(r_bin_elf_get_data_encoding)(ELFOBJ *bin) {
switch (bin->ehdr.e_ident[EI_DATA]) {
case ELFDATANONE: return strdup ("none");
case ELFDATA2LSB: return strdup ("2's complement, little endian");
case ELFDATA2MSB: return strdup ("2's complement, big endian");
default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_DATA]);
}
}
int Elf_(r_bin_elf_has_va)(ELFOBJ *bin) {
return true;
}
char* Elf_(r_bin_elf_get_arch)(ELFOBJ *bin) {
switch (bin->ehdr.e_machine) {
case EM_ARC:
case EM_ARC_A5:
return strdup ("arc");
case EM_AVR: return strdup ("avr");
case EM_CRIS: return strdup ("cris");
case EM_68K: return strdup ("m68k");
case EM_MIPS:
case EM_MIPS_RS3_LE:
case EM_MIPS_X:
return strdup ("mips");
case EM_MCST_ELBRUS:
return strdup ("elbrus");
case EM_TRICORE:
return strdup ("tricore");
case EM_ARM:
case EM_AARCH64:
return strdup ("arm");
case EM_HEXAGON:
return strdup ("hexagon");
case EM_BLACKFIN:
return strdup ("blackfin");
case EM_SPARC:
case EM_SPARC32PLUS:
case EM_SPARCV9:
return strdup ("sparc");
case EM_PPC:
case EM_PPC64:
return strdup ("ppc");
case EM_PARISC:
return strdup ("hppa");
case EM_PROPELLER:
return strdup ("propeller");
case EM_MICROBLAZE:
return strdup ("microblaze.gnu");
case EM_RISCV:
return strdup ("riscv");
case EM_VAX:
return strdup ("vax");
case EM_XTENSA:
return strdup ("xtensa");
case EM_LANAI:
return strdup ("lanai");
case EM_VIDEOCORE3:
case EM_VIDEOCORE4:
return strdup ("vc4");
case EM_SH:
return strdup ("sh");
case EM_V850:
return strdup ("v850");
case EM_IA_64:
return strdup("ia64");
default: return strdup ("x86");
}
}
char* Elf_(r_bin_elf_get_machine_name)(ELFOBJ *bin) {
switch (bin->ehdr.e_machine) {
case EM_NONE: return strdup ("No machine");
case EM_M32: return strdup ("AT&T WE 32100");
case EM_SPARC: return strdup ("SUN SPARC");
case EM_386: return strdup ("Intel 80386");
case EM_68K: return strdup ("Motorola m68k family");
case EM_88K: return strdup ("Motorola m88k family");
case EM_860: return strdup ("Intel 80860");
case EM_MIPS: return strdup ("MIPS R3000");
case EM_S370: return strdup ("IBM System/370");
case EM_MIPS_RS3_LE: return strdup ("MIPS R3000 little-endian");
case EM_PARISC: return strdup ("HPPA");
case EM_VPP500: return strdup ("Fujitsu VPP500");
case EM_SPARC32PLUS: return strdup ("Sun's \"v8plus\"");
case EM_960: return strdup ("Intel 80960");
case EM_PPC: return strdup ("PowerPC");
case EM_PPC64: return strdup ("PowerPC 64-bit");
case EM_S390: return strdup ("IBM S390");
case EM_V800: return strdup ("NEC V800 series");
case EM_FR20: return strdup ("Fujitsu FR20");
case EM_RH32: return strdup ("TRW RH-32");
case EM_RCE: return strdup ("Motorola RCE");
case EM_ARM: return strdup ("ARM");
case EM_BLACKFIN: return strdup ("Analog Devices Blackfin");
case EM_FAKE_ALPHA: return strdup ("Digital Alpha");
case EM_SH: return strdup ("Hitachi SH");
case EM_SPARCV9: return strdup ("SPARC v9 64-bit");
case EM_TRICORE: return strdup ("Siemens Tricore");
case EM_ARC: return strdup ("Argonaut RISC Core");
case EM_H8_300: return strdup ("Hitachi H8/300");
case EM_H8_300H: return strdup ("Hitachi H8/300H");
case EM_H8S: return strdup ("Hitachi H8S");
case EM_H8_500: return strdup ("Hitachi H8/500");
case EM_IA_64: return strdup ("Intel Merced");
case EM_MIPS_X: return strdup ("Stanford MIPS-X");
case EM_COLDFIRE: return strdup ("Motorola Coldfire");
case EM_68HC12: return strdup ("Motorola M68HC12");
case EM_MMA: return strdup ("Fujitsu MMA Multimedia Accelerator");
case EM_PCP: return strdup ("Siemens PCP");
case EM_NCPU: return strdup ("Sony nCPU embeeded RISC");
case EM_NDR1: return strdup ("Denso NDR1 microprocessor");
case EM_STARCORE: return strdup ("Motorola Start*Core processor");
case EM_ME16: return strdup ("Toyota ME16 processor");
case EM_ST100: return strdup ("STMicroelectronic ST100 processor");
case EM_TINYJ: return strdup ("Advanced Logic Corp. Tinyj emb.fam");
case EM_X86_64: return strdup ("AMD x86-64 architecture");
case EM_LANAI: return strdup ("32bit LANAI architecture");
case EM_PDSP: return strdup ("Sony DSP Processor");
case EM_FX66: return strdup ("Siemens FX66 microcontroller");
case EM_ST9PLUS: return strdup ("STMicroelectronics ST9+ 8/16 mc");
case EM_ST7: return strdup ("STmicroelectronics ST7 8 bit mc");
case EM_68HC16: return strdup ("Motorola MC68HC16 microcontroller");
case EM_68HC11: return strdup ("Motorola MC68HC11 microcontroller");
case EM_68HC08: return strdup ("Motorola MC68HC08 microcontroller");
case EM_68HC05: return strdup ("Motorola MC68HC05 microcontroller");
case EM_SVX: return strdup ("Silicon Graphics SVx");
case EM_ST19: return strdup ("STMicroelectronics ST19 8 bit mc");
case EM_VAX: return strdup ("Digital VAX");
case EM_CRIS: return strdup ("Axis Communications 32-bit embedded processor");
case EM_JAVELIN: return strdup ("Infineon Technologies 32-bit embedded processor");
case EM_FIREPATH: return strdup ("Element 14 64-bit DSP Processor");
case EM_ZSP: return strdup ("LSI Logic 16-bit DSP Processor");
case EM_MMIX: return strdup ("Donald Knuth's educational 64-bit processor");
case EM_HUANY: return strdup ("Harvard University machine-independent object files");
case EM_PRISM: return strdup ("SiTera Prism");
case EM_AVR: return strdup ("Atmel AVR 8-bit microcontroller");
case EM_FR30: return strdup ("Fujitsu FR30");
case EM_D10V: return strdup ("Mitsubishi D10V");
case EM_D30V: return strdup ("Mitsubishi D30V");
case EM_V850: return strdup ("NEC v850");
case EM_M32R: return strdup ("Mitsubishi M32R");
case EM_MN10300: return strdup ("Matsushita MN10300");
case EM_MN10200: return strdup ("Matsushita MN10200");
case EM_PJ: return strdup ("picoJava");
case EM_OPENRISC: return strdup ("OpenRISC 32-bit embedded processor");
case EM_ARC_A5: return strdup ("ARC Cores Tangent-A5");
case EM_XTENSA: return strdup ("Tensilica Xtensa Architecture");
case EM_AARCH64: return strdup ("ARM aarch64");
case EM_PROPELLER: return strdup ("Parallax Propeller");
case EM_MICROBLAZE: return strdup ("Xilinx MicroBlaze");
case EM_RISCV: return strdup ("RISC V");
case EM_VIDEOCORE3: return strdup ("VideoCore III");
case EM_VIDEOCORE4: return strdup ("VideoCore IV");
default: return r_str_newf ("<unknown>: 0x%x", bin->ehdr.e_machine);
}
}
char* Elf_(r_bin_elf_get_file_type)(ELFOBJ *bin) {
ut32 e_type;
if (!bin) {
return NULL;
}
e_type = (ut32)bin->ehdr.e_type; // cast to avoid warn in iphone-gcc, must be ut16
switch (e_type) {
case ET_NONE: return strdup ("NONE (None)");
case ET_REL: return strdup ("REL (Relocatable file)");
case ET_EXEC: return strdup ("EXEC (Executable file)");
case ET_DYN: return strdup ("DYN (Shared object file)");
case ET_CORE: return strdup ("CORE (Core file)");
}
if ((e_type >= ET_LOPROC) && (e_type <= ET_HIPROC)) {
return r_str_newf ("Processor Specific: %x", e_type);
}
if ((e_type >= ET_LOOS) && (e_type <= ET_HIOS)) {
return r_str_newf ("OS Specific: %x", e_type);
}
return r_str_newf ("<unknown>: %x", e_type);
}
char* Elf_(r_bin_elf_get_elf_class)(ELFOBJ *bin) {
switch (bin->ehdr.e_ident[EI_CLASS]) {
case ELFCLASSNONE: return strdup ("none");
case ELFCLASS32: return strdup ("ELF32");
case ELFCLASS64: return strdup ("ELF64");
default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_CLASS]);
}
}
int Elf_(r_bin_elf_get_bits)(ELFOBJ *bin) {
/* Hack for ARCompact */
if (bin->ehdr.e_machine == EM_ARC_A5) {
return 16;
}
/* Hack for Ps2 */
if (bin->phdr && bin->ehdr.e_machine == EM_MIPS) {
const ut32 mipsType = bin->ehdr.e_flags & EF_MIPS_ARCH;
if (bin->ehdr.e_type == ET_EXEC) {
int i;
bool haveInterp = false;
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_INTERP) {
haveInterp = true;
}
}
if (!haveInterp && mipsType == EF_MIPS_ARCH_3) {
// Playstation2 Hack
return 64;
}
}
// TODO: show this specific asm.cpu somewhere in bininfo (mips1, mips2, mips3, mips32r2, ...)
switch (mipsType) {
case EF_MIPS_ARCH_1:
case EF_MIPS_ARCH_2:
case EF_MIPS_ARCH_3:
case EF_MIPS_ARCH_4:
case EF_MIPS_ARCH_5:
case EF_MIPS_ARCH_32:
return 32;
case EF_MIPS_ARCH_64:
return 64;
case EF_MIPS_ARCH_32R2:
return 32;
case EF_MIPS_ARCH_64R2:
return 64;
break;
}
return 32;
}
/* Hack for Thumb */
if (bin->ehdr.e_machine == EM_ARM) {
if (bin->ehdr.e_type != ET_EXEC) {
struct r_bin_elf_symbol_t *symbol;
if ((symbol = Elf_(r_bin_elf_get_symbols) (bin))) {
int i = 0;
for (i = 0; !symbol[i].last; i++) {
ut64 paddr = symbol[i].offset;
if (paddr & 1) {
return 16;
}
}
}
}
{
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
if (entry & 1) {
return 16;
}
}
}
switch (bin->ehdr.e_ident[EI_CLASS]) {
case ELFCLASS32: return 32;
case ELFCLASS64: return 64;
case ELFCLASSNONE:
default: return 32; // defaults
}
}
static inline int noodle(ELFOBJ *bin, const char *s) {
const ut8 *p = bin->b->buf;
if (bin->b->length > 64) {
p += bin->b->length - 64;
} else {
return 0;
}
return r_mem_mem (p, 64, (const ut8 *)s, strlen (s)) != NULL;
}
static inline int needle(ELFOBJ *bin, const char *s) {
if (bin->shstrtab) {
ut32 len = bin->shstrtab_size;
if (len > 4096) {
len = 4096; // avoid slow loading .. can be buggy?
}
return r_mem_mem ((const ut8*)bin->shstrtab, len,
(const ut8*)s, strlen (s)) != NULL;
}
return 0;
}
// TODO: must return const char * all those strings must be const char os[LINUX] or so
char* Elf_(r_bin_elf_get_osabi_name)(ELFOBJ *bin) {
switch (bin->ehdr.e_ident[EI_OSABI]) {
case ELFOSABI_LINUX: return strdup("linux");
case ELFOSABI_SOLARIS: return strdup("solaris");
case ELFOSABI_FREEBSD: return strdup("freebsd");
case ELFOSABI_HPUX: return strdup("hpux");
}
/* Hack to identify OS */
if (needle (bin, "openbsd")) return strdup ("openbsd");
if (needle (bin, "netbsd")) return strdup ("netbsd");
if (needle (bin, "freebsd")) return strdup ("freebsd");
if (noodle (bin, "BEOS:APP_VERSION")) return strdup ("beos");
if (needle (bin, "GNU")) return strdup ("linux");
return strdup ("linux");
}
ut8 *Elf_(r_bin_elf_grab_regstate)(ELFOBJ *bin, int *len) {
if (bin->phdr) {
int i;
int num = bin->ehdr.e_phnum;
for (i = 0; i < num; i++) {
if (bin->phdr[i].p_type != PT_NOTE) {
continue;
}
int bits = Elf_(r_bin_elf_get_bits)(bin);
int regdelta = (bits == 64)? 0x84: 0x40; // x64 vs x32
int regsize = 160; // for x86-64
ut8 *buf = malloc (regsize);
if (r_buf_read_at (bin->b, bin->phdr[i].p_offset + regdelta, buf, regsize) != regsize) {
free (buf);
bprintf ("Cannot read register state from CORE file\n");
return NULL;
}
if (len) {
*len = regsize;
}
return buf;
}
}
bprintf ("Cannot find NOTE section\n");
return NULL;
}
int Elf_(r_bin_elf_is_big_endian)(ELFOBJ *bin) {
return (bin->ehdr.e_ident[EI_DATA] == ELFDATA2MSB);
}
/* XXX Init dt_strtab? */
char *Elf_(r_bin_elf_get_rpath)(ELFOBJ *bin) {
char *ret = NULL;
int j;
if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab) {
return NULL;
}
for (j = 0; j< bin->dyn_entries; j++) {
if (bin->dyn_buf[j].d_tag == DT_RPATH || bin->dyn_buf[j].d_tag == DT_RUNPATH) {
if (!(ret = calloc (1, ELF_STRING_LENGTH))) {
perror ("malloc (rpath)");
return NULL;
}
if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) {
free (ret);
return NULL;
}
strncpy (ret, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH);
ret[ELF_STRING_LENGTH - 1] = '\0';
break;
}
}
return ret;
}
static size_t get_relocs_num(ELFOBJ *bin) {
size_t i, size, ret = 0;
/* we need to be careful here, in malformed files the section size might
* not be a multiple of a Rel/Rela size; round up so we allocate enough
* space.
*/
#define NUMENTRIES_ROUNDUP(sectionsize, entrysize) (((sectionsize)+(entrysize)-1)/(entrysize))
if (!bin->g_sections) {
return 0;
}
size = bin->is_rela == DT_REL ? sizeof (Elf_(Rel)) : sizeof (Elf_(Rela));
for (i = 0; !bin->g_sections[i].last; i++) {
if (!strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."))) {
if (!bin->is_rela) {
size = sizeof (Elf_(Rela));
}
ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size);
} else if (!strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel."))){
if (!bin->is_rela) {
size = sizeof (Elf_(Rel));
}
ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size);
}
}
return ret;
#undef NUMENTRIES_ROUNDUP
}
static int read_reloc(ELFOBJ *bin, RBinElfReloc *r, int is_rela, ut64 offset) {
ut8 *buf = bin->b->buf;
int j = 0;
if (offset + sizeof (Elf_ (Rela)) >
bin->size || offset + sizeof (Elf_(Rela)) < offset) {
return -1;
}
if (is_rela == DT_RELA) {
Elf_(Rela) rela;
#if R_BIN_ELF64
rela.r_offset = READ64 (buf + offset, j)
rela.r_info = READ64 (buf + offset, j)
rela.r_addend = READ64 (buf + offset, j)
#else
rela.r_offset = READ32 (buf + offset, j)
rela.r_info = READ32 (buf + offset, j)
rela.r_addend = READ32 (buf + offset, j)
#endif
r->is_rela = is_rela;
r->offset = rela.r_offset;
r->type = ELF_R_TYPE (rela.r_info);
r->sym = ELF_R_SYM (rela.r_info);
r->last = 0;
r->addend = rela.r_addend;
return sizeof (Elf_(Rela));
} else {
Elf_(Rel) rel;
#if R_BIN_ELF64
rel.r_offset = READ64 (buf + offset, j)
rel.r_info = READ64 (buf + offset, j)
#else
rel.r_offset = READ32 (buf + offset, j)
rel.r_info = READ32 (buf + offset, j)
#endif
r->is_rela = is_rela;
r->offset = rel.r_offset;
r->type = ELF_R_TYPE (rel.r_info);
r->sym = ELF_R_SYM (rel.r_info);
r->last = 0;
return sizeof (Elf_(Rel));
}
}
RBinElfReloc* Elf_(r_bin_elf_get_relocs)(ELFOBJ *bin) {
int res, rel, rela, i, j;
size_t reloc_num = 0;
RBinElfReloc *ret = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
reloc_num = get_relocs_num (bin);
if (!reloc_num) {
return NULL;
}
bin->reloc_num = reloc_num;
ret = (RBinElfReloc*)calloc ((size_t)reloc_num + 1, sizeof(RBinElfReloc));
if (!ret) {
return NULL;
}
#if DEAD_CODE
ut64 section_text_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".text");
if (section_text_offset == -1) {
section_text_offset = 0;
}
#endif
for (i = 0, rel = 0; !bin->g_sections[i].last && rel < reloc_num ; i++) {
bool is_rela = 0 == strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."));
bool is_rel = 0 == strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel."));
if (!is_rela && !is_rel) {
continue;
}
for (j = 0; j < bin->g_sections[i].size; j += res) {
if (bin->g_sections[i].size > bin->size) {
break;
}
if (bin->g_sections[i].offset > bin->size) {
break;
}
if (rel >= reloc_num) {
bprintf ("Internal error: ELF relocation buffer too small,"
"please file a bug report.");
break;
}
if (!bin->is_rela) {
rela = is_rela? DT_RELA : DT_REL;
} else {
rela = bin->is_rela;
}
res = read_reloc (bin, &ret[rel], rela, bin->g_sections[i].offset + j);
if (j + res > bin->g_sections[i].size) {
bprintf ("Warning: malformed file, relocation entry #%u is partially beyond the end of section %u.\n", rel, i);
}
if (bin->ehdr.e_type == ET_REL) {
if (bin->g_sections[i].info < bin->ehdr.e_shnum && bin->shdr) {
ret[rel].rva = bin->shdr[bin->g_sections[i].info].sh_offset + ret[rel].offset;
ret[rel].rva = Elf_(r_bin_elf_p2v) (bin, ret[rel].rva);
} else {
ret[rel].rva = ret[rel].offset;
}
} else {
ret[rel].rva = ret[rel].offset;
ret[rel].offset = Elf_(r_bin_elf_v2p) (bin, ret[rel].offset);
}
ret[rel].last = 0;
if (res < 0) {
break;
}
rel++;
}
}
ret[reloc_num].last = 1;
return ret;
}
RBinElfLib* Elf_(r_bin_elf_get_libs)(ELFOBJ *bin) {
RBinElfLib *ret = NULL;
int j, k;
if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab || *(bin->strtab+1) == '0') {
return NULL;
}
for (j = 0, k = 0; j < bin->dyn_entries; j++)
if (bin->dyn_buf[j].d_tag == DT_NEEDED) {
RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib));
if (!r) {
perror ("realloc (libs)");
free (ret);
return NULL;
}
ret = r;
if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) {
free (ret);
return NULL;
}
strncpy (ret[k].name, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH);
ret[k].name[ELF_STRING_LENGTH - 1] = '\0';
ret[k].last = 0;
if (ret[k].name[0]) {
k++;
}
}
RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib));
if (!r) {
perror ("realloc (libs)");
free (ret);
return NULL;
}
ret = r;
ret[k].last = 1;
return ret;
}
static RBinElfSection* get_sections_from_phdr(ELFOBJ *bin) {
RBinElfSection *ret;
int i, num_sections = 0;
ut64 reldyn = 0, relava = 0, pltgotva = 0, relva = 0;
ut64 reldynsz = 0, relasz = 0, pltgotsz = 0;
if (!bin || !bin->phdr || !bin->ehdr.e_phnum)
return NULL;
for (i = 0; i < bin->dyn_entries; i++) {
switch (bin->dyn_buf[i].d_tag) {
case DT_REL:
reldyn = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
case DT_RELA:
relva = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
case DT_RELSZ:
reldynsz = bin->dyn_buf[i].d_un.d_val;
break;
case DT_RELASZ:
relasz = bin->dyn_buf[i].d_un.d_val;
break;
case DT_PLTGOT:
pltgotva = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
case DT_PLTRELSZ:
pltgotsz = bin->dyn_buf[i].d_un.d_val;
break;
case DT_JMPREL:
relava = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
default: break;
}
}
ret = calloc (num_sections + 1, sizeof(RBinElfSection));
if (!ret) {
return NULL;
}
i = 0;
if (reldyn) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, reldyn);
ret[i].rva = reldyn;
ret[i].size = reldynsz;
strcpy (ret[i].name, ".rel.dyn");
ret[i].last = 0;
i++;
}
if (relava) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relava);
ret[i].rva = relava;
ret[i].size = pltgotsz;
strcpy (ret[i].name, ".rela.plt");
ret[i].last = 0;
i++;
}
if (relva) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relva);
ret[i].rva = relva;
ret[i].size = relasz;
strcpy (ret[i].name, ".rel.plt");
ret[i].last = 0;
i++;
}
if (pltgotva) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, pltgotva);
ret[i].rva = pltgotva;
ret[i].size = pltgotsz;
strcpy (ret[i].name, ".got.plt");
ret[i].last = 0;
i++;
}
ret[i].last = 1;
return ret;
}
RBinElfSection* Elf_(r_bin_elf_get_sections)(ELFOBJ *bin) {
RBinElfSection *ret = NULL;
char unknown_s[20], invalid_s[20];
int i, nidx, unknown_c=0, invalid_c=0;
if (!bin) {
return NULL;
}
if (bin->g_sections) {
return bin->g_sections;
}
if (!bin->shdr) {
//we don't give up search in phdr section
return get_sections_from_phdr (bin);
}
if (!(ret = calloc ((bin->ehdr.e_shnum + 1), sizeof (RBinElfSection)))) {
return NULL;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
ret[i].offset = bin->shdr[i].sh_offset;
ret[i].size = bin->shdr[i].sh_size;
ret[i].align = bin->shdr[i].sh_addralign;
ret[i].flags = bin->shdr[i].sh_flags;
ret[i].link = bin->shdr[i].sh_link;
ret[i].info = bin->shdr[i].sh_info;
ret[i].type = bin->shdr[i].sh_type;
if (bin->ehdr.e_type == ET_REL) {
ret[i].rva = bin->baddr + bin->shdr[i].sh_offset;
} else {
ret[i].rva = bin->shdr[i].sh_addr;
}
nidx = bin->shdr[i].sh_name;
#define SHNAME (int)bin->shdr[i].sh_name
#define SHNLEN ELF_STRING_LENGTH - 4
#define SHSIZE (int)bin->shstrtab_size
if (nidx < 0 || !bin->shstrtab_section || !bin->shstrtab_size || nidx > bin->shstrtab_size) {
snprintf (invalid_s, sizeof (invalid_s) - 4, "invalid%d", invalid_c);
strncpy (ret[i].name, invalid_s, SHNLEN);
invalid_c++;
} else {
if (bin->shstrtab && (SHNAME > 0) && (SHNAME < SHSIZE)) {
strncpy (ret[i].name, &bin->shstrtab[SHNAME], SHNLEN);
} else {
if (bin->shdr[i].sh_type == SHT_NULL) {
//to follow the same behaviour as readelf
strncpy (ret[i].name, "", sizeof (ret[i].name) - 4);
} else {
snprintf (unknown_s, sizeof (unknown_s)-4, "unknown%d", unknown_c);
strncpy (ret[i].name, unknown_s, sizeof (ret[i].name)-4);
unknown_c++;
}
}
}
ret[i].name[ELF_STRING_LENGTH-2] = '\0';
ret[i].last = 0;
}
ret[i].last = 1;
return ret;
}
static void fill_symbol_bind_and_type (struct r_bin_elf_symbol_t *ret, Elf_(Sym) *sym) {
#define s_bind(x) ret->bind = x
#define s_type(x) ret->type = x
switch (ELF_ST_BIND(sym->st_info)) {
case STB_LOCAL: s_bind ("LOCAL"); break;
case STB_GLOBAL: s_bind ("GLOBAL"); break;
case STB_WEAK: s_bind ("WEAK"); break;
case STB_NUM: s_bind ("NUM"); break;
case STB_LOOS: s_bind ("LOOS"); break;
case STB_HIOS: s_bind ("HIOS"); break;
case STB_LOPROC: s_bind ("LOPROC"); break;
case STB_HIPROC: s_bind ("HIPROC"); break;
default: s_bind ("UNKNOWN");
}
switch (ELF_ST_TYPE (sym->st_info)) {
case STT_NOTYPE: s_type ("NOTYPE"); break;
case STT_OBJECT: s_type ("OBJECT"); break;
case STT_FUNC: s_type ("FUNC"); break;
case STT_SECTION: s_type ("SECTION"); break;
case STT_FILE: s_type ("FILE"); break;
case STT_COMMON: s_type ("COMMON"); break;
case STT_TLS: s_type ("TLS"); break;
case STT_NUM: s_type ("NUM"); break;
case STT_LOOS: s_type ("LOOS"); break;
case STT_HIOS: s_type ("HIOS"); break;
case STT_LOPROC: s_type ("LOPROC"); break;
case STT_HIPROC: s_type ("HIPROC"); break;
default: s_type ("UNKNOWN");
}
}
static RBinElfSymbol* get_symbols_from_phdr(ELFOBJ *bin, int type) {
Elf_(Sym) *sym = NULL;
Elf_(Addr) addr_sym_table = 0;
ut8 s[sizeof (Elf_(Sym))] = {0};
RBinElfSymbol *ret = NULL;
int i, j, r, tsize, nsym, ret_ctr;
ut64 toffset = 0, tmp_offset;
ut32 size, sym_size = 0;
if (!bin || !bin->phdr || !bin->ehdr.e_phnum) {
return NULL;
}
for (j = 0; j < bin->dyn_entries; j++) {
switch (bin->dyn_buf[j].d_tag) {
case (DT_SYMTAB):
addr_sym_table = Elf_(r_bin_elf_v2p) (bin, bin->dyn_buf[j].d_un.d_ptr);
break;
case (DT_SYMENT):
sym_size = bin->dyn_buf[j].d_un.d_val;
break;
default:
break;
}
}
if (!addr_sym_table) {
return NULL;
}
if (!sym_size) {
return NULL;
}
//since ELF doesn't specify the symbol table size we may read until the end of the buffer
nsym = (bin->size - addr_sym_table) / sym_size;
if (!UT32_MUL (&size, nsym, sizeof (Elf_ (Sym)))) {
goto beach;
}
if (size < 1) {
goto beach;
}
if (addr_sym_table > bin->size || addr_sym_table + size > bin->size) {
goto beach;
}
if (nsym < 1) {
return NULL;
}
// we reserve room for 4096 and grow as needed.
size_t capacity1 = 4096;
size_t capacity2 = 4096;
sym = (Elf_(Sym)*) calloc (capacity1, sym_size);
ret = (RBinElfSymbol *) calloc (capacity2, sizeof (struct r_bin_elf_symbol_t));
if (!sym || !ret) {
goto beach;
}
for (i = 1, ret_ctr = 0; i < nsym; i++) {
if (i >= capacity1) { // maybe grow
// You take what you want, but you eat what you take.
Elf_(Sym)* temp_sym = (Elf_(Sym)*) realloc(sym, (capacity1 * GROWTH_FACTOR) * sym_size);
if (!temp_sym) {
goto beach;
}
sym = temp_sym;
capacity1 *= GROWTH_FACTOR;
}
if (ret_ctr >= capacity2) { // maybe grow
RBinElfSymbol *temp_ret = realloc (ret, capacity2 * GROWTH_FACTOR * sizeof (struct r_bin_elf_symbol_t));
if (!temp_ret) {
goto beach;
}
ret = temp_ret;
capacity2 *= GROWTH_FACTOR;
}
// read in one entry
r = r_buf_read_at (bin->b, addr_sym_table + i * sizeof (Elf_ (Sym)), s, sizeof (Elf_ (Sym)));
if (r < 1) {
goto beach;
}
int j = 0;
#if R_BIN_ELF64
sym[i].st_name = READ32 (s, j);
sym[i].st_info = READ8 (s, j);
sym[i].st_other = READ8 (s, j);
sym[i].st_shndx = READ16 (s, j);
sym[i].st_value = READ64 (s, j);
sym[i].st_size = READ64 (s, j);
#else
sym[i].st_name = READ32 (s, j);
sym[i].st_value = READ32 (s, j);
sym[i].st_size = READ32 (s, j);
sym[i].st_info = READ8 (s, j);
sym[i].st_other = READ8 (s, j);
sym[i].st_shndx = READ16 (s, j);
#endif
// zero symbol is always empty
// Examine entry and maybe store
if (type == R_BIN_ELF_IMPORTS && sym[i].st_shndx == STN_UNDEF) {
if (sym[i].st_value) {
toffset = sym[i].st_value;
} else if ((toffset = get_import_addr (bin, i)) == -1){
toffset = 0;
}
tsize = 16;
} else if (type == R_BIN_ELF_SYMBOLS &&
sym[i].st_shndx != STN_UNDEF &&
ELF_ST_TYPE (sym[i].st_info) != STT_SECTION &&
ELF_ST_TYPE (sym[i].st_info) != STT_FILE) {
tsize = sym[i].st_size;
toffset = (ut64) sym[i].st_value;
} else {
continue;
}
tmp_offset = Elf_(r_bin_elf_v2p) (bin, toffset);
if (tmp_offset > bin->size) {
goto done;
}
if (sym[i].st_name + 2 > bin->strtab_size) {
// Since we are reading beyond the symbol table what's happening
// is that some entry is trying to dereference the strtab beyond its capacity
// is not a symbol so is the end
goto done;
}
ret[ret_ctr].offset = tmp_offset;
ret[ret_ctr].size = tsize;
{
int rest = ELF_STRING_LENGTH - 1;
int st_name = sym[i].st_name;
int maxsize = R_MIN (bin->size, bin->strtab_size);
if (st_name < 0 || st_name >= maxsize) {
ret[ret_ctr].name[0] = 0;
} else {
const int len = __strnlen (bin->strtab + st_name, rest);
memcpy (ret[ret_ctr].name, &bin->strtab[st_name], len);
}
}
ret[ret_ctr].ordinal = i;
ret[ret_ctr].in_shdr = false;
ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0';
fill_symbol_bind_and_type (&ret[ret_ctr], &sym[i]);
ret[ret_ctr].last = 0;
ret_ctr++;
}
done:
ret[ret_ctr].last = 1;
// Size everything down to only what is used
{
nsym = i > 0 ? i : 1;
Elf_ (Sym) * temp_sym = (Elf_ (Sym)*) realloc (sym, (nsym * GROWTH_FACTOR) * sym_size);
if (!temp_sym) {
goto beach;
}
sym = temp_sym;
}
{
ret_ctr = ret_ctr > 0 ? ret_ctr : 1;
RBinElfSymbol *p = (RBinElfSymbol *) realloc (ret, (ret_ctr + 1) * sizeof (RBinElfSymbol));
if (!p) {
goto beach;
}
ret = p;
}
if (type == R_BIN_ELF_IMPORTS && !bin->imports_by_ord_size) {
bin->imports_by_ord_size = ret_ctr + 1;
if (ret_ctr > 0) {
bin->imports_by_ord = (RBinImport * *) calloc (ret_ctr + 1, sizeof (RBinImport*));
} else {
bin->imports_by_ord = NULL;
}
} else if (type == R_BIN_ELF_SYMBOLS && !bin->symbols_by_ord_size && ret_ctr) {
bin->symbols_by_ord_size = ret_ctr + 1;
if (ret_ctr > 0) {
bin->symbols_by_ord = (RBinSymbol * *) calloc (ret_ctr + 1, sizeof (RBinSymbol*));
}else {
bin->symbols_by_ord = NULL;
}
}
free (sym);
return ret;
beach:
free (sym);
free (ret);
return NULL;
}
static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_symbols)(ELFOBJ *bin) {
if (!bin) {
return NULL;
}
if (bin->phdr_symbols) {
return bin->phdr_symbols;
}
bin->phdr_symbols = get_symbols_from_phdr (bin, R_BIN_ELF_SYMBOLS);
return bin->phdr_symbols;
}
static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_imports)(ELFOBJ *bin) {
if (!bin) {
return NULL;
}
if (bin->phdr_imports) {
return bin->phdr_imports;
}
bin->phdr_imports = get_symbols_from_phdr (bin, R_BIN_ELF_IMPORTS);
return bin->phdr_imports;
}
static int Elf_(fix_symbols)(ELFOBJ *bin, int nsym, int type, RBinElfSymbol **sym) {
int count = 0;
RBinElfSymbol *ret = *sym;
RBinElfSymbol *phdr_symbols = (type == R_BIN_ELF_SYMBOLS)
? Elf_(r_bin_elf_get_phdr_symbols) (bin)
: Elf_(r_bin_elf_get_phdr_imports) (bin);
RBinElfSymbol *tmp, *p;
if (phdr_symbols) {
RBinElfSymbol *d = ret;
while (!d->last) {
/* find match in phdr */
p = phdr_symbols;
while (!p->last) {
if (p->offset && d->offset == p->offset) {
p->in_shdr = true;
if (*p->name && strcmp (d->name, p->name)) {
strcpy (d->name, p->name);
}
}
p++;
}
d++;
}
p = phdr_symbols;
while (!p->last) {
if (!p->in_shdr) {
count++;
}
p++;
}
/*Take those symbols that are not present in the shdr but yes in phdr*/
/*This should only should happen with fucked up binaries*/
if (count > 0) {
/*what happens if a shdr says it has only one symbol? we should look anyway into phdr*/
tmp = (RBinElfSymbol*)realloc (ret, (nsym + count + 1) * sizeof (RBinElfSymbol));
if (!tmp) {
return -1;
}
ret = tmp;
ret[nsym--].last = 0;
p = phdr_symbols;
while (!p->last) {
if (!p->in_shdr) {
memcpy (&ret[++nsym], p, sizeof (RBinElfSymbol));
}
p++;
}
ret[nsym + 1].last = 1;
}
*sym = ret;
return nsym + 1;
}
return nsym;
}
static RBinElfSymbol* Elf_(_r_bin_elf_get_symbols_imports)(ELFOBJ *bin, int type) {
ut32 shdr_size;
int tsize, nsym, ret_ctr = 0, i, j, r, k, newsize;
ut64 toffset;
ut32 size = 0;
RBinElfSymbol *ret = NULL;
Elf_(Shdr) *strtab_section = NULL;
Elf_(Sym) *sym = NULL;
ut8 s[sizeof (Elf_(Sym))] = { 0 };
char *strtab = NULL;
if (!bin || !bin->shdr || !bin->ehdr.e_shnum || bin->ehdr.e_shnum == 0xffff) {
return (type == R_BIN_ELF_SYMBOLS)
? Elf_(r_bin_elf_get_phdr_symbols) (bin)
: Elf_(r_bin_elf_get_phdr_imports) (bin);
}
if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) {
return false;
}
if (shdr_size + 8 > bin->size) {
return false;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
if ((type == R_BIN_ELF_IMPORTS && bin->shdr[i].sh_type == (bin->ehdr.e_type == ET_REL ? SHT_SYMTAB : SHT_DYNSYM)) ||
(type == R_BIN_ELF_SYMBOLS && bin->shdr[i].sh_type == (Elf_(r_bin_elf_get_stripped) (bin) ? SHT_DYNSYM : SHT_SYMTAB))) {
if (bin->shdr[i].sh_link < 1) {
/* oops. fix out of range pointers */
continue;
}
// hack to avoid asan cry
if ((bin->shdr[i].sh_link * sizeof(Elf_(Shdr))) >= shdr_size) {
/* oops. fix out of range pointers */
continue;
}
strtab_section = &bin->shdr[bin->shdr[i].sh_link];
if (strtab_section->sh_size > ST32_MAX || strtab_section->sh_size+8 > bin->size) {
bprintf ("size (syms strtab)");
free (ret);
free (strtab);
return NULL;
}
if (!strtab) {
if (!(strtab = (char *)calloc (1, 8 + strtab_section->sh_size))) {
bprintf ("malloc (syms strtab)");
goto beach;
}
if (strtab_section->sh_offset > bin->size ||
strtab_section->sh_offset + strtab_section->sh_size > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, strtab_section->sh_offset,
(ut8*)strtab, strtab_section->sh_size) == -1) {
bprintf ("Warning: read (syms strtab)\n");
goto beach;
}
}
newsize = 1 + bin->shdr[i].sh_size;
if (newsize < 0 || newsize > bin->size) {
bprintf ("invalid shdr %d size\n", i);
goto beach;
}
nsym = (int)(bin->shdr[i].sh_size / sizeof (Elf_(Sym)));
if (nsym < 0) {
goto beach;
}
if (!(sym = (Elf_(Sym) *)calloc (nsym, sizeof (Elf_(Sym))))) {
bprintf ("calloc (syms)");
goto beach;
}
if (!UT32_MUL (&size, nsym, sizeof (Elf_(Sym)))) {
goto beach;
}
if (size < 1 || size > bin->size) {
goto beach;
}
if (bin->shdr[i].sh_offset > bin->size) {
goto beach;
}
if (bin->shdr[i].sh_offset + size > bin->size) {
goto beach;
}
for (j = 0; j < nsym; j++) {
int k = 0;
r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset + j * sizeof (Elf_(Sym)), s, sizeof (Elf_(Sym)));
if (r < 1) {
bprintf ("Warning: read (sym)\n");
goto beach;
}
#if R_BIN_ELF64
sym[j].st_name = READ32 (s, k)
sym[j].st_info = READ8 (s, k)
sym[j].st_other = READ8 (s, k)
sym[j].st_shndx = READ16 (s, k)
sym[j].st_value = READ64 (s, k)
sym[j].st_size = READ64 (s, k)
#else
sym[j].st_name = READ32 (s, k)
sym[j].st_value = READ32 (s, k)
sym[j].st_size = READ32 (s, k)
sym[j].st_info = READ8 (s, k)
sym[j].st_other = READ8 (s, k)
sym[j].st_shndx = READ16 (s, k)
#endif
}
free (ret);
ret = calloc (nsym, sizeof (RBinElfSymbol));
if (!ret) {
bprintf ("Cannot allocate %d symbols\n", nsym);
goto beach;
}
for (k = 1, ret_ctr = 0; k < nsym; k++) {
if (type == R_BIN_ELF_IMPORTS && sym[k].st_shndx == STN_UNDEF) {
if (sym[k].st_value) {
toffset = sym[k].st_value;
} else if ((toffset = get_import_addr (bin, k)) == -1){
toffset = 0;
}
tsize = 16;
} else if (type == R_BIN_ELF_SYMBOLS &&
sym[k].st_shndx != STN_UNDEF &&
ELF_ST_TYPE (sym[k].st_info) != STT_SECTION &&
ELF_ST_TYPE (sym[k].st_info) != STT_FILE) {
//int idx = sym[k].st_shndx;
tsize = sym[k].st_size;
toffset = (ut64)sym[k].st_value;
} else {
continue;
}
if (bin->ehdr.e_type == ET_REL) {
if (sym[k].st_shndx < bin->ehdr.e_shnum)
ret[ret_ctr].offset = sym[k].st_value + bin->shdr[sym[k].st_shndx].sh_offset;
} else {
ret[ret_ctr].offset = Elf_(r_bin_elf_v2p) (bin, toffset);
}
ret[ret_ctr].size = tsize;
if (sym[k].st_name + 2 > strtab_section->sh_size) {
bprintf ("Warning: index out of strtab range\n");
goto beach;
}
{
int rest = ELF_STRING_LENGTH - 1;
int st_name = sym[k].st_name;
int maxsize = R_MIN (bin->b->length, strtab_section->sh_size);
if (st_name < 0 || st_name >= maxsize) {
ret[ret_ctr].name[0] = 0;
} else {
const size_t len = __strnlen (strtab + sym[k].st_name, rest);
memcpy (ret[ret_ctr].name, &strtab[sym[k].st_name], len);
}
}
ret[ret_ctr].ordinal = k;
ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0';
fill_symbol_bind_and_type (&ret[ret_ctr], &sym[k]);
ret[ret_ctr].last = 0;
ret_ctr++;
}
ret[ret_ctr].last = 1; // ugly dirty hack :D
R_FREE (strtab);
R_FREE (sym);
}
}
if (!ret) {
return (type == R_BIN_ELF_SYMBOLS)
? Elf_(r_bin_elf_get_phdr_symbols) (bin)
: Elf_(r_bin_elf_get_phdr_imports) (bin);
}
int max = -1;
RBinElfSymbol *aux = NULL;
nsym = Elf_(fix_symbols) (bin, ret_ctr, type, &ret);
if (nsym == -1) {
goto beach;
}
aux = ret;
while (!aux->last) {
if ((int)aux->ordinal > max) {
max = aux->ordinal;
}
aux++;
}
nsym = max;
if (type == R_BIN_ELF_IMPORTS) {
R_FREE (bin->imports_by_ord);
bin->imports_by_ord_size = nsym + 1;
bin->imports_by_ord = (RBinImport**)calloc (R_MAX (1, nsym + 1), sizeof (RBinImport*));
} else if (type == R_BIN_ELF_SYMBOLS) {
R_FREE (bin->symbols_by_ord);
bin->symbols_by_ord_size = nsym + 1;
bin->symbols_by_ord = (RBinSymbol**)calloc (R_MAX (1, nsym + 1), sizeof (RBinSymbol*));
}
return ret;
beach:
free (ret);
free (sym);
free (strtab);
return NULL;
}
RBinElfSymbol *Elf_(r_bin_elf_get_symbols)(ELFOBJ *bin) {
if (!bin->g_symbols) {
bin->g_symbols = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_SYMBOLS);
}
return bin->g_symbols;
}
RBinElfSymbol *Elf_(r_bin_elf_get_imports)(ELFOBJ *bin) {
if (!bin->g_imports) {
bin->g_imports = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_IMPORTS);
}
return bin->g_imports;
}
RBinElfField* Elf_(r_bin_elf_get_fields)(ELFOBJ *bin) {
RBinElfField *ret = NULL;
int i = 0, j;
if (!bin || !(ret = calloc ((bin->ehdr.e_phnum + 3 + 1), sizeof (RBinElfField)))) {
return NULL;
}
strncpy (ret[i].name, "ehdr", ELF_STRING_LENGTH);
ret[i].offset = 0;
ret[i++].last = 0;
strncpy (ret[i].name, "shoff", ELF_STRING_LENGTH);
ret[i].offset = bin->ehdr.e_shoff;
ret[i++].last = 0;
strncpy (ret[i].name, "phoff", ELF_STRING_LENGTH);
ret[i].offset = bin->ehdr.e_phoff;
ret[i++].last = 0;
for (j = 0; bin->phdr && j < bin->ehdr.e_phnum; i++, j++) {
snprintf (ret[i].name, ELF_STRING_LENGTH, "phdr_%i", j);
ret[i].offset = bin->phdr[j].p_offset;
ret[i].last = 0;
}
ret[i].last = 1;
return ret;
}
void* Elf_(r_bin_elf_free)(ELFOBJ* bin) {
int i;
if (!bin) {
return NULL;
}
free (bin->phdr);
free (bin->shdr);
free (bin->strtab);
free (bin->dyn_buf);
free (bin->shstrtab);
free (bin->dynstr);
//free (bin->strtab_section);
if (bin->imports_by_ord) {
for (i = 0; i<bin->imports_by_ord_size; i++) {
free (bin->imports_by_ord[i]);
}
free (bin->imports_by_ord);
}
if (bin->symbols_by_ord) {
for (i = 0; i<bin->symbols_by_ord_size; i++) {
free (bin->symbols_by_ord[i]);
}
free (bin->symbols_by_ord);
}
r_buf_free (bin->b);
if (bin->g_symbols != bin->phdr_symbols) {
R_FREE (bin->phdr_symbols);
}
if (bin->g_imports != bin->phdr_imports) {
R_FREE (bin->phdr_imports);
}
R_FREE (bin->g_sections);
R_FREE (bin->g_symbols);
R_FREE (bin->g_imports);
free (bin);
return NULL;
}
ELFOBJ* Elf_(r_bin_elf_new)(const char* file, bool verbose) {
ut8 *buf;
int size;
ELFOBJ *bin = R_NEW0 (ELFOBJ);
if (!bin) {
return NULL;
}
memset (bin, 0, sizeof (ELFOBJ));
bin->file = file;
if (!(buf = (ut8*)r_file_slurp (file, &size))) {
return Elf_(r_bin_elf_free) (bin);
}
bin->size = size;
bin->verbose = verbose;
bin->b = r_buf_new ();
if (!r_buf_set_bytes (bin->b, buf, bin->size)) {
free (buf);
return Elf_(r_bin_elf_free) (bin);
}
if (!elf_init (bin)) {
free (buf);
return Elf_(r_bin_elf_free) (bin);
}
free (buf);
return bin;
}
ELFOBJ* Elf_(r_bin_elf_new_buf)(RBuffer *buf, bool verbose) {
ELFOBJ *bin = R_NEW0 (ELFOBJ);
bin->kv = sdb_new0 ();
bin->b = r_buf_new ();
bin->size = (ut32)buf->length;
bin->verbose = verbose;
if (!r_buf_set_bytes (bin->b, buf->buf, buf->length)) {
return Elf_(r_bin_elf_free) (bin);
}
if (!elf_init (bin)) {
return Elf_(r_bin_elf_free) (bin);
}
return bin;
}
static int is_in_pphdr (Elf_(Phdr) *p, ut64 addr) {
return addr >= p->p_offset && addr < p->p_offset + p->p_memsz;
}
static int is_in_vphdr (Elf_(Phdr) *p, ut64 addr) {
return addr >= p->p_vaddr && addr < p->p_vaddr + p->p_memsz;
}
/* converts a physical address to the virtual address, looking
* at the program headers in the binary bin */
ut64 Elf_(r_bin_elf_p2v) (ELFOBJ *bin, ut64 paddr) {
int i;
if (!bin) return 0;
if (!bin->phdr) {
if (bin->ehdr.e_type == ET_REL) {
return bin->baddr + paddr;
}
return paddr;
}
for (i = 0; i < bin->ehdr.e_phnum; ++i) {
Elf_(Phdr) *p = &bin->phdr[i];
if (!p) {
break;
}
if (p->p_type == PT_LOAD && is_in_pphdr (p, paddr)) {
if (!p->p_vaddr && !p->p_offset) {
continue;
}
return p->p_vaddr + paddr - p->p_offset;
}
}
return paddr;
}
/* converts a virtual address to the relative physical address, looking
* at the program headers in the binary bin */
ut64 Elf_(r_bin_elf_v2p) (ELFOBJ *bin, ut64 vaddr) {
int i;
if (!bin) {
return 0;
}
if (!bin->phdr) {
if (bin->ehdr.e_type == ET_REL) {
return vaddr - bin->baddr;
}
return vaddr;
}
for (i = 0; i < bin->ehdr.e_phnum; ++i) {
Elf_(Phdr) *p = &bin->phdr[i];
if (!p) {
break;
}
if (p->p_type == PT_LOAD && is_in_vphdr (p, vaddr)) {
if (!p->p_offset && !p->p_vaddr) {
continue;
}
return p->p_offset + vaddr - p->p_vaddr;
}
}
return vaddr;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_2903_0 |
crossvul-cpp_data_bad_5370_1 | /*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* 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__
*/
/*
* Windows Bitmap File Library
*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <assert.h>
#include "jasper/jas_types.h"
#include "jasper/jas_stream.h"
#include "jasper/jas_image.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_debug.h"
#include "bmp_cod.h"
/******************************************************************************\
* Local prototypes.
\******************************************************************************/
static int bmp_gethdr(jas_stream_t *in, bmp_hdr_t *hdr);
static bmp_info_t *bmp_getinfo(jas_stream_t *in);
static int bmp_getdata(jas_stream_t *in, bmp_info_t *info, jas_image_t *image);
static int bmp_getint16(jas_stream_t *in, int_fast16_t *val);
static int bmp_getint32(jas_stream_t *in, int_fast32_t *val);
static int bmp_gobble(jas_stream_t *in, long n);
/******************************************************************************\
* Interface functions.
\******************************************************************************/
jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
return 0;
}
JAS_DBGLOG(1, (
"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n",
hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off
));
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
return 0;
}
JAS_DBGLOG(1,
("BMP information: len %d; width %d; height %d; numplanes %d; "
"depth %d; enctype %d; siz %d; hres %d; vres %d; numcolors %d; "
"mincolors %d\n", info->len, info->width, info->height, info->numplanes,
info->depth, info->enctype, info->siz, info->hres, info->vres,
info->numcolors, info->mincolors));
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
bmp_info_destroy(info);
return 0;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
bmp_info_destroy(info);
return 0;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
bmp_info_destroy(info);
jas_image_destroy(image);
return 0;
}
bmp_info_destroy(info);
return image;
}
int bmp_validate(jas_stream_t *in)
{
int n;
int i;
uchar buf[2];
assert(JAS_STREAM_MAXPUTBACK >= 2);
/* Read the first two characters that constitute the signature. */
if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) {
return -1;
}
/* Put the characters read back onto the stream. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough characters? */
if (n < 2) {
return -1;
}
/* Is the signature correct for the BMP format? */
if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) {
return 0;
}
return -1;
}
/******************************************************************************\
* Code for aggregate types.
\******************************************************************************/
static int bmp_gethdr(jas_stream_t *in, bmp_hdr_t *hdr)
{
if (bmp_getint16(in, &hdr->magic) || hdr->magic != BMP_MAGIC ||
bmp_getint32(in, &hdr->siz) || bmp_getint16(in, &hdr->reserved1) ||
bmp_getint16(in, &hdr->reserved2) || bmp_getint32(in, &hdr->off)) {
return -1;
}
return 0;
}
static bmp_info_t *bmp_getinfo(jas_stream_t *in)
{
bmp_info_t *info;
int i;
bmp_palent_t *palent;
if (!(info = bmp_info_create())) {
return 0;
}
if (bmp_getint32(in, &info->len) || info->len != 40 ||
bmp_getint32(in, &info->width) || bmp_getint32(in, &info->height) ||
bmp_getint16(in, &info->numplanes) ||
bmp_getint16(in, &info->depth) || bmp_getint32(in, &info->enctype) ||
bmp_getint32(in, &info->siz) ||
bmp_getint32(in, &info->hres) || bmp_getint32(in, &info->vres) ||
bmp_getint32(in, &info->numcolors) ||
bmp_getint32(in, &info->mincolors)) {
bmp_info_destroy(info);
return 0;
}
if (info->height < 0) {
info->topdown = 1;
info->height = -info->height;
} else {
info->topdown = 0;
}
if (info->width <= 0 || info->height <= 0 || info->numplanes <= 0 ||
info->depth <= 0 || info->numcolors < 0 || info->mincolors < 0) {
bmp_info_destroy(info);
return 0;
}
if (info->enctype != BMP_ENC_RGB) {
jas_eprintf("unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
if (info->numcolors > 0) {
if (!(info->palents = jas_alloc2(info->numcolors,
sizeof(bmp_palent_t)))) {
bmp_info_destroy(info);
return 0;
}
} else {
info->palents = 0;
}
for (i = 0; i < info->numcolors; ++i) {
palent = &info->palents[i];
if ((palent->blu = jas_stream_getc(in)) == EOF ||
(palent->grn = jas_stream_getc(in)) == EOF ||
(palent->red = jas_stream_getc(in)) == EOF ||
(palent->res = jas_stream_getc(in)) == EOF) {
bmp_info_destroy(info);
return 0;
}
}
return info;
}
static int bmp_getdata(jas_stream_t *in, bmp_info_t *info, jas_image_t *image)
{
int i;
int j;
int y;
jas_matrix_t *cmpts[3];
int numpad;
int red;
int grn;
int blu;
int ret;
int numcmpts;
int cmptno;
int ind;
bmp_palent_t *palent;
int mxind;
int haspal;
assert(info->depth == 8 || info->depth == 24);
assert(info->enctype == BMP_ENC_RGB);
numcmpts = bmp_numcmpts(info);
haspal = bmp_haspal(info);
ret = 0;
for (i = 0; i < numcmpts; ++i) {
cmpts[i] = 0;
}
/* Create temporary matrices to hold component data. */
for (i = 0; i < numcmpts; ++i) {
if (!(cmpts[i] = jas_matrix_create(1, info->width))) {
ret = -1;
goto bmp_getdata_done;
}
}
/* Calculate number of padding bytes per row of image data. */
numpad = (numcmpts * info->width) % 4;
if (numpad) {
numpad = 4 - numpad;
}
mxind = (1 << info->depth) - 1;
for (i = 0; i < info->height; ++i) {
for (j = 0; j < info->width; ++j) {
if (haspal) {
if ((ind = jas_stream_getc(in)) == EOF) {
ret = -1;
goto bmp_getdata_done;
}
if (ind > mxind) {
ret = -1;
goto bmp_getdata_done;
}
if (ind < info->numcolors) {
palent = &info->palents[ind];
red = palent->red;
grn = palent->grn;
blu = palent->blu;
} else {
red = ind;
grn = ind;
blu = ind;
}
} else {
if ((blu = jas_stream_getc(in)) == EOF ||
(grn = jas_stream_getc(in)) == EOF ||
(red = jas_stream_getc(in)) == EOF) {
ret = -1;
goto bmp_getdata_done;
}
}
if (numcmpts == 3) {
jas_matrix_setv(cmpts[0], j, red);
jas_matrix_setv(cmpts[1], j, grn);
jas_matrix_setv(cmpts[2], j, blu);
} else {
jas_matrix_setv(cmpts[0], j, red);
}
}
for (j = numpad; j > 0; --j) {
if (jas_stream_getc(in) == EOF) {
ret = -1;
goto bmp_getdata_done;
}
}
for (cmptno = 0; cmptno < numcmpts; ++cmptno) {
y = info->topdown ? i : (info->height - 1 - i);
if (jas_image_writecmpt(image, cmptno, 0, y, info->width,
1, cmpts[cmptno])) {
ret = -1;
goto bmp_getdata_done;
}
}
}
bmp_getdata_done:
/* Destroy the temporary matrices. */
for (i = 0; i < numcmpts; ++i) {
if (cmpts[i]) {
jas_matrix_destroy(cmpts[i]);
}
}
return ret;
}
/******************************************************************************\
* Code for primitive types.
\******************************************************************************/
static int bmp_getint16(jas_stream_t *in, int_fast16_t *val)
{
int lo;
int hi;
if ((lo = jas_stream_getc(in)) == EOF || (hi = jas_stream_getc(in)) == EOF) {
return -1;
}
if (val) {
*val = (hi << 8) | lo;
}
return 0;
}
static int bmp_getint32(jas_stream_t *in, int_fast32_t *val)
{
int n;
uint_fast32_t v;
int c;
for (n = 4, v = 0;;) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v |= (JAS_CAST(uint_fast32_t, c) << 24);
if (--n <= 0) {
break;
}
v >>= 8;
}
if (val) {
*val = v;
}
return 0;
}
static int bmp_gobble(jas_stream_t *in, long n)
{
while (--n >= 0) {
if (jas_stream_getc(in) == EOF) {
return -1;
}
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_5370_1 |
crossvul-cpp_data_bad_5350_0 | /*
* algif_hash: User-space interface for hash algorithms
*
* This file provides the user-space API for hash algorithms.
*
* 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/hash.h>
#include <crypto/if_alg.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/net.h>
#include <net/sock.h>
struct hash_ctx {
struct af_alg_sgl sgl;
u8 *result;
struct af_alg_completion completion;
unsigned int len;
bool more;
struct ahash_request req;
};
static int hash_sendmsg(struct socket *sock, struct msghdr *msg,
size_t ignored)
{
int limit = ALG_MAX_PAGES * PAGE_SIZE;
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
long copied = 0;
int err;
if (limit > sk->sk_sndbuf)
limit = sk->sk_sndbuf;
lock_sock(sk);
if (!ctx->more) {
err = crypto_ahash_init(&ctx->req);
if (err)
goto unlock;
}
ctx->more = 0;
while (msg_data_left(msg)) {
int len = msg_data_left(msg);
if (len > limit)
len = limit;
len = af_alg_make_sg(&ctx->sgl, &msg->msg_iter, len);
if (len < 0) {
err = copied ? 0 : len;
goto unlock;
}
ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, NULL, len);
err = af_alg_wait_for_completion(crypto_ahash_update(&ctx->req),
&ctx->completion);
af_alg_free_sg(&ctx->sgl);
if (err)
goto unlock;
copied += len;
iov_iter_advance(&msg->msg_iter, len);
}
err = 0;
ctx->more = msg->msg_flags & MSG_MORE;
if (!ctx->more) {
ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);
err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),
&ctx->completion);
}
unlock:
release_sock(sk);
return err ?: copied;
}
static ssize_t hash_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 hash_ctx *ctx = ask->private;
int err;
if (flags & MSG_SENDPAGE_NOTLAST)
flags |= MSG_MORE;
lock_sock(sk);
sg_init_table(ctx->sgl.sg, 1);
sg_set_page(ctx->sgl.sg, page, size, offset);
ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, ctx->result, size);
if (!(flags & MSG_MORE)) {
if (ctx->more)
err = crypto_ahash_finup(&ctx->req);
else
err = crypto_ahash_digest(&ctx->req);
} else {
if (!ctx->more) {
err = crypto_ahash_init(&ctx->req);
if (err)
goto unlock;
}
err = crypto_ahash_update(&ctx->req);
}
err = af_alg_wait_for_completion(err, &ctx->completion);
if (err)
goto unlock;
ctx->more = flags & MSG_MORE;
unlock:
release_sock(sk);
return err ?: size;
}
static int hash_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req));
int err;
if (len > ds)
len = ds;
else if (len < ds)
msg->msg_flags |= MSG_TRUNC;
lock_sock(sk);
if (ctx->more) {
ctx->more = 0;
ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);
err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),
&ctx->completion);
if (err)
goto unlock;
}
err = memcpy_to_msg(msg, ctx->result, len);
unlock:
release_sock(sk);
return err ?: len;
}
static int hash_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
struct ahash_request *req = &ctx->req;
char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];
struct sock *sk2;
struct alg_sock *ask2;
struct hash_ctx *ctx2;
int err;
err = crypto_ahash_export(req, state);
if (err)
return err;
err = af_alg_accept(ask->parent, newsock);
if (err)
return err;
sk2 = newsock->sk;
ask2 = alg_sk(sk2);
ctx2 = ask2->private;
ctx2->more = 1;
err = crypto_ahash_import(&ctx2->req, state);
if (err) {
sock_orphan(sk2);
sock_put(sk2);
}
return err;
}
static struct proto_ops algif_hash_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,
.setsockopt = sock_no_setsockopt,
.poll = sock_no_poll,
.release = af_alg_release,
.sendmsg = hash_sendmsg,
.sendpage = hash_sendpage,
.recvmsg = hash_recvmsg,
.accept = hash_accept,
};
static void *hash_bind(const char *name, u32 type, u32 mask)
{
return crypto_alloc_ahash(name, type, mask);
}
static void hash_release(void *private)
{
crypto_free_ahash(private);
}
static int hash_setkey(void *private, const u8 *key, unsigned int keylen)
{
return crypto_ahash_setkey(private, key, keylen);
}
static void hash_sock_destruct(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
sock_kzfree_s(sk, ctx->result,
crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)));
sock_kfree_s(sk, ctx, ctx->len);
af_alg_release_parent(sk);
}
static int hash_accept_parent(void *private, struct sock *sk)
{
struct hash_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned len = sizeof(*ctx) + crypto_ahash_reqsize(private);
unsigned ds = crypto_ahash_digestsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->result = sock_kmalloc(sk, ds, GFP_KERNEL);
if (!ctx->result) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->result, 0, ds);
ctx->len = len;
ctx->more = 0;
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
ahash_request_set_tfm(&ctx->req, private);
ahash_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = hash_sock_destruct;
return 0;
}
static const struct af_alg_type algif_type_hash = {
.bind = hash_bind,
.release = hash_release,
.setkey = hash_setkey,
.accept = hash_accept_parent,
.ops = &algif_hash_ops,
.name = "hash",
.owner = THIS_MODULE
};
static int __init algif_hash_init(void)
{
return af_alg_register_type(&algif_type_hash);
}
static void __exit algif_hash_exit(void)
{
int err = af_alg_unregister_type(&algif_type_hash);
BUG_ON(err);
}
module_init(algif_hash_init);
module_exit(algif_hash_exit);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_5350_0 |
crossvul-cpp_data_good_5371_0 | /*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2002 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__
*/
/*
* JP2 Library
*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <assert.h>
#include <stdlib.h>
#include "jasper/jas_stream.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_debug.h"
#include "jp2_cod.h"
/******************************************************************************\
* Function prototypes.
\******************************************************************************/
#define ONES(n) ((1 << (n)) - 1)
jp2_boxinfo_t *jp2_boxinfolookup(int type);
static int jp2_getuint8(jas_stream_t *in, uint_fast8_t *val);
static int jp2_getuint16(jas_stream_t *in, uint_fast16_t *val);
static int jp2_getuint32(jas_stream_t *in, uint_fast32_t *val);
static int jp2_getuint64(jas_stream_t *in, uint_fast64_t *val);
static int jp2_putuint8(jas_stream_t *out, uint_fast8_t val);
static int jp2_putuint16(jas_stream_t *out, uint_fast16_t val);
static int jp2_putuint32(jas_stream_t *out, uint_fast32_t val);
static int jp2_putuint64(jas_stream_t *out, uint_fast64_t val);
static int jp2_getint(jas_stream_t *in, int s, int n, int_fast32_t *val);
jp2_box_t *jp2_box_get(jas_stream_t *in);
void jp2_box_dump(jp2_box_t *box, FILE *out);
static int jp2_jp_getdata(jp2_box_t *box, jas_stream_t *in);
static int jp2_jp_putdata(jp2_box_t *box, jas_stream_t *out);
static int jp2_ftyp_getdata(jp2_box_t *box, jas_stream_t *in);
static int jp2_ftyp_putdata(jp2_box_t *box, jas_stream_t *out);
static int jp2_ihdr_getdata(jp2_box_t *box, jas_stream_t *in);
static int jp2_ihdr_putdata(jp2_box_t *box, jas_stream_t *out);
static void jp2_bpcc_destroy(jp2_box_t *box);
static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in);
static int jp2_bpcc_putdata(jp2_box_t *box, jas_stream_t *out);
static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in);
static int jp2_colr_putdata(jp2_box_t *box, jas_stream_t *out);
static void jp2_colr_dumpdata(jp2_box_t *box, FILE *out);
static void jp2_colr_destroy(jp2_box_t *box);
static void jp2_cdef_destroy(jp2_box_t *box);
static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in);
static int jp2_cdef_putdata(jp2_box_t *box, jas_stream_t *out);
static void jp2_cdef_dumpdata(jp2_box_t *box, FILE *out);
static void jp2_cmap_destroy(jp2_box_t *box);
static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in);
static int jp2_cmap_putdata(jp2_box_t *box, jas_stream_t *out);
static void jp2_cmap_dumpdata(jp2_box_t *box, FILE *out);
static void jp2_pclr_destroy(jp2_box_t *box);
static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in);
static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out);
static void jp2_pclr_dumpdata(jp2_box_t *box, FILE *out);
/******************************************************************************\
* Local data.
\******************************************************************************/
jp2_boxinfo_t jp2_boxinfos[] = {
{JP2_BOX_JP, "JP", 0,
{0, 0, jp2_jp_getdata, jp2_jp_putdata, 0}},
{JP2_BOX_FTYP, "FTYP", 0,
{0, 0, jp2_ftyp_getdata, jp2_ftyp_putdata, 0}},
{JP2_BOX_JP2H, "JP2H", JP2_BOX_SUPER,
{0, 0, 0, 0, 0}},
{JP2_BOX_IHDR, "IHDR", 0,
{0, 0, jp2_ihdr_getdata, jp2_ihdr_putdata, 0}},
{JP2_BOX_BPCC, "BPCC", 0,
{0, jp2_bpcc_destroy, jp2_bpcc_getdata, jp2_bpcc_putdata, 0}},
{JP2_BOX_COLR, "COLR", 0,
{0, jp2_colr_destroy, jp2_colr_getdata, jp2_colr_putdata, jp2_colr_dumpdata}},
{JP2_BOX_PCLR, "PCLR", 0,
{0, jp2_pclr_destroy, jp2_pclr_getdata, jp2_pclr_putdata, jp2_pclr_dumpdata}},
{JP2_BOX_CMAP, "CMAP", 0,
{0, jp2_cmap_destroy, jp2_cmap_getdata, jp2_cmap_putdata, jp2_cmap_dumpdata}},
{JP2_BOX_CDEF, "CDEF", 0,
{0, jp2_cdef_destroy, jp2_cdef_getdata, jp2_cdef_putdata, jp2_cdef_dumpdata}},
{JP2_BOX_RES, "RES", JP2_BOX_SUPER,
{0, 0, 0, 0, 0}},
{JP2_BOX_RESC, "RESC", 0,
{0, 0, 0, 0, 0}},
{JP2_BOX_RESD, "RESD", 0,
{0, 0, 0, 0, 0}},
{JP2_BOX_JP2C, "JP2C", JP2_BOX_NODATA,
{0, 0, 0, 0, 0}},
{JP2_BOX_JP2I, "JP2I", 0,
{0, 0, 0, 0, 0}},
{JP2_BOX_XML, "XML", 0,
{0, 0, 0, 0, 0}},
{JP2_BOX_UUID, "UUID", 0,
{0, 0, 0, 0, 0}},
{JP2_BOX_UINF, "UINF", JP2_BOX_SUPER,
{0, 0, 0, 0, 0}},
{JP2_BOX_ULST, "ULST", 0,
{0, 0, 0, 0, 0}},
{JP2_BOX_URL, "URL", 0,
{0, 0, 0, 0, 0}},
{0, 0, 0, {0, 0, 0, 0, 0}},
};
jp2_boxinfo_t jp2_boxinfo_unk = {
0, "Unknown", 0, {0, 0, 0, 0, 0}
};
/******************************************************************************\
* Box constructor.
\******************************************************************************/
jp2_box_t *jp2_box_create(int type)
{
jp2_box_t *box;
jp2_boxinfo_t *boxinfo;
if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
return 0;
}
memset(box, 0, sizeof(jp2_box_t));
box->type = type;
box->len = 0;
if (!(boxinfo = jp2_boxinfolookup(type))) {
return 0;
}
box->info = boxinfo;
box->ops = &boxinfo->ops;
return box;
}
/******************************************************************************\
* Box destructor.
\******************************************************************************/
void jp2_box_destroy(jp2_box_t *box)
{
if (box->ops->destroy) {
(*box->ops->destroy)(box);
}
jas_free(box);
}
static void jp2_bpcc_destroy(jp2_box_t *box)
{
jp2_bpcc_t *bpcc = &box->data.bpcc;
if (bpcc->bpcs) {
jas_free(bpcc->bpcs);
bpcc->bpcs = 0;
}
}
static void jp2_cdef_destroy(jp2_box_t *box)
{
jp2_cdef_t *cdef = &box->data.cdef;
if (cdef->ents) {
jas_free(cdef->ents);
cdef->ents = 0;
}
}
/******************************************************************************\
* Box input.
\******************************************************************************/
jp2_box_t *jp2_box_get(jas_stream_t *in)
{
jp2_box_t *box;
jp2_boxinfo_t *boxinfo;
jas_stream_t *tmpstream;
uint_fast32_t len;
uint_fast64_t extlen;
bool dataflag;
box = 0;
tmpstream = 0;
if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
goto error;
}
box->ops = &jp2_boxinfo_unk.ops;
if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) {
goto error;
}
boxinfo = jp2_boxinfolookup(box->type);
box->info = boxinfo;
box->ops = &boxinfo->ops;
box->len = len;
JAS_DBGLOG(10, (
"preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\n",
'"', boxinfo->name, '"', box->type, box->len
));
if (box->len == 1) {
if (jp2_getuint64(in, &extlen)) {
goto error;
}
if (extlen > 0xffffffffUL) {
jas_eprintf("warning: cannot handle large 64-bit box length\n");
extlen = 0xffffffffUL;
}
box->len = extlen;
box->datalen = extlen - JP2_BOX_HDRLEN(true);
} else {
box->datalen = box->len - JP2_BOX_HDRLEN(false);
}
if (box->len != 0 && box->len < 8) {
goto error;
}
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (jas_stream_copy(tmpstream, in, box->datalen)) {
// Mark the box data as never having been constructed
// so that we will not errantly attempt to destroy it later.
box->ops = &jp2_boxinfo_unk.ops;
jas_eprintf("cannot copy box data\n");
goto error;
}
jas_stream_rewind(tmpstream);
if (box->ops->getdata) {
if ((*box->ops->getdata)(box, tmpstream)) {
jas_eprintf("cannot parse box data\n");
goto error;
}
}
jas_stream_close(tmpstream);
}
if (jas_getdbglevel() >= 1) {
jp2_box_dump(box, stderr);
}
return box;
error:
if (box) {
jp2_box_destroy(box);
}
if (tmpstream) {
jas_stream_close(tmpstream);
}
return 0;
}
void jp2_box_dump(jp2_box_t *box, FILE *out)
{
jp2_boxinfo_t *boxinfo;
boxinfo = jp2_boxinfolookup(box->type);
assert(boxinfo);
fprintf(out, "JP2 box: ");
fprintf(out, "type=%c%s%c (0x%08x); length=%d\n", '"', boxinfo->name,
'"', box->type, box->len);
if (box->ops->dumpdata) {
(*box->ops->dumpdata)(box, out);
}
}
static int jp2_jp_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_jp_t *jp = &box->data.jp;
if (jp2_getuint32(in, &jp->magic)) {
return -1;
}
return 0;
}
static int jp2_ftyp_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_ftyp_t *ftyp = &box->data.ftyp;
unsigned int i;
if (jp2_getuint32(in, &ftyp->majver) || jp2_getuint32(in, &ftyp->minver)) {
return -1;
}
ftyp->numcompatcodes = (box->datalen - 8) / 4;
if (ftyp->numcompatcodes > JP2_FTYP_MAXCOMPATCODES) {
return -1;
}
for (i = 0; i < ftyp->numcompatcodes; ++i) {
if (jp2_getuint32(in, &ftyp->compatcodes[i])) {
return -1;
}
}
return 0;
}
static int jp2_ihdr_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_ihdr_t *ihdr = &box->data.ihdr;
if (jp2_getuint32(in, &ihdr->height) || jp2_getuint32(in, &ihdr->width) ||
jp2_getuint16(in, &ihdr->numcmpts) || jp2_getuint8(in, &ihdr->bpc) ||
jp2_getuint8(in, &ihdr->comptype) || jp2_getuint8(in, &ihdr->csunk) ||
jp2_getuint8(in, &ihdr->ipr)) {
return -1;
}
return 0;
}
static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_bpcc_t *bpcc = &box->data.bpcc;
unsigned int i;
bpcc->numcmpts = box->datalen;
if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < bpcc->numcmpts; ++i) {
if (jp2_getuint8(in, &bpcc->bpcs[i])) {
return -1;
}
}
return 0;
}
static void jp2_colr_dumpdata(jp2_box_t *box, FILE *out)
{
jp2_colr_t *colr = &box->data.colr;
fprintf(out, "method=%d; pri=%d; approx=%d\n", (int)colr->method, (int)colr->pri, (int)colr->approx);
switch (colr->method) {
case JP2_COLR_ENUM:
fprintf(out, "csid=%d\n", (int)colr->csid);
break;
case JP2_COLR_ICC:
jas_memdump(out, colr->iccp, colr->iccplen);
break;
}
}
static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_colr_t *colr = &box->data.colr;
colr->csid = 0;
colr->iccp = 0;
colr->iccplen = 0;
if (jp2_getuint8(in, &colr->method) || jp2_getuint8(in, &colr->pri) ||
jp2_getuint8(in, &colr->approx)) {
return -1;
}
switch (colr->method) {
case JP2_COLR_ENUM:
if (jp2_getuint32(in, &colr->csid)) {
return -1;
}
break;
case JP2_COLR_ICC:
colr->iccplen = box->datalen - 3;
if (!(colr->iccp = jas_alloc2(colr->iccplen, sizeof(uint_fast8_t)))) {
return -1;
}
if (jas_stream_read(in, colr->iccp, colr->iccplen) != colr->iccplen) {
return -1;
}
break;
}
return 0;
}
static void jp2_cdef_dumpdata(jp2_box_t *box, FILE *out)
{
jp2_cdef_t *cdef = &box->data.cdef;
unsigned int i;
for (i = 0; i < cdef->numchans; ++i) {
fprintf(out, "channo=%d; type=%d; assoc=%d\n",
cdef->ents[i].channo, cdef->ents[i].type, cdef->ents[i].assoc);
}
}
static void jp2_colr_destroy(jp2_box_t *box)
{
jp2_colr_t *colr = &box->data.colr;
if (colr->iccp) {
jas_free(colr->iccp);
}
}
static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_cdef_t *cdef = &box->data.cdef;
jp2_cdefchan_t *chan;
unsigned int channo;
if (jp2_getuint16(in, &cdef->numchans)) {
return -1;
}
if (!(cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)))) {
return -1;
}
for (channo = 0; channo < cdef->numchans; ++channo) {
chan = &cdef->ents[channo];
if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) ||
jp2_getuint16(in, &chan->assoc)) {
return -1;
}
}
return 0;
}
/******************************************************************************\
* Box output.
\******************************************************************************/
int jp2_box_put(jp2_box_t *box, jas_stream_t *out)
{
jas_stream_t *tmpstream;
bool extlen;
bool dataflag;
tmpstream = 0;
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (box->ops->putdata) {
if ((*box->ops->putdata)(box, tmpstream)) {
goto error;
}
}
box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
jas_stream_rewind(tmpstream);
}
extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
if (jp2_putuint32(out, extlen ? 1 : box->len)) {
goto error;
}
if (jp2_putuint32(out, box->type)) {
goto error;
}
if (extlen) {
if (jp2_putuint64(out, box->len)) {
goto error;
}
}
if (dataflag) {
if (jas_stream_copy(out, tmpstream, box->len - JP2_BOX_HDRLEN(false))) {
goto error;
}
jas_stream_close(tmpstream);
}
return 0;
error:
if (tmpstream) {
jas_stream_close(tmpstream);
}
return -1;
}
static int jp2_jp_putdata(jp2_box_t *box, jas_stream_t *out)
{
jp2_jp_t *jp = &box->data.jp;
if (jp2_putuint32(out, jp->magic)) {
return -1;
}
return 0;
}
static int jp2_ftyp_putdata(jp2_box_t *box, jas_stream_t *out)
{
jp2_ftyp_t *ftyp = &box->data.ftyp;
unsigned int i;
if (jp2_putuint32(out, ftyp->majver) || jp2_putuint32(out, ftyp->minver)) {
return -1;
}
for (i = 0; i < ftyp->numcompatcodes; ++i) {
if (jp2_putuint32(out, ftyp->compatcodes[i])) {
return -1;
}
}
return 0;
}
static int jp2_ihdr_putdata(jp2_box_t *box, jas_stream_t *out)
{
jp2_ihdr_t *ihdr = &box->data.ihdr;
if (jp2_putuint32(out, ihdr->height) || jp2_putuint32(out, ihdr->width) ||
jp2_putuint16(out, ihdr->numcmpts) || jp2_putuint8(out, ihdr->bpc) ||
jp2_putuint8(out, ihdr->comptype) || jp2_putuint8(out, ihdr->csunk) ||
jp2_putuint8(out, ihdr->ipr)) {
return -1;
}
return 0;
}
static int jp2_bpcc_putdata(jp2_box_t *box, jas_stream_t *out)
{
jp2_bpcc_t *bpcc = &box->data.bpcc;
unsigned int i;
for (i = 0; i < bpcc->numcmpts; ++i) {
if (jp2_putuint8(out, bpcc->bpcs[i])) {
return -1;
}
}
return 0;
}
static int jp2_colr_putdata(jp2_box_t *box, jas_stream_t *out)
{
jp2_colr_t *colr = &box->data.colr;
if (jp2_putuint8(out, colr->method) || jp2_putuint8(out, colr->pri) ||
jp2_putuint8(out, colr->approx)) {
return -1;
}
switch (colr->method) {
case JP2_COLR_ENUM:
if (jp2_putuint32(out, colr->csid)) {
return -1;
}
break;
case JP2_COLR_ICC:
if (jas_stream_write(out, colr->iccp,
JAS_CAST(int, colr->iccplen)) != JAS_CAST(int, colr->iccplen))
return -1;
break;
}
return 0;
}
static int jp2_cdef_putdata(jp2_box_t *box, jas_stream_t *out)
{
jp2_cdef_t *cdef = &box->data.cdef;
unsigned int i;
jp2_cdefchan_t *ent;
if (jp2_putuint16(out, cdef->numchans)) {
return -1;
}
for (i = 0; i < cdef->numchans; ++i) {
ent = &cdef->ents[i];
if (jp2_putuint16(out, ent->channo) ||
jp2_putuint16(out, ent->type) ||
jp2_putuint16(out, ent->assoc)) {
return -1;
}
}
return 0;
}
/******************************************************************************\
* Input operations for primitive types.
\******************************************************************************/
static int jp2_getuint8(jas_stream_t *in, uint_fast8_t *val)
{
int c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
if (val) {
*val = c;
}
return 0;
}
static int jp2_getuint16(jas_stream_t *in, uint_fast16_t *val)
{
uint_fast16_t v;
int c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if (val) {
*val = v;
}
return 0;
}
static int jp2_getuint32(jas_stream_t *in, uint_fast32_t *val)
{
uint_fast32_t v;
int c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if (val) {
*val = v;
}
return 0;
}
static int jp2_getuint64(jas_stream_t *in, uint_fast64_t *val)
{
uint_fast64_t tmpval;
int i;
int c;
tmpval = 0;
for (i = 0; i < 8; ++i) {
tmpval <<= 8;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
tmpval |= (c & 0xff);
}
*val = tmpval;
return 0;
}
/******************************************************************************\
* Output operations for primitive types.
\******************************************************************************/
static int jp2_putuint8(jas_stream_t *out, uint_fast8_t val)
{
if (jas_stream_putc(out, val & 0xff) == EOF) {
return -1;
}
return 0;
}
static int jp2_putuint16(jas_stream_t *out, uint_fast16_t val)
{
if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
jas_stream_putc(out, val & 0xff) == EOF) {
return -1;
}
return 0;
}
static int jp2_putuint32(jas_stream_t *out, uint_fast32_t val)
{
if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF ||
jas_stream_putc(out, (val >> 16) & 0xff) == EOF ||
jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
jas_stream_putc(out, val & 0xff) == EOF) {
return -1;
}
return 0;
}
static int jp2_putuint64(jas_stream_t *out, uint_fast64_t val)
{
if (jp2_putuint32(out, (val >> 32) & 0xffffffffUL) ||
jp2_putuint32(out, val & 0xffffffffUL)) {
return -1;
}
return 0;
}
/******************************************************************************\
* Miscellaneous code.
\******************************************************************************/
jp2_boxinfo_t *jp2_boxinfolookup(int type)
{
jp2_boxinfo_t *boxinfo;
for (boxinfo = jp2_boxinfos; boxinfo->name; ++boxinfo) {
if (boxinfo->type == type) {
return boxinfo;
}
}
return &jp2_boxinfo_unk;
}
static void jp2_cmap_destroy(jp2_box_t *box)
{
jp2_cmap_t *cmap = &box->data.cmap;
if (cmap->ents) {
jas_free(cmap->ents);
}
}
static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_cmap_t *cmap = &box->data.cmap;
jp2_cmapent_t *ent;
unsigned int i;
cmap->numchans = (box->datalen) / 4;
if (!(cmap->ents = jas_alloc2(cmap->numchans, sizeof(jp2_cmapent_t)))) {
return -1;
}
for (i = 0; i < cmap->numchans; ++i) {
ent = &cmap->ents[i];
if (jp2_getuint16(in, &ent->cmptno) ||
jp2_getuint8(in, &ent->map) ||
jp2_getuint8(in, &ent->pcol)) {
return -1;
}
}
return 0;
}
static int jp2_cmap_putdata(jp2_box_t *box, jas_stream_t *out)
{
/* Eliminate compiler warning about unused variables. */
box = 0;
out = 0;
return -1;
}
static void jp2_cmap_dumpdata(jp2_box_t *box, FILE *out)
{
jp2_cmap_t *cmap = &box->data.cmap;
unsigned int i;
jp2_cmapent_t *ent;
fprintf(out, "numchans = %d\n", (int) cmap->numchans);
for (i = 0; i < cmap->numchans; ++i) {
ent = &cmap->ents[i];
fprintf(out, "cmptno=%d; map=%d; pcol=%d\n",
(int) ent->cmptno, (int) ent->map, (int) ent->pcol);
}
}
static void jp2_pclr_destroy(jp2_box_t *box)
{
jp2_pclr_t *pclr = &box->data.pclr;
if (pclr->lutdata) {
jas_free(pclr->lutdata);
}
if (pclr->bpc)
jas_free(pclr->bpc);
}
static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_pclr_t *pclr = &box->data.pclr;
int lutsize;
unsigned int i;
unsigned int j;
int_fast32_t x;
pclr->lutdata = 0;
if (jp2_getuint16(in, &pclr->numlutents) ||
jp2_getuint8(in, &pclr->numchans)) {
return -1;
}
lutsize = pclr->numlutents * pclr->numchans;
if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) {
return -1;
}
if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < pclr->numchans; ++i) {
if (jp2_getuint8(in, &pclr->bpc[i])) {
return -1;
}
}
for (i = 0; i < pclr->numlutents; ++i) {
for (j = 0; j < pclr->numchans; ++j) {
if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0,
(pclr->bpc[j] & 0x7f) + 1, &x)) {
return -1;
}
pclr->lutdata[i * pclr->numchans + j] = x;
}
}
return 0;
}
static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out)
{
#if 0
jp2_pclr_t *pclr = &box->data.pclr;
#endif
/* Eliminate warning about unused variable. */
box = 0;
out = 0;
return -1;
}
static void jp2_pclr_dumpdata(jp2_box_t *box, FILE *out)
{
jp2_pclr_t *pclr = &box->data.pclr;
unsigned int i;
int j;
fprintf(out, "numents=%d; numchans=%d\n", (int) pclr->numlutents,
(int) pclr->numchans);
for (i = 0; i < pclr->numlutents; ++i) {
for (j = 0; j < pclr->numchans; ++j) {
fprintf(out, "LUT[%d][%d]=%d\n", i, j, pclr->lutdata[i * pclr->numchans + j]);
}
}
}
static int jp2_getint(jas_stream_t *in, int s, int n, int_fast32_t *val)
{
int c;
int i;
uint_fast32_t v;
int m;
m = (n + 7) / 8;
v = 0;
for (i = 0; i < m; ++i) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
}
v &= ONES(n);
if (s) {
int sb;
sb = v & (1 << (8 * m - 1));
*val = ((~v) + 1) & ONES(8 * m);
if (sb) {
*val = -*val;
}
} else {
*val = v;
}
return 0;
}
jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo)
{
unsigned int i;
jp2_cdefchan_t *cdefent;
for (i = 0; i < cdef->numchans; ++i) {
cdefent = &cdef->ents[i];
if (cdefent->channo == JAS_CAST(unsigned int, channo)) {
return cdefent;
}
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5371_0 |
crossvul-cpp_data_good_3403_0 | /*
* DNxHD/VC-3 parser
* Copyright (c) 2008 Baptiste Coudurier <baptiste.coudurier@free.fr>
*
* 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
* DNxHD/VC-3 parser
*/
#include "parser.h"
#include "dnxhddata.h"
typedef struct {
ParseContext pc;
int interlaced;
int cur_field; /* first field is 0, second is 1 */
int cur_byte;
int remaining;
int w, h;
} DNXHDParserContext;
static int dnxhd_get_hr_frame_size(int cid, int w, int h)
{
int result, i = ff_dnxhd_get_cid_table(cid);
if (i < 0)
return i;
result = ((h + 15) / 16) * ((w + 15) / 16) * ff_dnxhd_cid_table[i].packet_scale.num / ff_dnxhd_cid_table[i].packet_scale.den;
result = (result + 2048) / 4096 * 4096;
return FFMAX(result, 8192);
}
static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
int interlaced = dctx->interlaced;
int cur_field = dctx->cur_field;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
interlaced = (state&2)>>1; /* byte following the 5-byte header prefix */
cur_field = state&1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
int remaining;
if (cid <= 0)
continue;
remaining = avpriv_dnxhd_get_frame_size(cid);
if (remaining <= 0) {
remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (remaining <= 0)
continue;
}
dctx->remaining = remaining;
if (buf_size - i >= dctx->remaining && (!dctx->interlaced || dctx->cur_field)) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->interlaced = interlaced;
dctx->cur_field = 0;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->interlaced = interlaced;
dctx->cur_field = 0;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
dctx->interlaced = interlaced;
dctx->cur_field = cur_field;
return END_NOT_FOUND;
}
static int dnxhd_parse(AVCodecParserContext *s,
AVCodecContext *avctx,
const uint8_t **poutbuf, int *poutbuf_size,
const uint8_t *buf, int buf_size)
{
DNXHDParserContext *dctx = s->priv_data;
ParseContext *pc = &dctx->pc;
int next;
if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
next = buf_size;
} else {
next = dnxhd_find_frame_end(dctx, buf, buf_size);
if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
*poutbuf = NULL;
*poutbuf_size = 0;
return buf_size;
}
}
*poutbuf = buf;
*poutbuf_size = buf_size;
return next;
}
AVCodecParser ff_dnxhd_parser = {
.codec_ids = { AV_CODEC_ID_DNXHD },
.priv_data_size = sizeof(DNXHDParserContext),
.parser_parse = dnxhd_parse,
.parser_close = ff_parse_close,
};
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3403_0 |
crossvul-cpp_data_bad_4057_0 | /*
* Copyright (C) 2012 Philip Van Hoof <philip@codeminded.be>
* Copyright (C) 2009 Vic Lee.
*
* This 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#ifndef _MSC_VER
#define _XOPEN_SOURCE 500
#endif
#include <rfb/rfbclient.h>
#include <errno.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#ifdef _MSC_VER
typedef CRITICAL_SECTION MUTEX_TYPE;
#define MUTEX_INIT(mutex) InitializeCriticalSection(&mutex)
#define MUTEX_FREE(mutex) DeleteCriticalSection(&mutex)
#define MUTEX_LOCK(mutex) EnterCriticalSection(&mutex)
#define MUTEX_UNLOCK(mutex) LeaveCriticalSection(&mutex)
#define CURRENT_THREAD_ID GetCurrentThreadId()
#else
#include <pthread.h>
typedef pthread_mutex_t MUTEX_TYPE;
#define MUTEX_INIT(mutex) {\
pthread_mutexattr_t mutexAttr;\
pthread_mutexattr_init(&mutexAttr);\
pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE);\
pthread_mutex_init(&mutex, &mutexAttr);\
}
#define MUTEX_FREE(mutex) pthread_mutex_destroy(&mutex)
#define MUTEX_LOCK(mutex) pthread_mutex_lock(&mutex)
#define MUTEX_UNLOCK(mutex) pthread_mutex_unlock(&mutex)
#define CURRENT_THREAD_ID pthread_self()
#endif
#include "tls.h"
#ifdef _MSC_VER
#include <BaseTsd.h> // That's for SSIZE_T
typedef SSIZE_T ssize_t;
#define snprintf _snprintf
#endif
static rfbBool rfbTLSInitialized = FALSE;
static MUTEX_TYPE *mutex_buf = NULL;
struct CRYPTO_dynlock_value {
MUTEX_TYPE mutex;
};
static void locking_function(int mode, int n, const char *file, int line)
{
if (mode & CRYPTO_LOCK)
MUTEX_LOCK(mutex_buf[n]);
else
MUTEX_UNLOCK(mutex_buf[n]);
}
static unsigned long id_function(void)
{
return ((unsigned long) CURRENT_THREAD_ID);
}
static struct CRYPTO_dynlock_value *dyn_create_function(const char *file, int line)
{
struct CRYPTO_dynlock_value *value;
value = (struct CRYPTO_dynlock_value *)
malloc(sizeof(struct CRYPTO_dynlock_value));
if (!value)
goto err;
MUTEX_INIT(value->mutex);
return value;
err:
return (NULL);
}
static void dyn_lock_function (int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)
{
if (mode & CRYPTO_LOCK)
MUTEX_LOCK(l->mutex);
else
MUTEX_UNLOCK(l->mutex);
}
static void
dyn_destroy_function(struct CRYPTO_dynlock_value *l, const char *file, int line)
{
MUTEX_FREE(l->mutex);
free(l);
}
static int
ssl_errno (SSL *ssl, int ret)
{
switch (SSL_get_error (ssl, ret)) {
case SSL_ERROR_NONE:
return 0;
case SSL_ERROR_ZERO_RETURN:
/* this one does not map well at all */
//d(printf ("ssl_errno: SSL_ERROR_ZERO_RETURN\n"));
return EINVAL;
case SSL_ERROR_WANT_READ: /* non-fatal; retry */
case SSL_ERROR_WANT_WRITE: /* non-fatal; retry */
//d(printf ("ssl_errno: SSL_ERROR_WANT_[READ,WRITE]\n"));
return EAGAIN;
case SSL_ERROR_SYSCALL:
//d(printf ("ssl_errno: SSL_ERROR_SYSCALL\n"));
return EINTR;
case SSL_ERROR_SSL:
//d(printf ("ssl_errno: SSL_ERROR_SSL <-- very useful error...riiiiight\n"));
return EINTR;
default:
//d(printf ("ssl_errno: default error\n"));
return EINTR;
}
}
static rfbBool
InitializeTLS(void)
{
int i;
if (rfbTLSInitialized) return TRUE;
mutex_buf = malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
if (mutex_buf == NULL) {
rfbClientLog("Failed to initialized OpenSSL: memory.\n");
return (-1);
}
for (i = 0; i < CRYPTO_num_locks(); i++)
MUTEX_INIT(mutex_buf[i]);
CRYPTO_set_locking_callback(locking_function);
CRYPTO_set_id_callback(id_function);
CRYPTO_set_dynlock_create_callback(dyn_create_function);
CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
RAND_load_file("/dev/urandom", 1024);
rfbClientLog("OpenSSL version %s initialized.\n", SSLeay_version(SSLEAY_VERSION));
rfbTLSInitialized = TRUE;
return TRUE;
}
static int sock_read_ready(SSL *ssl, uint32_t ms)
{
int r = 0;
fd_set fds;
struct timeval tv;
FD_ZERO(&fds);
FD_SET(SSL_get_fd(ssl), &fds);
tv.tv_sec = ms / 1000;
tv.tv_usec = (ms % 1000) * 1000;
r = select (SSL_get_fd(ssl) + 1, &fds, NULL, NULL, &tv);
return r;
}
static int wait_for_data(SSL *ssl, int ret, int timeout)
{
int err;
int retval = 1;
err = SSL_get_error(ssl, ret);
switch(err)
{
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
ret = sock_read_ready(ssl, timeout*1000);
if (ret == -1) {
retval = 2;
}
break;
default:
retval = 3;
long verify_res = SSL_get_verify_result(ssl);
if (verify_res != X509_V_OK)
rfbClientLog("Could not verify server certificate: %s.\n",
X509_verify_cert_error_string(verify_res));
break;
}
ERR_clear_error();
return retval;
}
static rfbBool
load_crls_from_file(char *file, SSL_CTX *ssl_ctx)
{
X509_STORE *st;
X509_CRL *crl;
int i;
int count = 0;
BIO *bio;
STACK_OF(X509_INFO) *xis = NULL;
X509_INFO *xi;
st = SSL_CTX_get_cert_store(ssl_ctx);
int rv = 0;
bio = BIO_new_file(file, "r");
if (bio == NULL)
return FALSE;
xis = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
BIO_free(bio);
for (i = 0; i < sk_X509_INFO_num(xis); i++)
{
xi = sk_X509_INFO_value(xis, i);
if (xi->crl)
{
X509_STORE_add_crl(st, xi->crl);
xi->crl = NULL;
count++;
}
}
sk_X509_INFO_pop_free(xis, X509_INFO_free);
if (count > 0)
return TRUE;
else
return FALSE;
}
static SSL *
open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred)
{
SSL_CTX *ssl_ctx = NULL;
SSL *ssl = NULL;
int n, finished = 0;
X509_VERIFY_PARAM *param;
uint8_t verify_crls = cred->x509Credential.x509CrlVerifyMode;
if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method())))
{
rfbClientLog("Could not create new SSL context.\n");
return NULL;
}
param = X509_VERIFY_PARAM_new();
/* Setup verification if not anonymous */
if (!anonTLS)
{
if (cred->x509Credential.x509CACertFile)
{
if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL))
{
rfbClientLog("Failed to load CA certificate from %s.\n",
cred->x509Credential.x509CACertFile);
goto error_free_ctx;
}
} else {
rfbClientLog("Using default paths for certificate verification.\n");
SSL_CTX_set_default_verify_paths (ssl_ctx);
}
if (cred->x509Credential.x509CACrlFile)
{
if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx))
{
rfbClientLog("CRLs could not be loaded.\n");
goto error_free_ctx;
}
if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll;
}
if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile)
{
if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1)
{
rfbClientLog("Client certificate could not be loaded.\n");
goto error_free_ctx;
}
if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile,
SSL_FILETYPE_PEM) != 1)
{
rfbClientLog("Client private key could not be loaded.\n");
goto error_free_ctx;
}
if (SSL_CTX_check_private_key(ssl_ctx) == 0) {
rfbClientLog("Client certificate and private key do not match.\n");
goto error_free_ctx;
}
}
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
if (verify_crls == rfbX509CrlVerifyClient)
X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
else if (verify_crls == rfbX509CrlVerifyAll)
X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost)))
{
rfbClientLog("Could not set server name for verification.\n");
goto error_free_ctx;
}
SSL_CTX_set1_param(ssl_ctx, param);
}
if (!(ssl = SSL_new (ssl_ctx)))
{
rfbClientLog("Could not create a new SSL session.\n");
goto error_free_ctx;
}
/* TODO: finetune this list, take into account anonTLS bool */
SSL_set_cipher_list(ssl, "ALL");
SSL_set_fd (ssl, sockfd);
SSL_CTX_set_app_data (ssl_ctx, client);
do
{
n = SSL_connect(ssl);
if (n != 1)
{
if (wait_for_data(ssl, n, 1) != 1)
{
finished = 1;
SSL_shutdown(ssl);
goto error_free_ssl;
}
}
} while( n != 1 && finished != 1 );
X509_VERIFY_PARAM_free(param);
return ssl;
error_free_ssl:
SSL_free(ssl);
error_free_ctx:
X509_VERIFY_PARAM_free(param);
SSL_CTX_free(ssl_ctx);
return NULL;
}
static rfbBool
InitializeTLSSession(rfbClient* client, rfbBool anonTLS, rfbCredential *cred)
{
if (client->tlsSession) return TRUE;
client->tlsSession = open_ssl_connection (client, client->sock, anonTLS, cred);
if (!client->tlsSession)
return FALSE;
rfbClientLog("TLS session initialized.\n");
return TRUE;
}
static rfbBool
HandshakeTLS(rfbClient* client)
{
int timeout = 15;
int ret;
return TRUE;
while (timeout > 0 && (ret = SSL_do_handshake(client->tlsSession)) < 0)
{
if (ret != -1)
{
rfbClientLog("TLS handshake blocking.\n");
#ifdef WIN32
Sleep(1000);
#else
sleep(1);
#endif
timeout--;
continue;
}
rfbClientLog("TLS handshake failed.\n");
FreeTLS(client);
return FALSE;
}
if (timeout <= 0)
{
rfbClientLog("TLS handshake timeout.\n");
FreeTLS(client);
return FALSE;
}
rfbClientLog("TLS handshake done.\n");
return TRUE;
}
/* VeNCrypt sub auth. 1 byte auth count, followed by count * 4 byte integers */
static rfbBool
ReadVeNCryptSecurityType(rfbClient* client, uint32_t *result)
{
uint8_t count=0;
uint8_t loop=0;
uint8_t flag=0;
uint32_t tAuth[256], t;
char buf1[500],buf2[10];
uint32_t authScheme;
if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE;
if (count==0)
{
rfbClientLog("List of security types is ZERO. Giving up.\n");
return FALSE;
}
rfbClientLog("We have %d security types to read\n", count);
authScheme=0;
/* now, we have a list of available security types to read ( uint8_t[] ) */
for (loop=0;loop<count;loop++)
{
if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 4)) return FALSE;
t=rfbClientSwap32IfLE(tAuth[loop]);
rfbClientLog("%d) Received security type %d\n", loop, t);
if (flag) continue;
if (t==rfbVeNCryptTLSNone ||
t==rfbVeNCryptTLSVNC ||
t==rfbVeNCryptTLSPlain ||
#ifdef LIBVNCSERVER_HAVE_SASL
t==rfbVeNCryptTLSSASL ||
t==rfbVeNCryptX509SASL ||
#endif /*LIBVNCSERVER_HAVE_SASL */
t==rfbVeNCryptX509None ||
t==rfbVeNCryptX509VNC ||
t==rfbVeNCryptX509Plain)
{
flag++;
authScheme=t;
rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count);
/* send back 4 bytes (in original byte order!) indicating which security type to use */
if (!WriteToRFBServer(client, (char *)&tAuth[loop], 4)) return FALSE;
}
tAuth[loop]=t;
}
if (authScheme==0)
{
memset(buf1, 0, sizeof(buf1));
for (loop=0;loop<count;loop++)
{
if (strlen(buf1)>=sizeof(buf1)-1) break;
snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]);
strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1);
}
rfbClientLog("Unknown VeNCrypt authentication scheme from VNC server: %s\n",
buf1);
return FALSE;
}
*result = authScheme;
return TRUE;
}
rfbBool
HandleAnonTLSAuth(rfbClient* client)
{
if (!InitializeTLS() || !InitializeTLSSession(client, TRUE, NULL)) return FALSE;
if (!HandshakeTLS(client)) return FALSE;
return TRUE;
}
static void
FreeX509Credential(rfbCredential *cred)
{
if (cred->x509Credential.x509CACertFile) free(cred->x509Credential.x509CACertFile);
if (cred->x509Credential.x509CACrlFile) free(cred->x509Credential.x509CACrlFile);
if (cred->x509Credential.x509ClientCertFile) free(cred->x509Credential.x509ClientCertFile);
if (cred->x509Credential.x509ClientKeyFile) free(cred->x509Credential.x509ClientKeyFile);
free(cred);
}
rfbBool
HandleVeNCryptAuth(rfbClient* client)
{
uint8_t major, minor, status;
uint32_t authScheme;
rfbBool anonTLS;
rfbCredential *cred = NULL;
rfbBool result = TRUE;
if (!InitializeTLS()) return FALSE;
/* Read VeNCrypt version */
if (!ReadFromRFBServer(client, (char *)&major, 1) ||
!ReadFromRFBServer(client, (char *)&minor, 1))
{
return FALSE;
}
rfbClientLog("Got VeNCrypt version %d.%d from server.\n", (int)major, (int)minor);
if (major != 0 && minor != 2)
{
rfbClientLog("Unsupported VeNCrypt version.\n");
return FALSE;
}
if (!WriteToRFBServer(client, (char *)&major, 1) ||
!WriteToRFBServer(client, (char *)&minor, 1) ||
!ReadFromRFBServer(client, (char *)&status, 1))
{
return FALSE;
}
if (status != 0)
{
rfbClientLog("Server refused VeNCrypt version %d.%d.\n", (int)major, (int)minor);
return FALSE;
}
if (!ReadVeNCryptSecurityType(client, &authScheme)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&status, 1) || status != 1)
{
rfbClientLog("Server refused VeNCrypt authentication %d (%d).\n", authScheme, (int)status);
return FALSE;
}
client->subAuthScheme = authScheme;
/* Some VeNCrypt security types are anonymous TLS, others are X509 */
switch (authScheme)
{
case rfbVeNCryptTLSNone:
case rfbVeNCryptTLSVNC:
case rfbVeNCryptTLSPlain:
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbVeNCryptTLSSASL:
#endif /* LIBVNCSERVER_HAVE_SASL */
anonTLS = TRUE;
break;
default:
anonTLS = FALSE;
break;
}
/* Get X509 Credentials if it's not anonymous */
if (!anonTLS)
{
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
cred = client->GetCredential(client, rfbCredentialTypeX509);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
}
/* Start up the TLS session */
if (!InitializeTLSSession(client, anonTLS, cred)) result = FALSE;
if (!HandshakeTLS(client)) result = FALSE;
/* We are done here. The caller should continue with client->subAuthScheme
* to do actual sub authentication.
*/
if (cred) FreeX509Credential(cred);
return result;
}
int
ReadFromTLS(rfbClient* client, char *out, unsigned int n)
{
ssize_t ret;
ret = SSL_read (client->tlsSession, out, n);
if (ret >= 0)
return ret;
else {
errno = ssl_errno (client->tlsSession, ret);
if (errno != EAGAIN) {
rfbClientLog("Error reading from TLS: -.\n");
}
}
return -1;
}
int
WriteToTLS(rfbClient* client, const char *buf, unsigned int n)
{
unsigned int offset = 0;
ssize_t ret;
while (offset < n)
{
ret = SSL_write (client->tlsSession, buf + offset, (size_t)(n-offset));
if (ret < 0)
errno = ssl_errno (client->tlsSession, ret);
if (ret == 0) continue;
if (ret < 0)
{
if (errno == EAGAIN || errno == EWOULDBLOCK) continue;
rfbClientLog("Error writing to TLS: -\n");
return -1;
}
offset += (unsigned int)ret;
}
return offset;
}
void FreeTLS(rfbClient* client)
{
int i;
if (mutex_buf != NULL) {
CRYPTO_set_dynlock_create_callback(NULL);
CRYPTO_set_dynlock_lock_callback(NULL);
CRYPTO_set_dynlock_destroy_callback(NULL);
CRYPTO_set_locking_callback(NULL);
CRYPTO_set_id_callback(NULL);
for (i = 0; i < CRYPTO_num_locks(); i++)
MUTEX_FREE(mutex_buf[i]);
free(mutex_buf);
mutex_buf = NULL;
}
SSL_free(client->tlsSession);
}
#ifdef LIBVNCSERVER_HAVE_SASL
int GetTLSCipherBits(rfbClient* client)
{
SSL *ssl = (SSL *)(client->tlsSession);
const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
return SSL_CIPHER_get_bits(cipher, NULL);
}
#endif /* LIBVNCSERVER_HAVE_SASL */
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_4057_0 |
crossvul-cpp_data_good_4042_1 | /*******************************************************************************
*
* Copyright (c) 2000-2003 Intel Corporation
* All rights reserved.
* Copyright (c) 2012 France Telecom 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 name of Intel Corporation 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 INTEL 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.
*
******************************************************************************/
/************************************************************************
* Purpose: This file defines the functions for services. It defines
* functions for adding and removing services to and from the service table,
* adding and accessing subscription and other attributes pertaining to the
* service
************************************************************************/
#include "service_table.h"
#include "config.h"
#ifdef INCLUDE_DEVICE_APIS
#if EXCLUDE_GENA == 0
/************************************************************************
* Function : copy_subscription
*
* Parameters :
* subscription *in ; Source subscription
* subscription *out ; Destination subscription
*
* Description : Makes a copy of the subscription
*
* Return : int ;
* HTTP_SUCCESS - On success
*
* Note :
************************************************************************/
int copy_subscription(subscription *in, subscription *out)
{
int return_code = HTTP_SUCCESS;
memcpy(out->sid, in->sid, SID_SIZE);
out->sid[SID_SIZE] = 0;
out->ToSendEventKey = in->ToSendEventKey;
out->expireTime = in->expireTime;
out->active = in->active;
return_code = copy_URL_list(&in->DeliveryURLs, &out->DeliveryURLs);
if (return_code != HTTP_SUCCESS) {
return return_code;
}
ListInit(&out->outgoing, 0, 0);
out->next = NULL;
return HTTP_SUCCESS;
}
/************************************************************************
* Function : RemoveSubscriptionSID
*
* Parameters :
* Upnp_SID sid ; subscription ID
* service_info * service ; service object providing the
*list of subscriptions
*
* Description : Remove the subscription represented by the
* const Upnp_SID sid parameter from the service table and update
* the service table.
*
* Return : void ;
*
* Note :
************************************************************************/
void RemoveSubscriptionSID(Upnp_SID sid, service_info *service)
{
subscription *finger = service->subscriptionList;
subscription *previous = NULL;
while (finger) {
if (!strcmp(sid, finger->sid)) {
if (previous) {
previous->next = finger->next;
} else {
service->subscriptionList = finger->next;
}
finger->next = NULL;
freeSubscriptionList(finger);
finger = NULL;
service->TotalSubscriptions--;
} else {
previous = finger;
finger = finger->next;
}
}
}
subscription *GetSubscriptionSID(const Upnp_SID sid, service_info *service)
{
subscription *next = service->subscriptionList;
subscription *previous = NULL;
subscription *found = NULL;
time_t current_time;
while (next && !found) {
if (!strcmp(next->sid, sid))
found = next;
else {
previous = next;
next = next->next;
}
}
if (found) {
/* get the current_time */
time(¤t_time);
if (found->expireTime && found->expireTime < current_time) {
if (previous) {
previous->next = found->next;
} else {
service->subscriptionList = found->next;
}
found->next = NULL;
freeSubscriptionList(found);
found = NULL;
service->TotalSubscriptions--;
}
}
return found;
}
subscription *GetNextSubscription(service_info *service, subscription *current)
{
time_t current_time;
subscription *next = NULL;
subscription *previous = NULL;
int notDone = 1;
/* get the current_time */
time(¤t_time);
while (notDone && current) {
previous = current;
current = current->next;
if (!current) {
notDone = 0;
next = current;
} else if (current->expireTime &&
current->expireTime < current_time) {
previous->next = current->next;
current->next = NULL;
freeSubscriptionList(current);
current = previous;
service->TotalSubscriptions--;
} else if (current->active) {
notDone = 0;
next = current;
}
}
return next;
}
subscription *GetFirstSubscription(service_info *service)
{
subscription temp;
subscription *next = NULL;
temp.next = service->subscriptionList;
next = GetNextSubscription(service, &temp);
service->subscriptionList = temp.next;
/* service->subscriptionList = next; */
return next;
}
void freeSubscription(subscription *sub)
{
if (sub) {
free_URL_list(&sub->DeliveryURLs);
freeSubscriptionQueuedEvents(sub);
}
}
/************************************************************************
* Function : freeSubscriptionList
*
* Parameters :
* subscription * head ; head of the subscription list
*
* Description : Free's memory allocated for all the subscriptions
* in the service table.
*
* Return : void ;
*
* Note :
************************************************************************/
void freeSubscriptionList(subscription *head)
{
subscription *next = NULL;
while (head) {
next = head->next;
freeSubscription(head);
free(head);
head = next;
}
}
/*******************************************************************************
* Function : FindServiceId
*
* Parameters :
* service_table *table; service table
* const char *serviceId; string representing the service id to be found
* among those in the
* table const char *UDN; string representing the UDN to be found among those
* in the table
*
* Description: Traverses through the service table and returns a pointer to the
* service node that matches a known service id and a known UDN.
*
* Return:
* service_info *: pointer to the matching service_info node.
******************************************************************************/
service_info *FindServiceId(
service_table *table, const char *serviceId, const char *UDN)
{
service_info *finger = NULL;
if (table) {
finger = table->serviceList;
while (finger) {
if (!strcmp(serviceId, finger->serviceId) &&
!strcmp(UDN, finger->UDN)) {
return finger;
}
finger = finger->next;
}
}
return NULL;
}
/************************************************************************
* Function : FindServiceEventURLPath
*
* Parameters :
* service_table *table ; service table
* char * eventURLPath ; event URL path used to find a service
* from the table
*
* Description : Traverses the service table and finds the node whose
* event URL Path matches a know value
*
* Return : service_info * - pointer to the service list node from the
* service table whose event URL matches a known event URL;
*
* Note :
************************************************************************/
service_info *FindServiceEventURLPath(
service_table *table, const char *eventURLPath)
{
service_info *finger = NULL;
uri_type parsed_url;
uri_type parsed_url_in;
if (!table || !eventURLPath) {
return NULL;
}
if (parse_uri(eventURLPath, strlen(eventURLPath), &parsed_url_in) ==
HTTP_SUCCESS) {
finger = table->serviceList;
while (finger) {
if (finger->eventURL) {
if (parse_uri(finger->eventURL,
strlen(finger->eventURL),
&parsed_url) == HTTP_SUCCESS) {
if (!token_cmp(&parsed_url.pathquery,
&parsed_url_in.pathquery)) {
return finger;
}
}
}
finger = finger->next;
}
}
return NULL;
}
#endif /* EXCLUDE_GENA */
/***********************************************************************
* Function: FindServiceControlURLPath
*
* Parameters:
* service_table *table; service table
* char *controlURLPath; control URL path used to find a service from
* the table
*
* Description: Traverses the service table and finds the node whose
* control URL Path matches a know value
*
* Return: service_info *: pointer to the service list node from the
* service table whose control URL Path matches a known value.
**********************************************************************/
#if EXCLUDE_SOAP == 0
service_info *FindServiceControlURLPath(
service_table *table, const char *controlURLPath)
{
service_info *finger = NULL;
uri_type parsed_url;
uri_type parsed_url_in;
if (!table || !controlURLPath) {
return NULL;
}
if (parse_uri(controlURLPath, strlen(controlURLPath), &parsed_url_in) ==
HTTP_SUCCESS) {
finger = table->serviceList;
while (finger) {
if (finger->controlURL) {
if (parse_uri(finger->controlURL,
strlen(finger->controlURL),
&parsed_url) == HTTP_SUCCESS) {
if (!token_cmp(&parsed_url.pathquery,
&parsed_url_in.pathquery)) {
return finger;
}
}
}
finger = finger->next;
}
}
return NULL;
}
#endif /* EXCLUDE_SOAP */
/***********************************************************************
* Function: printService
*
* Parameters:
* service_info *service; Service whose information is to be printed
* Upnp_LogLevel level; Debug level specified to the print function
* Dbg_Module module; Debug module specified to the print function
*
* Description: For debugging purposes prints information from the
* service passed into the function.
*
* Return: void
**********************************************************************/
#ifdef DEBUG
void printService(service_info *service, Upnp_LogLevel level, Dbg_Module module)
{
if (service) {
if (service->serviceType) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"serviceType: %s\n",
service->serviceType);
}
if (service->serviceId) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"serviceId: %s\n",
service->serviceId);
}
if (service->SCPDURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"SCPDURL: %s\n",
service->SCPDURL);
}
if (service->controlURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"controlURL: %s\n",
service->controlURL);
}
if (service->eventURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"eventURL: %s\n",
service->eventURL);
}
if (service->UDN) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"UDN: %s\n\n",
service->UDN);
}
if (service->active) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"Service is active\n");
} else {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"Service is inactive\n");
}
}
}
#endif
/************************************************************************
* Function: printServiceList
*
* Parameters:
* service_info *service; Service whose information is to be printed
* Upnp_LogLevel level; Debug level specified to the print function
* Dbg_Module module; Debug module specified to the print function
*
* Description: For debugging purposes prints information of each
* service from the service table passed into the function.
*
* Return: void
************************************************************************/
#ifdef DEBUG
void printServiceList(
service_info *service, Upnp_LogLevel level, Dbg_Module module)
{
while (service) {
if (service->serviceType) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"serviceType: %s\n",
service->serviceType);
}
if (service->serviceId) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"serviceId: %s\n",
service->serviceId);
}
if (service->SCPDURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"SCPDURL: %s\n",
service->SCPDURL);
}
if (service->controlURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"controlURL: %s\n",
service->controlURL);
}
if (service->eventURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"eventURL: %s\n",
service->eventURL);
}
if (service->UDN) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"UDN: %s\n\n",
service->UDN);
}
if (service->active) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"Service is active\n");
} else {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"Service is inactive\n");
}
service = service->next;
}
}
#endif
/************************************************************************
* Function: printServiceTable
*
* Parameters:
* service_table *table; Service table to be printed
* Upnp_LogLevel level; Debug level specified to the print function
* Dbg_Module module; Debug module specified to the print function
*
* Description: For debugging purposes prints the URL base of the table
* and information of each service from the service table passed into
* the function.
*
* Return: void
************************************************************************/
#ifdef DEBUG
void printServiceTable(
service_table *table, Upnp_LogLevel level, Dbg_Module module)
{
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"URL_BASE: %s\n",
table->URLBase);
UpnpPrintf(level, module, __FILE__, __LINE__, "Services: \n");
printServiceList(table->serviceList, level, module);
}
#endif
#if EXCLUDE_GENA == 0
/************************************************************************
* Function : freeService
*
* Parameters :
* service_info *in ; service information that is to be freed
*
* Description : Free's memory allocated for the various components
* of the service entry in the service table.
*
* Return : void ;
*
* Note :
************************************************************************/
void freeService(service_info *in)
{
if (in) {
if (in->serviceType)
ixmlFreeDOMString(in->serviceType);
if (in->serviceId)
ixmlFreeDOMString(in->serviceId);
if (in->SCPDURL)
free(in->SCPDURL);
if (in->controlURL)
free(in->controlURL);
if (in->eventURL)
free(in->eventURL);
if (in->UDN)
ixmlFreeDOMString(in->UDN);
if (in->subscriptionList)
freeSubscriptionList(in->subscriptionList);
in->TotalSubscriptions = 0;
free(in);
}
}
/************************************************************************
* Function : freeServiceList
*
* Parameters :
* service_info * head ; Head of the service list to be freed
*
* Description : Free's memory allocated for the various components
* of each service entry in the service table.
*
* Return : void ;
*
* Note :
************************************************************************/
void freeServiceList(service_info *head)
{
service_info *next = NULL;
while (head) {
if (head->serviceType)
ixmlFreeDOMString(head->serviceType);
if (head->serviceId)
ixmlFreeDOMString(head->serviceId);
if (head->SCPDURL)
free(head->SCPDURL);
if (head->controlURL)
free(head->controlURL);
if (head->eventURL)
free(head->eventURL);
if (head->UDN)
ixmlFreeDOMString(head->UDN);
if (head->subscriptionList)
freeSubscriptionList(head->subscriptionList);
head->TotalSubscriptions = 0;
next = head->next;
free(head);
head = next;
}
}
/************************************************************************
* Function : freeServiceTable
*
* Parameters :
* service_table * table ; Service table whose memory needs to be
* freed
*
* Description : Free's dynamic memory in table.
* (does not free table, only memory within the structure)
*
* Return : void ;
*
* Note :
************************************************************************/
void freeServiceTable(service_table *table)
{
ixmlFreeDOMString(table->URLBase);
freeServiceList(table->serviceList);
table->serviceList = NULL;
table->endServiceList = NULL;
}
/*******************************************************************************
* Function: getElementValue
*
* Parameters:
* IXML_Node *node; Input node which provides the list of child nodes
*
* Description: Returns the clone of the element value
*
* Return: DOMString
*
* Note: value must be freed with DOMString_free
******************************************************************************/
DOMString getElementValue(IXML_Node *node)
{
IXML_Node *child = (IXML_Node *)ixmlNode_getFirstChild(node);
const DOMString temp = NULL;
if (child && ixmlNode_getNodeType(child) == eTEXT_NODE) {
temp = ixmlNode_getNodeValue(child);
return ixmlCloneDOMString(temp);
} else {
return NULL;
}
}
/*******************************************************************************
* Function: getSubElement
*
* Parameters:
* const char *element_name; sub element name to be searched for
* IXML_Node *node; Input node which provides the list of child nodes
* IXML_Node **out; Ouput node to which the matched child node is
* returned.
*
* Description: Traverses through a list of XML nodes to find the node with the
* known element name.
*
* Return: int
* 1 - On Success
* 0 - On Failure
******************************************************************************/
int getSubElement(const char *element_name, IXML_Node *node, IXML_Node **out)
{
const DOMString NodeName = NULL;
int found = 0;
IXML_Node *child = (IXML_Node *)ixmlNode_getFirstChild(node);
(*out) = NULL;
while (child && !found) {
switch (ixmlNode_getNodeType(child)) {
case eELEMENT_NODE:
NodeName = ixmlNode_getNodeName(child);
if (!strcmp(NodeName, element_name)) {
(*out) = child;
found = 1;
return found;
}
break;
default:
break;
}
child = (IXML_Node *)ixmlNode_getNextSibling(child);
}
return found;
}
/*******************************************************************************
* Function: getServiceList
*
* Parameters:
* IXML_Node *node; XML node information
* service_info **end; service added is returned to the output parameter
* char *URLBase; provides Base URL to resolve relative URL
*
* Description: Returns pointer to service info after getting the sub-elements
* of the service info.
*
* Return: service_info *: pointer to the service info node
******************************************************************************/
service_info *getServiceList(IXML_Node *node, service_info **end, char *URLBase)
{
IXML_Node *serviceList = NULL;
IXML_Node *current_service = NULL;
IXML_Node *UDN = NULL;
IXML_Node *serviceType = NULL;
IXML_Node *serviceId = NULL;
IXML_Node *SCPDURL = NULL;
IXML_Node *controlURL = NULL;
IXML_Node *eventURL = NULL;
DOMString tempDOMString = NULL;
service_info *head = NULL;
service_info *current = NULL;
service_info *previous = NULL;
IXML_NodeList *serviceNodeList = NULL;
long unsigned int NumOfServices = 0lu;
long unsigned int i = 0lu;
int fail = 0;
if (getSubElement("UDN", node, &UDN) &&
getSubElement("serviceList", node, &serviceList)) {
serviceNodeList = ixmlElement_getElementsByTagName(
(IXML_Element *)serviceList, "service");
if (serviceNodeList) {
NumOfServices = ixmlNodeList_length(serviceNodeList);
for (i = 0lu; i < NumOfServices; i++) {
current_service =
ixmlNodeList_item(serviceNodeList, i);
fail = 0;
if (current) {
current->next =
malloc(sizeof(service_info));
previous = current;
current = current->next;
} else {
head = malloc(sizeof(service_info));
current = head;
}
if (!current) {
freeServiceList(head);
ixmlNodeList_free(serviceNodeList);
return NULL;
}
current->next = NULL;
current->controlURL = NULL;
current->eventURL = NULL;
current->serviceType = NULL;
current->serviceId = NULL;
current->SCPDURL = NULL;
current->active = 1;
current->subscriptionList = NULL;
current->TotalSubscriptions = 0;
if (!(current->UDN = getElementValue(UDN)))
fail = 1;
if (!getSubElement("serviceType",
current_service,
&serviceType) ||
!(current->serviceType =
getElementValue(
serviceType)))
fail = 1;
if (!getSubElement("serviceId",
current_service,
&serviceId) ||
!(current->serviceId = getElementValue(
serviceId)))
fail = 1;
if (!getSubElement("SCPDURL",
current_service,
&SCPDURL) ||
!(tempDOMString = getElementValue(
SCPDURL)) ||
!(current->SCPDURL = resolve_rel_url(
URLBase, tempDOMString)))
fail = 1;
ixmlFreeDOMString(tempDOMString);
tempDOMString = NULL;
if (!(getSubElement("controlURL",
current_service,
&controlURL)) ||
!(tempDOMString = getElementValue(
controlURL)) ||
!(current->controlURL = resolve_rel_url(
URLBase, tempDOMString))) {
UpnpPrintf(UPNP_INFO,
GENA,
__FILE__,
__LINE__,
"BAD OR MISSING CONTROL URL");
UpnpPrintf(UPNP_INFO,
GENA,
__FILE__,
__LINE__,
"CONTROL URL SET TO NULL IN "
"SERVICE INFO");
current->controlURL = NULL;
fail = 0;
}
ixmlFreeDOMString(tempDOMString);
tempDOMString = NULL;
if (!getSubElement("eventSubURL",
current_service,
&eventURL) ||
!(tempDOMString = getElementValue(
eventURL)) ||
!(current->eventURL = resolve_rel_url(
URLBase, tempDOMString))) {
UpnpPrintf(UPNP_INFO,
GENA,
__FILE__,
__LINE__,
"BAD OR MISSING EVENT URL");
UpnpPrintf(UPNP_INFO,
GENA,
__FILE__,
__LINE__,
"EVENT URL SET TO NULL IN "
"SERVICE INFO");
current->eventURL = NULL;
fail = 0;
}
ixmlFreeDOMString(tempDOMString);
tempDOMString = NULL;
if (fail) {
freeServiceList(current);
if (previous)
previous->next = NULL;
else
head = NULL;
current = previous;
}
}
ixmlNodeList_free(serviceNodeList);
}
(*end) = current;
return head;
} else {
(*end) = NULL;
return NULL;
}
}
/*******************************************************************************
* Function: getAllServiceList
*
* Parameters:
* IXML_Node *node; XML node information
* char *URLBase; provides Base URL to resolve relative URL
* service_info **out_end; service added is returned to the output parameter
*
* Description: Returns pointer to service info after getting the sub-elements
* of the service info.
*
* Return: service_info *
******************************************************************************/
service_info *getAllServiceList(
IXML_Node *node, char *URLBase, service_info **out_end)
{
service_info *head = NULL;
service_info *end = NULL;
service_info *next_end = NULL;
IXML_NodeList *deviceList = NULL;
IXML_Node *currentDevice = NULL;
long unsigned int NumOfDevices = 0lu;
long unsigned int i = 0lu;
(*out_end) = NULL;
deviceList = ixmlElement_getElementsByTagName(
(IXML_Element *)node, "device");
if (deviceList) {
NumOfDevices = ixmlNodeList_length(deviceList);
for (i = 0lu; i < NumOfDevices; i++) {
currentDevice = ixmlNodeList_item(deviceList, i);
if (head) {
end->next = getServiceList(
currentDevice, &next_end, URLBase);
if (next_end)
end = next_end;
} else {
head = getServiceList(
currentDevice, &end, URLBase);
}
}
ixmlNodeList_free(deviceList);
}
(*out_end) = end;
return head;
}
/*******************************************************************************
* Function: removeServiceTable
*
* Parameters:
* IXML_Node *node ; XML node information
* service_table *in; service table from which services will be removed
*
* Description: This function assumes that services for a particular root device
* are placed linearly in the service table, and in the order in which they
* are found in the description document all services for this root device
* are removed from the list
*
* Return: int
******************************************************************************/
int removeServiceTable(IXML_Node *node, service_table *in)
{
IXML_Node *root = NULL;
IXML_Node *currentUDN = NULL;
DOMString UDN = NULL;
IXML_NodeList *deviceList = NULL;
service_info *current_service = NULL;
service_info *start_search = NULL;
service_info *prev_service = NULL;
long unsigned int NumOfDevices = 0lu;
long unsigned int i = 0lu;
if (getSubElement("root", node, &root)) {
start_search = in->serviceList;
deviceList = ixmlElement_getElementsByTagName(
(IXML_Element *)root, "device");
if (deviceList) {
NumOfDevices = ixmlNodeList_length(deviceList);
for (i = 0lu; i < NumOfDevices; i++) {
if ((start_search) &&
((getSubElement(
"UDN", node, ¤tUDN)) &&
(UDN = getElementValue(
currentUDN)))) {
current_service = start_search;
/* Services are put in the service table
* in the order in which they appear in
* the description document, therefore
* we go through the list only once to
* remove a particular root device */
while ((current_service) &&
(strcmp(current_service->UDN,
UDN))) {
current_service =
current_service->next;
if (current_service != NULL)
prev_service =
current_service
->next;
}
while ((current_service) &&
(!strcmp(current_service->UDN,
UDN))) {
if (prev_service) {
prev_service->next =
current_service
->next;
} else {
in->serviceList =
current_service
->next;
}
if (current_service ==
in->endServiceList)
in->endServiceList =
prev_service;
start_search =
current_service->next;
freeService(current_service);
current_service = start_search;
}
ixmlFreeDOMString(UDN);
UDN = NULL;
}
}
ixmlNodeList_free(deviceList);
}
}
return 1;
}
/*******************************************************************************
* Function: addServiceTable
*
* Parameters :
* IXML_Node *node; XML node information
* service_table *in; service table that will be initialized with
* services
* const char *DefaultURLBase; Default base URL on which the URL will be
* returned to the service list.
*
* Description: Add Service to the table.
*
* Return: int
******************************************************************************/
int addServiceTable(
IXML_Node *node, service_table *in, const char *DefaultURLBase)
{
IXML_Node *root = NULL;
IXML_Node *URLBase = NULL;
service_info *tempEnd = NULL;
if (in->URLBase) {
free(in->URLBase);
in->URLBase = NULL;
}
if (getSubElement("root", node, &root)) {
if (getSubElement("URLBase", root, &URLBase)) {
in->URLBase = getElementValue(URLBase);
} else {
if (DefaultURLBase) {
in->URLBase =
ixmlCloneDOMString(DefaultURLBase);
} else {
in->URLBase = ixmlCloneDOMString("");
}
}
if ((in->endServiceList->next = getAllServiceList(
root, in->URLBase, &tempEnd))) {
in->endServiceList = tempEnd;
return 1;
}
}
return 0;
}
/************************************************************************
* Function : getServiceTable
*
* Parameters :
* IXML_Node *node ; XML node information
* service_table *out ; output parameter which will contain the
* service list and URL
* const char *DefaultURLBase ; Default base URL on which the URL
* will be returned.
*
* Description : Retrieve service from the table
*
* Return : int ;
*
* Note :
************************************************************************/
int getServiceTable(
IXML_Node *node, service_table *out, const char *DefaultURLBase)
{
IXML_Node *root = NULL;
IXML_Node *URLBase = NULL;
if (getSubElement("root", node, &root)) {
if (getSubElement("URLBase", root, &URLBase)) {
out->URLBase = getElementValue(URLBase);
} else {
if (DefaultURLBase) {
out->URLBase =
ixmlCloneDOMString(DefaultURLBase);
} else {
out->URLBase = ixmlCloneDOMString("");
}
}
out->serviceList = getAllServiceList(
root, out->URLBase, &out->endServiceList);
if (out->serviceList) {
return 1;
}
}
return 0;
}
#endif /* EXCLUDE_GENA */
#endif /* INCLUDE_DEVICE_APIS */
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_4042_1 |
crossvul-cpp_data_bad_213_0 | // SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* Copyright (c) 2013 Red Hat, Inc.
* All Rights Reserved.
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_shared.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_bit.h"
#include "xfs_sb.h"
#include "xfs_mount.h"
#include "xfs_da_format.h"
#include "xfs_da_btree.h"
#include "xfs_inode.h"
#include "xfs_trans.h"
#include "xfs_inode_item.h"
#include "xfs_bmap_btree.h"
#include "xfs_bmap.h"
#include "xfs_attr_sf.h"
#include "xfs_attr_remote.h"
#include "xfs_attr.h"
#include "xfs_attr_leaf.h"
#include "xfs_error.h"
#include "xfs_trace.h"
#include "xfs_buf_item.h"
#include "xfs_cksum.h"
#include "xfs_dir2.h"
#include "xfs_log.h"
/*
* xfs_attr_leaf.c
*
* Routines to implement leaf blocks of attributes as Btrees of hashed names.
*/
/*========================================================================
* Function prototypes for the kernel.
*========================================================================*/
/*
* Routines used for growing the Btree.
*/
STATIC int xfs_attr3_leaf_create(struct xfs_da_args *args,
xfs_dablk_t which_block, struct xfs_buf **bpp);
STATIC int xfs_attr3_leaf_add_work(struct xfs_buf *leaf_buffer,
struct xfs_attr3_icleaf_hdr *ichdr,
struct xfs_da_args *args, int freemap_index);
STATIC void xfs_attr3_leaf_compact(struct xfs_da_args *args,
struct xfs_attr3_icleaf_hdr *ichdr,
struct xfs_buf *leaf_buffer);
STATIC void xfs_attr3_leaf_rebalance(xfs_da_state_t *state,
xfs_da_state_blk_t *blk1,
xfs_da_state_blk_t *blk2);
STATIC int xfs_attr3_leaf_figure_balance(xfs_da_state_t *state,
xfs_da_state_blk_t *leaf_blk_1,
struct xfs_attr3_icleaf_hdr *ichdr1,
xfs_da_state_blk_t *leaf_blk_2,
struct xfs_attr3_icleaf_hdr *ichdr2,
int *number_entries_in_blk1,
int *number_usedbytes_in_blk1);
/*
* Utility routines.
*/
STATIC void xfs_attr3_leaf_moveents(struct xfs_da_args *args,
struct xfs_attr_leafblock *src_leaf,
struct xfs_attr3_icleaf_hdr *src_ichdr, int src_start,
struct xfs_attr_leafblock *dst_leaf,
struct xfs_attr3_icleaf_hdr *dst_ichdr, int dst_start,
int move_count);
STATIC int xfs_attr_leaf_entsize(xfs_attr_leafblock_t *leaf, int index);
/*
* attr3 block 'firstused' conversion helpers.
*
* firstused refers to the offset of the first used byte of the nameval region
* of an attr leaf block. The region starts at the tail of the block and expands
* backwards towards the middle. As such, firstused is initialized to the block
* size for an empty leaf block and is reduced from there.
*
* The attr3 block size is pegged to the fsb size and the maximum fsb is 64k.
* The in-core firstused field is 32-bit and thus supports the maximum fsb size.
* The on-disk field is only 16-bit, however, and overflows at 64k. Since this
* only occurs at exactly 64k, we use zero as a magic on-disk value to represent
* the attr block size. The following helpers manage the conversion between the
* in-core and on-disk formats.
*/
static void
xfs_attr3_leaf_firstused_from_disk(
struct xfs_da_geometry *geo,
struct xfs_attr3_icleaf_hdr *to,
struct xfs_attr_leafblock *from)
{
struct xfs_attr3_leaf_hdr *hdr3;
if (from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC)) {
hdr3 = (struct xfs_attr3_leaf_hdr *) from;
to->firstused = be16_to_cpu(hdr3->firstused);
} else {
to->firstused = be16_to_cpu(from->hdr.firstused);
}
/*
* Convert from the magic fsb size value to actual blocksize. This
* should only occur for empty blocks when the block size overflows
* 16-bits.
*/
if (to->firstused == XFS_ATTR3_LEAF_NULLOFF) {
ASSERT(!to->count && !to->usedbytes);
ASSERT(geo->blksize > USHRT_MAX);
to->firstused = geo->blksize;
}
}
static void
xfs_attr3_leaf_firstused_to_disk(
struct xfs_da_geometry *geo,
struct xfs_attr_leafblock *to,
struct xfs_attr3_icleaf_hdr *from)
{
struct xfs_attr3_leaf_hdr *hdr3;
uint32_t firstused;
/* magic value should only be seen on disk */
ASSERT(from->firstused != XFS_ATTR3_LEAF_NULLOFF);
/*
* Scale down the 32-bit in-core firstused value to the 16-bit on-disk
* value. This only overflows at the max supported value of 64k. Use the
* magic on-disk value to represent block size in this case.
*/
firstused = from->firstused;
if (firstused > USHRT_MAX) {
ASSERT(from->firstused == geo->blksize);
firstused = XFS_ATTR3_LEAF_NULLOFF;
}
if (from->magic == XFS_ATTR3_LEAF_MAGIC) {
hdr3 = (struct xfs_attr3_leaf_hdr *) to;
hdr3->firstused = cpu_to_be16(firstused);
} else {
to->hdr.firstused = cpu_to_be16(firstused);
}
}
void
xfs_attr3_leaf_hdr_from_disk(
struct xfs_da_geometry *geo,
struct xfs_attr3_icleaf_hdr *to,
struct xfs_attr_leafblock *from)
{
int i;
ASSERT(from->hdr.info.magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC) ||
from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC));
if (from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC)) {
struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)from;
to->forw = be32_to_cpu(hdr3->info.hdr.forw);
to->back = be32_to_cpu(hdr3->info.hdr.back);
to->magic = be16_to_cpu(hdr3->info.hdr.magic);
to->count = be16_to_cpu(hdr3->count);
to->usedbytes = be16_to_cpu(hdr3->usedbytes);
xfs_attr3_leaf_firstused_from_disk(geo, to, from);
to->holes = hdr3->holes;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
to->freemap[i].base = be16_to_cpu(hdr3->freemap[i].base);
to->freemap[i].size = be16_to_cpu(hdr3->freemap[i].size);
}
return;
}
to->forw = be32_to_cpu(from->hdr.info.forw);
to->back = be32_to_cpu(from->hdr.info.back);
to->magic = be16_to_cpu(from->hdr.info.magic);
to->count = be16_to_cpu(from->hdr.count);
to->usedbytes = be16_to_cpu(from->hdr.usedbytes);
xfs_attr3_leaf_firstused_from_disk(geo, to, from);
to->holes = from->hdr.holes;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
to->freemap[i].base = be16_to_cpu(from->hdr.freemap[i].base);
to->freemap[i].size = be16_to_cpu(from->hdr.freemap[i].size);
}
}
void
xfs_attr3_leaf_hdr_to_disk(
struct xfs_da_geometry *geo,
struct xfs_attr_leafblock *to,
struct xfs_attr3_icleaf_hdr *from)
{
int i;
ASSERT(from->magic == XFS_ATTR_LEAF_MAGIC ||
from->magic == XFS_ATTR3_LEAF_MAGIC);
if (from->magic == XFS_ATTR3_LEAF_MAGIC) {
struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)to;
hdr3->info.hdr.forw = cpu_to_be32(from->forw);
hdr3->info.hdr.back = cpu_to_be32(from->back);
hdr3->info.hdr.magic = cpu_to_be16(from->magic);
hdr3->count = cpu_to_be16(from->count);
hdr3->usedbytes = cpu_to_be16(from->usedbytes);
xfs_attr3_leaf_firstused_to_disk(geo, to, from);
hdr3->holes = from->holes;
hdr3->pad1 = 0;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
hdr3->freemap[i].base = cpu_to_be16(from->freemap[i].base);
hdr3->freemap[i].size = cpu_to_be16(from->freemap[i].size);
}
return;
}
to->hdr.info.forw = cpu_to_be32(from->forw);
to->hdr.info.back = cpu_to_be32(from->back);
to->hdr.info.magic = cpu_to_be16(from->magic);
to->hdr.count = cpu_to_be16(from->count);
to->hdr.usedbytes = cpu_to_be16(from->usedbytes);
xfs_attr3_leaf_firstused_to_disk(geo, to, from);
to->hdr.holes = from->holes;
to->hdr.pad1 = 0;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
to->hdr.freemap[i].base = cpu_to_be16(from->freemap[i].base);
to->hdr.freemap[i].size = cpu_to_be16(from->freemap[i].size);
}
}
static xfs_failaddr_t
xfs_attr3_leaf_verify(
struct xfs_buf *bp)
{
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_mount *mp = bp->b_target->bt_mount;
struct xfs_attr_leafblock *leaf = bp->b_addr;
struct xfs_perag *pag = bp->b_pag;
struct xfs_attr_leaf_entry *entries;
xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &ichdr, leaf);
if (xfs_sb_version_hascrc(&mp->m_sb)) {
struct xfs_da3_node_hdr *hdr3 = bp->b_addr;
if (ichdr.magic != XFS_ATTR3_LEAF_MAGIC)
return __this_address;
if (!uuid_equal(&hdr3->info.uuid, &mp->m_sb.sb_meta_uuid))
return __this_address;
if (be64_to_cpu(hdr3->info.blkno) != bp->b_bn)
return __this_address;
if (!xfs_log_check_lsn(mp, be64_to_cpu(hdr3->info.lsn)))
return __this_address;
} else {
if (ichdr.magic != XFS_ATTR_LEAF_MAGIC)
return __this_address;
}
/*
* In recovery there is a transient state where count == 0 is valid
* because we may have transitioned an empty shortform attr to a leaf
* if the attr didn't fit in shortform.
*/
if (pag && pag->pagf_init && ichdr.count == 0)
return __this_address;
/*
* firstused is the block offset of the first name info structure.
* Make sure it doesn't go off the block or crash into the header.
*/
if (ichdr.firstused > mp->m_attr_geo->blksize)
return __this_address;
if (ichdr.firstused < xfs_attr3_leaf_hdr_size(leaf))
return __this_address;
/* Make sure the entries array doesn't crash into the name info. */
entries = xfs_attr3_leaf_entryp(bp->b_addr);
if ((char *)&entries[ichdr.count] >
(char *)bp->b_addr + ichdr.firstused)
return __this_address;
/* XXX: need to range check rest of attr header values */
/* XXX: hash order check? */
return NULL;
}
static void
xfs_attr3_leaf_write_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
struct xfs_buf_log_item *bip = bp->b_log_item;
struct xfs_attr3_leaf_hdr *hdr3 = bp->b_addr;
xfs_failaddr_t fa;
fa = xfs_attr3_leaf_verify(bp);
if (fa) {
xfs_verifier_error(bp, -EFSCORRUPTED, fa);
return;
}
if (!xfs_sb_version_hascrc(&mp->m_sb))
return;
if (bip)
hdr3->info.lsn = cpu_to_be64(bip->bli_item.li_lsn);
xfs_buf_update_cksum(bp, XFS_ATTR3_LEAF_CRC_OFF);
}
/*
* leaf/node format detection on trees is sketchy, so a node read can be done on
* leaf level blocks when detection identifies the tree as a node format tree
* incorrectly. In this case, we need to swap the verifier to match the correct
* format of the block being read.
*/
static void
xfs_attr3_leaf_read_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
xfs_failaddr_t fa;
if (xfs_sb_version_hascrc(&mp->m_sb) &&
!xfs_buf_verify_cksum(bp, XFS_ATTR3_LEAF_CRC_OFF))
xfs_verifier_error(bp, -EFSBADCRC, __this_address);
else {
fa = xfs_attr3_leaf_verify(bp);
if (fa)
xfs_verifier_error(bp, -EFSCORRUPTED, fa);
}
}
const struct xfs_buf_ops xfs_attr3_leaf_buf_ops = {
.name = "xfs_attr3_leaf",
.verify_read = xfs_attr3_leaf_read_verify,
.verify_write = xfs_attr3_leaf_write_verify,
.verify_struct = xfs_attr3_leaf_verify,
};
int
xfs_attr3_leaf_read(
struct xfs_trans *tp,
struct xfs_inode *dp,
xfs_dablk_t bno,
xfs_daddr_t mappedbno,
struct xfs_buf **bpp)
{
int err;
err = xfs_da_read_buf(tp, dp, bno, mappedbno, bpp,
XFS_ATTR_FORK, &xfs_attr3_leaf_buf_ops);
if (!err && tp && *bpp)
xfs_trans_buf_set_type(tp, *bpp, XFS_BLFT_ATTR_LEAF_BUF);
return err;
}
/*========================================================================
* Namespace helper routines
*========================================================================*/
/*
* If namespace bits don't match return 0.
* If all match then return 1.
*/
STATIC int
xfs_attr_namesp_match(int arg_flags, int ondisk_flags)
{
return XFS_ATTR_NSP_ONDISK(ondisk_flags) == XFS_ATTR_NSP_ARGS_TO_ONDISK(arg_flags);
}
/*========================================================================
* External routines when attribute fork size < XFS_LITINO(mp).
*========================================================================*/
/*
* Query whether the requested number of additional bytes of extended
* attribute space will be able to fit inline.
*
* Returns zero if not, else the di_forkoff fork offset to be used in the
* literal area for attribute data once the new bytes have been added.
*
* di_forkoff must be 8 byte aligned, hence is stored as a >>3 value;
* special case for dev/uuid inodes, they have fixed size data forks.
*/
int
xfs_attr_shortform_bytesfit(xfs_inode_t *dp, int bytes)
{
int offset;
int minforkoff; /* lower limit on valid forkoff locations */
int maxforkoff; /* upper limit on valid forkoff locations */
int dsize;
xfs_mount_t *mp = dp->i_mount;
/* rounded down */
offset = (XFS_LITINO(mp, dp->i_d.di_version) - bytes) >> 3;
if (dp->i_d.di_format == XFS_DINODE_FMT_DEV) {
minforkoff = roundup(sizeof(xfs_dev_t), 8) >> 3;
return (offset >= minforkoff) ? minforkoff : 0;
}
/*
* If the requested numbers of bytes is smaller or equal to the
* current attribute fork size we can always proceed.
*
* Note that if_bytes in the data fork might actually be larger than
* the current data fork size is due to delalloc extents. In that
* case either the extent count will go down when they are converted
* to real extents, or the delalloc conversion will take care of the
* literal area rebalancing.
*/
if (bytes <= XFS_IFORK_ASIZE(dp))
return dp->i_d.di_forkoff;
/*
* For attr2 we can try to move the forkoff if there is space in the
* literal area, but for the old format we are done if there is no
* space in the fixed attribute fork.
*/
if (!(mp->m_flags & XFS_MOUNT_ATTR2))
return 0;
dsize = dp->i_df.if_bytes;
switch (dp->i_d.di_format) {
case XFS_DINODE_FMT_EXTENTS:
/*
* If there is no attr fork and the data fork is extents,
* determine if creating the default attr fork will result
* in the extents form migrating to btree. If so, the
* minimum offset only needs to be the space required for
* the btree root.
*/
if (!dp->i_d.di_forkoff && dp->i_df.if_bytes >
xfs_default_attroffset(dp))
dsize = XFS_BMDR_SPACE_CALC(MINDBTPTRS);
break;
case XFS_DINODE_FMT_BTREE:
/*
* If we have a data btree then keep forkoff if we have one,
* otherwise we are adding a new attr, so then we set
* minforkoff to where the btree root can finish so we have
* plenty of room for attrs
*/
if (dp->i_d.di_forkoff) {
if (offset < dp->i_d.di_forkoff)
return 0;
return dp->i_d.di_forkoff;
}
dsize = XFS_BMAP_BROOT_SPACE(mp, dp->i_df.if_broot);
break;
}
/*
* A data fork btree root must have space for at least
* MINDBTPTRS key/ptr pairs if the data fork is small or empty.
*/
minforkoff = max(dsize, XFS_BMDR_SPACE_CALC(MINDBTPTRS));
minforkoff = roundup(minforkoff, 8) >> 3;
/* attr fork btree root can have at least this many key/ptr pairs */
maxforkoff = XFS_LITINO(mp, dp->i_d.di_version) -
XFS_BMDR_SPACE_CALC(MINABTPTRS);
maxforkoff = maxforkoff >> 3; /* rounded down */
if (offset >= maxforkoff)
return maxforkoff;
if (offset >= minforkoff)
return offset;
return 0;
}
/*
* Switch on the ATTR2 superblock bit (implies also FEATURES2)
*/
STATIC void
xfs_sbversion_add_attr2(xfs_mount_t *mp, xfs_trans_t *tp)
{
if ((mp->m_flags & XFS_MOUNT_ATTR2) &&
!(xfs_sb_version_hasattr2(&mp->m_sb))) {
spin_lock(&mp->m_sb_lock);
if (!xfs_sb_version_hasattr2(&mp->m_sb)) {
xfs_sb_version_addattr2(&mp->m_sb);
spin_unlock(&mp->m_sb_lock);
xfs_log_sb(tp);
} else
spin_unlock(&mp->m_sb_lock);
}
}
/*
* Create the initial contents of a shortform attribute list.
*/
void
xfs_attr_shortform_create(xfs_da_args_t *args)
{
xfs_attr_sf_hdr_t *hdr;
xfs_inode_t *dp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_create(args);
dp = args->dp;
ASSERT(dp != NULL);
ifp = dp->i_afp;
ASSERT(ifp != NULL);
ASSERT(ifp->if_bytes == 0);
if (dp->i_d.di_aformat == XFS_DINODE_FMT_EXTENTS) {
ifp->if_flags &= ~XFS_IFEXTENTS; /* just in case */
dp->i_d.di_aformat = XFS_DINODE_FMT_LOCAL;
ifp->if_flags |= XFS_IFINLINE;
} else {
ASSERT(ifp->if_flags & XFS_IFINLINE);
}
xfs_idata_realloc(dp, sizeof(*hdr), XFS_ATTR_FORK);
hdr = (xfs_attr_sf_hdr_t *)ifp->if_u1.if_data;
hdr->count = 0;
hdr->totsize = cpu_to_be16(sizeof(*hdr));
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_ADATA);
}
/*
* Add a name/value pair to the shortform attribute list.
* Overflow from the inode has already been checked for.
*/
void
xfs_attr_shortform_add(xfs_da_args_t *args, int forkoff)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int i, offset, size;
xfs_mount_t *mp;
xfs_inode_t *dp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_add(args);
dp = args->dp;
mp = dp->i_mount;
dp->i_d.di_forkoff = forkoff;
ifp = dp->i_afp;
ASSERT(ifp->if_flags & XFS_IFINLINE);
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) {
#ifdef DEBUG
if (sfe->namelen != args->namelen)
continue;
if (memcmp(args->name, sfe->nameval, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
ASSERT(0);
#endif
}
offset = (char *)sfe - (char *)sf;
size = XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);
xfs_idata_realloc(dp, size, XFS_ATTR_FORK);
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
sfe = (xfs_attr_sf_entry_t *)((char *)sf + offset);
sfe->namelen = args->namelen;
sfe->valuelen = args->valuelen;
sfe->flags = XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags);
memcpy(sfe->nameval, args->name, args->namelen);
memcpy(&sfe->nameval[args->namelen], args->value, args->valuelen);
sf->hdr.count++;
be16_add_cpu(&sf->hdr.totsize, size);
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_ADATA);
xfs_sbversion_add_attr2(mp, args->trans);
}
/*
* After the last attribute is removed revert to original inode format,
* making all literal area available to the data fork once more.
*/
void
xfs_attr_fork_remove(
struct xfs_inode *ip,
struct xfs_trans *tp)
{
xfs_idestroy_fork(ip, XFS_ATTR_FORK);
ip->i_d.di_forkoff = 0;
ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
ASSERT(ip->i_d.di_anextents == 0);
ASSERT(ip->i_afp == NULL);
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
}
/*
* Remove an attribute from the shortform attribute list structure.
*/
int
xfs_attr_shortform_remove(xfs_da_args_t *args)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int base, size=0, end, totsize, i;
xfs_mount_t *mp;
xfs_inode_t *dp;
trace_xfs_attr_sf_remove(args);
dp = args->dp;
mp = dp->i_mount;
base = sizeof(xfs_attr_sf_hdr_t);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
sfe = &sf->list[0];
end = sf->hdr.count;
for (i = 0; i < end; sfe = XFS_ATTR_SF_NEXTENTRY(sfe),
base += size, i++) {
size = XFS_ATTR_SF_ENTSIZE(sfe);
if (sfe->namelen != args->namelen)
continue;
if (memcmp(sfe->nameval, args->name, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
break;
}
if (i == end)
return -ENOATTR;
/*
* Fix up the attribute fork data, covering the hole
*/
end = base + size;
totsize = be16_to_cpu(sf->hdr.totsize);
if (end != totsize)
memmove(&((char *)sf)[base], &((char *)sf)[end], totsize - end);
sf->hdr.count--;
be16_add_cpu(&sf->hdr.totsize, -size);
/*
* Fix up the start offset of the attribute fork
*/
totsize -= size;
if (totsize == sizeof(xfs_attr_sf_hdr_t) &&
(mp->m_flags & XFS_MOUNT_ATTR2) &&
(dp->i_d.di_format != XFS_DINODE_FMT_BTREE) &&
!(args->op_flags & XFS_DA_OP_ADDNAME)) {
xfs_attr_fork_remove(dp, args->trans);
} else {
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
dp->i_d.di_forkoff = xfs_attr_shortform_bytesfit(dp, totsize);
ASSERT(dp->i_d.di_forkoff);
ASSERT(totsize > sizeof(xfs_attr_sf_hdr_t) ||
(args->op_flags & XFS_DA_OP_ADDNAME) ||
!(mp->m_flags & XFS_MOUNT_ATTR2) ||
dp->i_d.di_format == XFS_DINODE_FMT_BTREE);
xfs_trans_log_inode(args->trans, dp,
XFS_ILOG_CORE | XFS_ILOG_ADATA);
}
xfs_sbversion_add_attr2(mp, args->trans);
return 0;
}
/*
* Look up a name in a shortform attribute list structure.
*/
/*ARGSUSED*/
int
xfs_attr_shortform_lookup(xfs_da_args_t *args)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int i;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_lookup(args);
ifp = args->dp->i_afp;
ASSERT(ifp->if_flags & XFS_IFINLINE);
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) {
if (sfe->namelen != args->namelen)
continue;
if (memcmp(args->name, sfe->nameval, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
return -EEXIST;
}
return -ENOATTR;
}
/*
* Look up a name in a shortform attribute list structure.
*/
/*ARGSUSED*/
int
xfs_attr_shortform_getvalue(xfs_da_args_t *args)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int i;
ASSERT(args->dp->i_afp->if_flags == XFS_IFINLINE);
sf = (xfs_attr_shortform_t *)args->dp->i_afp->if_u1.if_data;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) {
if (sfe->namelen != args->namelen)
continue;
if (memcmp(args->name, sfe->nameval, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
if (args->flags & ATTR_KERNOVAL) {
args->valuelen = sfe->valuelen;
return -EEXIST;
}
if (args->valuelen < sfe->valuelen) {
args->valuelen = sfe->valuelen;
return -ERANGE;
}
args->valuelen = sfe->valuelen;
memcpy(args->value, &sfe->nameval[args->namelen],
args->valuelen);
return -EEXIST;
}
return -ENOATTR;
}
/*
* Convert from using the shortform to the leaf. On success, return the
* buffer so that we can keep it locked until we're totally done with it.
*/
int
xfs_attr_shortform_to_leaf(
struct xfs_da_args *args,
struct xfs_buf **leaf_bp)
{
xfs_inode_t *dp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_da_args_t nargs;
char *tmpbuffer;
int error, i, size;
xfs_dablk_t blkno;
struct xfs_buf *bp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_to_leaf(args);
dp = args->dp;
ifp = dp->i_afp;
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
size = be16_to_cpu(sf->hdr.totsize);
tmpbuffer = kmem_alloc(size, KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, ifp->if_u1.if_data, size);
sf = (xfs_attr_shortform_t *)tmpbuffer;
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);
bp = NULL;
error = xfs_da_grow_inode(args, &blkno);
if (error) {
/*
* If we hit an IO error middle of the transaction inside
* grow_inode(), we may have inconsistent data. Bail out.
*/
if (error == -EIO)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
ASSERT(blkno == 0);
error = xfs_attr3_leaf_create(args, blkno, &bp);
if (error) {
error = xfs_da_shrink_inode(args, 0, bp);
bp = NULL;
if (error)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.geo = args->geo;
nargs.firstblock = args->firstblock;
nargs.dfops = args->dfops;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; i++) {
nargs.name = sfe->nameval;
nargs.namelen = sfe->namelen;
nargs.value = &sfe->nameval[nargs.namelen];
nargs.valuelen = sfe->valuelen;
nargs.hashval = xfs_da_hashname(sfe->nameval,
sfe->namelen);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);
error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
ASSERT(error == -ENOATTR);
error = xfs_attr3_leaf_add(bp, &nargs);
ASSERT(error != -ENOSPC);
if (error)
goto out;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
error = 0;
*leaf_bp = bp;
out:
kmem_free(tmpbuffer);
return error;
}
/*
* Check a leaf attribute block to see if all the entries would fit into
* a shortform attribute list.
*/
int
xfs_attr_shortform_allfit(
struct xfs_buf *bp,
struct xfs_inode *dp)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
xfs_attr_leaf_name_local_t *name_loc;
struct xfs_attr3_icleaf_hdr leafhdr;
int bytes;
int i;
struct xfs_mount *mp = bp->b_target->bt_mount;
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &leafhdr, leaf);
entry = xfs_attr3_leaf_entryp(leaf);
bytes = sizeof(struct xfs_attr_sf_hdr);
for (i = 0; i < leafhdr.count; entry++, i++) {
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* don't copy partial entries */
if (!(entry->flags & XFS_ATTR_LOCAL))
return 0;
name_loc = xfs_attr3_leaf_name_local(leaf, i);
if (name_loc->namelen >= XFS_ATTR_SF_ENTSIZE_MAX)
return 0;
if (be16_to_cpu(name_loc->valuelen) >= XFS_ATTR_SF_ENTSIZE_MAX)
return 0;
bytes += sizeof(struct xfs_attr_sf_entry) - 1
+ name_loc->namelen
+ be16_to_cpu(name_loc->valuelen);
}
if ((dp->i_mount->m_flags & XFS_MOUNT_ATTR2) &&
(dp->i_d.di_format != XFS_DINODE_FMT_BTREE) &&
(bytes == sizeof(struct xfs_attr_sf_hdr)))
return -1;
return xfs_attr_shortform_bytesfit(dp, bytes);
}
/* Verify the consistency of an inline attribute fork. */
xfs_failaddr_t
xfs_attr_shortform_verify(
struct xfs_inode *ip)
{
struct xfs_attr_shortform *sfp;
struct xfs_attr_sf_entry *sfep;
struct xfs_attr_sf_entry *next_sfep;
char *endp;
struct xfs_ifork *ifp;
int i;
int size;
ASSERT(ip->i_d.di_aformat == XFS_DINODE_FMT_LOCAL);
ifp = XFS_IFORK_PTR(ip, XFS_ATTR_FORK);
sfp = (struct xfs_attr_shortform *)ifp->if_u1.if_data;
size = ifp->if_bytes;
/*
* Give up if the attribute is way too short.
*/
if (size < sizeof(struct xfs_attr_sf_hdr))
return __this_address;
endp = (char *)sfp + size;
/* Check all reported entries */
sfep = &sfp->list[0];
for (i = 0; i < sfp->hdr.count; i++) {
/*
* struct xfs_attr_sf_entry has a variable length.
* Check the fixed-offset parts of the structure are
* within the data buffer.
*/
if (((char *)sfep + sizeof(*sfep)) >= endp)
return __this_address;
/* Don't allow names with known bad length. */
if (sfep->namelen == 0)
return __this_address;
/*
* Check that the variable-length part of the structure is
* within the data buffer. The next entry starts after the
* name component, so nextentry is an acceptable test.
*/
next_sfep = XFS_ATTR_SF_NEXTENTRY(sfep);
if ((char *)next_sfep > endp)
return __this_address;
/*
* Check for unknown flags. Short form doesn't support
* the incomplete or local bits, so we can use the namespace
* mask here.
*/
if (sfep->flags & ~XFS_ATTR_NSP_ONDISK_MASK)
return __this_address;
/*
* Check for invalid namespace combinations. We only allow
* one namespace flag per xattr, so we can just count the
* bits (i.e. hweight) here.
*/
if (hweight8(sfep->flags & XFS_ATTR_NSP_ONDISK_MASK) > 1)
return __this_address;
sfep = next_sfep;
}
if ((void *)sfep != (void *)endp)
return __this_address;
return NULL;
}
/*
* Convert a leaf attribute list to shortform attribute list
*/
int
xfs_attr3_leaf_to_shortform(
struct xfs_buf *bp,
struct xfs_da_args *args,
int forkoff)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_da_args nargs;
struct xfs_inode *dp = args->dp;
char *tmpbuffer;
int error;
int i;
trace_xfs_attr_leaf_to_sf(args);
tmpbuffer = kmem_alloc(args->geo->blksize, KM_SLEEP);
if (!tmpbuffer)
return -ENOMEM;
memcpy(tmpbuffer, bp->b_addr, args->geo->blksize);
leaf = (xfs_attr_leafblock_t *)tmpbuffer;
xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
entry = xfs_attr3_leaf_entryp(leaf);
/* XXX (dgc): buffer is about to be marked stale - why zero it? */
memset(bp->b_addr, 0, args->geo->blksize);
/*
* Clean out the prior contents of the attribute list.
*/
error = xfs_da_shrink_inode(args, 0, bp);
if (error)
goto out;
if (forkoff == -1) {
ASSERT(dp->i_mount->m_flags & XFS_MOUNT_ATTR2);
ASSERT(dp->i_d.di_format != XFS_DINODE_FMT_BTREE);
xfs_attr_fork_remove(dp, args->trans);
goto out;
}
xfs_attr_shortform_create(args);
/*
* Copy the attributes
*/
memset((char *)&nargs, 0, sizeof(nargs));
nargs.geo = args->geo;
nargs.dp = dp;
nargs.firstblock = args->firstblock;
nargs.dfops = args->dfops;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
for (i = 0; i < ichdr.count; entry++, i++) {
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* don't copy partial entries */
if (!entry->nameidx)
continue;
ASSERT(entry->flags & XFS_ATTR_LOCAL);
name_loc = xfs_attr3_leaf_name_local(leaf, i);
nargs.name = name_loc->nameval;
nargs.namelen = name_loc->namelen;
nargs.value = &name_loc->nameval[nargs.namelen];
nargs.valuelen = be16_to_cpu(name_loc->valuelen);
nargs.hashval = be32_to_cpu(entry->hashval);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(entry->flags);
xfs_attr_shortform_add(&nargs, forkoff);
}
error = 0;
out:
kmem_free(tmpbuffer);
return error;
}
/*
* Convert from using a single leaf to a root node and a leaf.
*/
int
xfs_attr3_leaf_to_node(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr icleafhdr;
struct xfs_attr_leaf_entry *entries;
struct xfs_da_node_entry *btree;
struct xfs_da3_icnode_hdr icnodehdr;
struct xfs_da_intnode *node;
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_buf *bp1 = NULL;
struct xfs_buf *bp2 = NULL;
xfs_dablk_t blkno;
int error;
trace_xfs_attr_leaf_to_node(args);
error = xfs_da_grow_inode(args, &blkno);
if (error)
goto out;
error = xfs_attr3_leaf_read(args->trans, dp, 0, -1, &bp1);
if (error)
goto out;
error = xfs_da_get_buf(args->trans, dp, blkno, -1, &bp2, XFS_ATTR_FORK);
if (error)
goto out;
/* copy leaf to new buffer, update identifiers */
xfs_trans_buf_set_type(args->trans, bp2, XFS_BLFT_ATTR_LEAF_BUF);
bp2->b_ops = bp1->b_ops;
memcpy(bp2->b_addr, bp1->b_addr, args->geo->blksize);
if (xfs_sb_version_hascrc(&mp->m_sb)) {
struct xfs_da3_blkinfo *hdr3 = bp2->b_addr;
hdr3->blkno = cpu_to_be64(bp2->b_bn);
}
xfs_trans_log_buf(args->trans, bp2, 0, args->geo->blksize - 1);
/*
* Set up the new root node.
*/
error = xfs_da3_node_create(args, 0, 1, &bp1, XFS_ATTR_FORK);
if (error)
goto out;
node = bp1->b_addr;
dp->d_ops->node_hdr_from_disk(&icnodehdr, node);
btree = dp->d_ops->node_tree_p(node);
leaf = bp2->b_addr;
xfs_attr3_leaf_hdr_from_disk(args->geo, &icleafhdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
/* both on-disk, don't endian-flip twice */
btree[0].hashval = entries[icleafhdr.count - 1].hashval;
btree[0].before = cpu_to_be32(blkno);
icnodehdr.count = 1;
dp->d_ops->node_hdr_to_disk(node, &icnodehdr);
xfs_trans_log_buf(args->trans, bp1, 0, args->geo->blksize - 1);
error = 0;
out:
return error;
}
/*========================================================================
* Routines used for growing the Btree.
*========================================================================*/
/*
* Create the initial contents of a leaf attribute list
* or a leaf in a node attribute list.
*/
STATIC int
xfs_attr3_leaf_create(
struct xfs_da_args *args,
xfs_dablk_t blkno,
struct xfs_buf **bpp)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_buf *bp;
int error;
trace_xfs_attr_leaf_create(args);
error = xfs_da_get_buf(args->trans, args->dp, blkno, -1, &bp,
XFS_ATTR_FORK);
if (error)
return error;
bp->b_ops = &xfs_attr3_leaf_buf_ops;
xfs_trans_buf_set_type(args->trans, bp, XFS_BLFT_ATTR_LEAF_BUF);
leaf = bp->b_addr;
memset(leaf, 0, args->geo->blksize);
memset(&ichdr, 0, sizeof(ichdr));
ichdr.firstused = args->geo->blksize;
if (xfs_sb_version_hascrc(&mp->m_sb)) {
struct xfs_da3_blkinfo *hdr3 = bp->b_addr;
ichdr.magic = XFS_ATTR3_LEAF_MAGIC;
hdr3->blkno = cpu_to_be64(bp->b_bn);
hdr3->owner = cpu_to_be64(dp->i_ino);
uuid_copy(&hdr3->uuid, &mp->m_sb.sb_meta_uuid);
ichdr.freemap[0].base = sizeof(struct xfs_attr3_leaf_hdr);
} else {
ichdr.magic = XFS_ATTR_LEAF_MAGIC;
ichdr.freemap[0].base = sizeof(struct xfs_attr_leaf_hdr);
}
ichdr.freemap[0].size = ichdr.firstused - ichdr.freemap[0].base;
xfs_attr3_leaf_hdr_to_disk(args->geo, leaf, &ichdr);
xfs_trans_log_buf(args->trans, bp, 0, args->geo->blksize - 1);
*bpp = bp;
return 0;
}
/*
* Split the leaf node, rebalance, then add the new entry.
*/
int
xfs_attr3_leaf_split(
struct xfs_da_state *state,
struct xfs_da_state_blk *oldblk,
struct xfs_da_state_blk *newblk)
{
xfs_dablk_t blkno;
int error;
trace_xfs_attr_leaf_split(state->args);
/*
* Allocate space for a new leaf node.
*/
ASSERT(oldblk->magic == XFS_ATTR_LEAF_MAGIC);
error = xfs_da_grow_inode(state->args, &blkno);
if (error)
return error;
error = xfs_attr3_leaf_create(state->args, blkno, &newblk->bp);
if (error)
return error;
newblk->blkno = blkno;
newblk->magic = XFS_ATTR_LEAF_MAGIC;
/*
* Rebalance the entries across the two leaves.
* NOTE: rebalance() currently depends on the 2nd block being empty.
*/
xfs_attr3_leaf_rebalance(state, oldblk, newblk);
error = xfs_da3_blk_link(state, oldblk, newblk);
if (error)
return error;
/*
* Save info on "old" attribute for "atomic rename" ops, leaf_add()
* modifies the index/blkno/rmtblk/rmtblkcnt fields to show the
* "new" attrs info. Will need the "old" info to remove it later.
*
* Insert the "new" entry in the correct block.
*/
if (state->inleaf) {
trace_xfs_attr_leaf_add_old(state->args);
error = xfs_attr3_leaf_add(oldblk->bp, state->args);
} else {
trace_xfs_attr_leaf_add_new(state->args);
error = xfs_attr3_leaf_add(newblk->bp, state->args);
}
/*
* Update last hashval in each block since we added the name.
*/
oldblk->hashval = xfs_attr_leaf_lasthash(oldblk->bp, NULL);
newblk->hashval = xfs_attr_leaf_lasthash(newblk->bp, NULL);
return error;
}
/*
* Add a name to the leaf attribute list structure.
*/
int
xfs_attr3_leaf_add(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
int tablesize;
int entsize;
int sum;
int tmp;
int i;
trace_xfs_attr_leaf_add(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
ASSERT(args->index >= 0 && args->index <= ichdr.count);
entsize = xfs_attr_leaf_newentsize(args, NULL);
/*
* Search through freemap for first-fit on new name length.
* (may need to figure in size of entry struct too)
*/
tablesize = (ichdr.count + 1) * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf);
for (sum = 0, i = XFS_ATTR_LEAF_MAPSIZE - 1; i >= 0; i--) {
if (tablesize > ichdr.firstused) {
sum += ichdr.freemap[i].size;
continue;
}
if (!ichdr.freemap[i].size)
continue; /* no space in this map */
tmp = entsize;
if (ichdr.freemap[i].base < ichdr.firstused)
tmp += sizeof(xfs_attr_leaf_entry_t);
if (ichdr.freemap[i].size >= tmp) {
tmp = xfs_attr3_leaf_add_work(bp, &ichdr, args, i);
goto out_log_hdr;
}
sum += ichdr.freemap[i].size;
}
/*
* If there are no holes in the address space of the block,
* and we don't have enough freespace, then compaction will do us
* no good and we should just give up.
*/
if (!ichdr.holes && sum < entsize)
return -ENOSPC;
/*
* Compact the entries to coalesce free space.
* This may change the hdr->count via dropping INCOMPLETE entries.
*/
xfs_attr3_leaf_compact(args, &ichdr, bp);
/*
* After compaction, the block is guaranteed to have only one
* free region, in freemap[0]. If it is not big enough, give up.
*/
if (ichdr.freemap[0].size < (entsize + sizeof(xfs_attr_leaf_entry_t))) {
tmp = -ENOSPC;
goto out_log_hdr;
}
tmp = xfs_attr3_leaf_add_work(bp, &ichdr, args, 0);
out_log_hdr:
xfs_attr3_leaf_hdr_to_disk(args->geo, leaf, &ichdr);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, &leaf->hdr,
xfs_attr3_leaf_hdr_size(leaf)));
return tmp;
}
/*
* Add a name to a leaf attribute list structure.
*/
STATIC int
xfs_attr3_leaf_add_work(
struct xfs_buf *bp,
struct xfs_attr3_icleaf_hdr *ichdr,
struct xfs_da_args *args,
int mapindex)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_mount *mp;
int tmp;
int i;
trace_xfs_attr_leaf_add_work(args);
leaf = bp->b_addr;
ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE);
ASSERT(args->index >= 0 && args->index <= ichdr->count);
/*
* Force open some space in the entry array and fill it in.
*/
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
if (args->index < ichdr->count) {
tmp = ichdr->count - args->index;
tmp *= sizeof(xfs_attr_leaf_entry_t);
memmove(entry + 1, entry, tmp);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry)));
}
ichdr->count++;
/*
* Allocate space for the new string (at the end of the run).
*/
mp = args->trans->t_mountp;
ASSERT(ichdr->freemap[mapindex].base < args->geo->blksize);
ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0);
ASSERT(ichdr->freemap[mapindex].size >=
xfs_attr_leaf_newentsize(args, NULL));
ASSERT(ichdr->freemap[mapindex].size < args->geo->blksize);
ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0);
ichdr->freemap[mapindex].size -= xfs_attr_leaf_newentsize(args, &tmp);
entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base +
ichdr->freemap[mapindex].size);
entry->hashval = cpu_to_be32(args->hashval);
entry->flags = tmp ? XFS_ATTR_LOCAL : 0;
entry->flags |= XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags);
if (args->op_flags & XFS_DA_OP_RENAME) {
entry->flags |= XFS_ATTR_INCOMPLETE;
if ((args->blkno2 == args->blkno) &&
(args->index2 <= args->index)) {
args->index2++;
}
}
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
ASSERT((args->index == 0) ||
(be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval)));
ASSERT((args->index == ichdr->count - 1) ||
(be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval)));
/*
* For "remote" attribute values, simply note that we need to
* allocate space for the "remote" value. We can't actually
* allocate the extents in this transaction, and we can't decide
* which blocks they should be as we might allocate more blocks
* as part of this transaction (a split operation for example).
*/
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
name_loc->namelen = args->namelen;
name_loc->valuelen = cpu_to_be16(args->valuelen);
memcpy((char *)name_loc->nameval, args->name, args->namelen);
memcpy((char *)&name_loc->nameval[args->namelen], args->value,
be16_to_cpu(name_loc->valuelen));
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->namelen = args->namelen;
memcpy((char *)name_rmt->name, args->name, args->namelen);
entry->flags |= XFS_ATTR_INCOMPLETE;
/* just in case */
name_rmt->valuelen = 0;
name_rmt->valueblk = 0;
args->rmtblkno = 1;
args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen);
args->rmtvaluelen = args->valuelen;
}
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index),
xfs_attr_leaf_entsize(leaf, args->index)));
/*
* Update the control info for this leaf node
*/
if (be16_to_cpu(entry->nameidx) < ichdr->firstused)
ichdr->firstused = be16_to_cpu(entry->nameidx);
ASSERT(ichdr->firstused >= ichdr->count * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf));
tmp = (ichdr->count - 1) * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf);
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
if (ichdr->freemap[i].base == tmp) {
ichdr->freemap[i].base += sizeof(xfs_attr_leaf_entry_t);
ichdr->freemap[i].size -= sizeof(xfs_attr_leaf_entry_t);
}
}
ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index);
return 0;
}
/*
* Garbage collect a leaf attribute list block by copying it to a new buffer.
*/
STATIC void
xfs_attr3_leaf_compact(
struct xfs_da_args *args,
struct xfs_attr3_icleaf_hdr *ichdr_dst,
struct xfs_buf *bp)
{
struct xfs_attr_leafblock *leaf_src;
struct xfs_attr_leafblock *leaf_dst;
struct xfs_attr3_icleaf_hdr ichdr_src;
struct xfs_trans *trans = args->trans;
char *tmpbuffer;
trace_xfs_attr_leaf_compact(args);
tmpbuffer = kmem_alloc(args->geo->blksize, KM_SLEEP);
memcpy(tmpbuffer, bp->b_addr, args->geo->blksize);
memset(bp->b_addr, 0, args->geo->blksize);
leaf_src = (xfs_attr_leafblock_t *)tmpbuffer;
leaf_dst = bp->b_addr;
/*
* Copy the on-disk header back into the destination buffer to ensure
* all the information in the header that is not part of the incore
* header structure is preserved.
*/
memcpy(bp->b_addr, tmpbuffer, xfs_attr3_leaf_hdr_size(leaf_src));
/* Initialise the incore headers */
ichdr_src = *ichdr_dst; /* struct copy */
ichdr_dst->firstused = args->geo->blksize;
ichdr_dst->usedbytes = 0;
ichdr_dst->count = 0;
ichdr_dst->holes = 0;
ichdr_dst->freemap[0].base = xfs_attr3_leaf_hdr_size(leaf_src);
ichdr_dst->freemap[0].size = ichdr_dst->firstused -
ichdr_dst->freemap[0].base;
/* write the header back to initialise the underlying buffer */
xfs_attr3_leaf_hdr_to_disk(args->geo, leaf_dst, ichdr_dst);
/*
* Copy all entry's in the same (sorted) order,
* but allocate name/value pairs packed and in sequence.
*/
xfs_attr3_leaf_moveents(args, leaf_src, &ichdr_src, 0,
leaf_dst, ichdr_dst, 0, ichdr_src.count);
/*
* this logs the entire buffer, but the caller must write the header
* back to the buffer when it is finished modifying it.
*/
xfs_trans_log_buf(trans, bp, 0, args->geo->blksize - 1);
kmem_free(tmpbuffer);
}
/*
* Compare two leaf blocks "order".
* Return 0 unless leaf2 should go before leaf1.
*/
static int
xfs_attr3_leaf_order(
struct xfs_buf *leaf1_bp,
struct xfs_attr3_icleaf_hdr *leaf1hdr,
struct xfs_buf *leaf2_bp,
struct xfs_attr3_icleaf_hdr *leaf2hdr)
{
struct xfs_attr_leaf_entry *entries1;
struct xfs_attr_leaf_entry *entries2;
entries1 = xfs_attr3_leaf_entryp(leaf1_bp->b_addr);
entries2 = xfs_attr3_leaf_entryp(leaf2_bp->b_addr);
if (leaf1hdr->count > 0 && leaf2hdr->count > 0 &&
((be32_to_cpu(entries2[0].hashval) <
be32_to_cpu(entries1[0].hashval)) ||
(be32_to_cpu(entries2[leaf2hdr->count - 1].hashval) <
be32_to_cpu(entries1[leaf1hdr->count - 1].hashval)))) {
return 1;
}
return 0;
}
int
xfs_attr_leaf_order(
struct xfs_buf *leaf1_bp,
struct xfs_buf *leaf2_bp)
{
struct xfs_attr3_icleaf_hdr ichdr1;
struct xfs_attr3_icleaf_hdr ichdr2;
struct xfs_mount *mp = leaf1_bp->b_target->bt_mount;
xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &ichdr1, leaf1_bp->b_addr);
xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &ichdr2, leaf2_bp->b_addr);
return xfs_attr3_leaf_order(leaf1_bp, &ichdr1, leaf2_bp, &ichdr2);
}
/*
* Redistribute the attribute list entries between two leaf nodes,
* taking into account the size of the new entry.
*
* NOTE: if new block is empty, then it will get the upper half of the
* old block. At present, all (one) callers pass in an empty second block.
*
* This code adjusts the args->index/blkno and args->index2/blkno2 fields
* to match what it is doing in splitting the attribute leaf block. Those
* values are used in "atomic rename" operations on attributes. Note that
* the "new" and "old" values can end up in different blocks.
*/
STATIC void
xfs_attr3_leaf_rebalance(
struct xfs_da_state *state,
struct xfs_da_state_blk *blk1,
struct xfs_da_state_blk *blk2)
{
struct xfs_da_args *args;
struct xfs_attr_leafblock *leaf1;
struct xfs_attr_leafblock *leaf2;
struct xfs_attr3_icleaf_hdr ichdr1;
struct xfs_attr3_icleaf_hdr ichdr2;
struct xfs_attr_leaf_entry *entries1;
struct xfs_attr_leaf_entry *entries2;
int count;
int totallen;
int max;
int space;
int swap;
/*
* Set up environment.
*/
ASSERT(blk1->magic == XFS_ATTR_LEAF_MAGIC);
ASSERT(blk2->magic == XFS_ATTR_LEAF_MAGIC);
leaf1 = blk1->bp->b_addr;
leaf2 = blk2->bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(state->args->geo, &ichdr1, leaf1);
xfs_attr3_leaf_hdr_from_disk(state->args->geo, &ichdr2, leaf2);
ASSERT(ichdr2.count == 0);
args = state->args;
trace_xfs_attr_leaf_rebalance(args);
/*
* Check ordering of blocks, reverse if it makes things simpler.
*
* NOTE: Given that all (current) callers pass in an empty
* second block, this code should never set "swap".
*/
swap = 0;
if (xfs_attr3_leaf_order(blk1->bp, &ichdr1, blk2->bp, &ichdr2)) {
struct xfs_da_state_blk *tmp_blk;
struct xfs_attr3_icleaf_hdr tmp_ichdr;
tmp_blk = blk1;
blk1 = blk2;
blk2 = tmp_blk;
/* struct copies to swap them rather than reconverting */
tmp_ichdr = ichdr1;
ichdr1 = ichdr2;
ichdr2 = tmp_ichdr;
leaf1 = blk1->bp->b_addr;
leaf2 = blk2->bp->b_addr;
swap = 1;
}
/*
* Examine entries until we reduce the absolute difference in
* byte usage between the two blocks to a minimum. Then get
* the direction to copy and the number of elements to move.
*
* "inleaf" is true if the new entry should be inserted into blk1.
* If "swap" is also true, then reverse the sense of "inleaf".
*/
state->inleaf = xfs_attr3_leaf_figure_balance(state, blk1, &ichdr1,
blk2, &ichdr2,
&count, &totallen);
if (swap)
state->inleaf = !state->inleaf;
/*
* Move any entries required from leaf to leaf:
*/
if (count < ichdr1.count) {
/*
* Figure the total bytes to be added to the destination leaf.
*/
/* number entries being moved */
count = ichdr1.count - count;
space = ichdr1.usedbytes - totallen;
space += count * sizeof(xfs_attr_leaf_entry_t);
/*
* leaf2 is the destination, compact it if it looks tight.
*/
max = ichdr2.firstused - xfs_attr3_leaf_hdr_size(leaf1);
max -= ichdr2.count * sizeof(xfs_attr_leaf_entry_t);
if (space > max)
xfs_attr3_leaf_compact(args, &ichdr2, blk2->bp);
/*
* Move high entries from leaf1 to low end of leaf2.
*/
xfs_attr3_leaf_moveents(args, leaf1, &ichdr1,
ichdr1.count - count, leaf2, &ichdr2, 0, count);
} else if (count > ichdr1.count) {
/*
* I assert that since all callers pass in an empty
* second buffer, this code should never execute.
*/
ASSERT(0);
/*
* Figure the total bytes to be added to the destination leaf.
*/
/* number entries being moved */
count -= ichdr1.count;
space = totallen - ichdr1.usedbytes;
space += count * sizeof(xfs_attr_leaf_entry_t);
/*
* leaf1 is the destination, compact it if it looks tight.
*/
max = ichdr1.firstused - xfs_attr3_leaf_hdr_size(leaf1);
max -= ichdr1.count * sizeof(xfs_attr_leaf_entry_t);
if (space > max)
xfs_attr3_leaf_compact(args, &ichdr1, blk1->bp);
/*
* Move low entries from leaf2 to high end of leaf1.
*/
xfs_attr3_leaf_moveents(args, leaf2, &ichdr2, 0, leaf1, &ichdr1,
ichdr1.count, count);
}
xfs_attr3_leaf_hdr_to_disk(state->args->geo, leaf1, &ichdr1);
xfs_attr3_leaf_hdr_to_disk(state->args->geo, leaf2, &ichdr2);
xfs_trans_log_buf(args->trans, blk1->bp, 0, args->geo->blksize - 1);
xfs_trans_log_buf(args->trans, blk2->bp, 0, args->geo->blksize - 1);
/*
* Copy out last hashval in each block for B-tree code.
*/
entries1 = xfs_attr3_leaf_entryp(leaf1);
entries2 = xfs_attr3_leaf_entryp(leaf2);
blk1->hashval = be32_to_cpu(entries1[ichdr1.count - 1].hashval);
blk2->hashval = be32_to_cpu(entries2[ichdr2.count - 1].hashval);
/*
* Adjust the expected index for insertion.
* NOTE: this code depends on the (current) situation that the
* second block was originally empty.
*
* If the insertion point moved to the 2nd block, we must adjust
* the index. We must also track the entry just following the
* new entry for use in an "atomic rename" operation, that entry
* is always the "old" entry and the "new" entry is what we are
* inserting. The index/blkno fields refer to the "old" entry,
* while the index2/blkno2 fields refer to the "new" entry.
*/
if (blk1->index > ichdr1.count) {
ASSERT(state->inleaf == 0);
blk2->index = blk1->index - ichdr1.count;
args->index = args->index2 = blk2->index;
args->blkno = args->blkno2 = blk2->blkno;
} else if (blk1->index == ichdr1.count) {
if (state->inleaf) {
args->index = blk1->index;
args->blkno = blk1->blkno;
args->index2 = 0;
args->blkno2 = blk2->blkno;
} else {
/*
* On a double leaf split, the original attr location
* is already stored in blkno2/index2, so don't
* overwrite it overwise we corrupt the tree.
*/
blk2->index = blk1->index - ichdr1.count;
args->index = blk2->index;
args->blkno = blk2->blkno;
if (!state->extravalid) {
/*
* set the new attr location to match the old
* one and let the higher level split code
* decide where in the leaf to place it.
*/
args->index2 = blk2->index;
args->blkno2 = blk2->blkno;
}
}
} else {
ASSERT(state->inleaf == 1);
args->index = args->index2 = blk1->index;
args->blkno = args->blkno2 = blk1->blkno;
}
}
/*
* Examine entries until we reduce the absolute difference in
* byte usage between the two blocks to a minimum.
* GROT: Is this really necessary? With other than a 512 byte blocksize,
* GROT: there will always be enough room in either block for a new entry.
* GROT: Do a double-split for this case?
*/
STATIC int
xfs_attr3_leaf_figure_balance(
struct xfs_da_state *state,
struct xfs_da_state_blk *blk1,
struct xfs_attr3_icleaf_hdr *ichdr1,
struct xfs_da_state_blk *blk2,
struct xfs_attr3_icleaf_hdr *ichdr2,
int *countarg,
int *usedbytesarg)
{
struct xfs_attr_leafblock *leaf1 = blk1->bp->b_addr;
struct xfs_attr_leafblock *leaf2 = blk2->bp->b_addr;
struct xfs_attr_leaf_entry *entry;
int count;
int max;
int index;
int totallen = 0;
int half;
int lastdelta;
int foundit = 0;
int tmp;
/*
* Examine entries until we reduce the absolute difference in
* byte usage between the two blocks to a minimum.
*/
max = ichdr1->count + ichdr2->count;
half = (max + 1) * sizeof(*entry);
half += ichdr1->usedbytes + ichdr2->usedbytes +
xfs_attr_leaf_newentsize(state->args, NULL);
half /= 2;
lastdelta = state->args->geo->blksize;
entry = xfs_attr3_leaf_entryp(leaf1);
for (count = index = 0; count < max; entry++, index++, count++) {
#define XFS_ATTR_ABS(A) (((A) < 0) ? -(A) : (A))
/*
* The new entry is in the first block, account for it.
*/
if (count == blk1->index) {
tmp = totallen + sizeof(*entry) +
xfs_attr_leaf_newentsize(state->args, NULL);
if (XFS_ATTR_ABS(half - tmp) > lastdelta)
break;
lastdelta = XFS_ATTR_ABS(half - tmp);
totallen = tmp;
foundit = 1;
}
/*
* Wrap around into the second block if necessary.
*/
if (count == ichdr1->count) {
leaf1 = leaf2;
entry = xfs_attr3_leaf_entryp(leaf1);
index = 0;
}
/*
* Figure out if next leaf entry would be too much.
*/
tmp = totallen + sizeof(*entry) + xfs_attr_leaf_entsize(leaf1,
index);
if (XFS_ATTR_ABS(half - tmp) > lastdelta)
break;
lastdelta = XFS_ATTR_ABS(half - tmp);
totallen = tmp;
#undef XFS_ATTR_ABS
}
/*
* Calculate the number of usedbytes that will end up in lower block.
* If new entry not in lower block, fix up the count.
*/
totallen -= count * sizeof(*entry);
if (foundit) {
totallen -= sizeof(*entry) +
xfs_attr_leaf_newentsize(state->args, NULL);
}
*countarg = count;
*usedbytesarg = totallen;
return foundit;
}
/*========================================================================
* Routines used for shrinking the Btree.
*========================================================================*/
/*
* Check a leaf block and its neighbors to see if the block should be
* collapsed into one or the other neighbor. Always keep the block
* with the smaller block number.
* If the current block is over 50% full, don't try to join it, return 0.
* If the block is empty, fill in the state structure and return 2.
* If it can be collapsed, fill in the state structure and return 1.
* If nothing can be done, return 0.
*
* GROT: allow for INCOMPLETE entries in calculation.
*/
int
xfs_attr3_leaf_toosmall(
struct xfs_da_state *state,
int *action)
{
struct xfs_attr_leafblock *leaf;
struct xfs_da_state_blk *blk;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_buf *bp;
xfs_dablk_t blkno;
int bytes;
int forward;
int error;
int retval;
int i;
trace_xfs_attr_leaf_toosmall(state->args);
/*
* Check for the degenerate case of the block being over 50% full.
* If so, it's not worth even looking to see if we might be able
* to coalesce with a sibling.
*/
blk = &state->path.blk[ state->path.active-1 ];
leaf = blk->bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(state->args->geo, &ichdr, leaf);
bytes = xfs_attr3_leaf_hdr_size(leaf) +
ichdr.count * sizeof(xfs_attr_leaf_entry_t) +
ichdr.usedbytes;
if (bytes > (state->args->geo->blksize >> 1)) {
*action = 0; /* blk over 50%, don't try to join */
return 0;
}
/*
* Check for the degenerate case of the block being empty.
* If the block is empty, we'll simply delete it, no need to
* coalesce it with a sibling block. We choose (arbitrarily)
* to merge with the forward block unless it is NULL.
*/
if (ichdr.count == 0) {
/*
* Make altpath point to the block we want to keep and
* path point to the block we want to drop (this one).
*/
forward = (ichdr.forw != 0);
memcpy(&state->altpath, &state->path, sizeof(state->path));
error = xfs_da3_path_shift(state, &state->altpath, forward,
0, &retval);
if (error)
return error;
if (retval) {
*action = 0;
} else {
*action = 2;
}
return 0;
}
/*
* Examine each sibling block to see if we can coalesce with
* at least 25% free space to spare. We need to figure out
* whether to merge with the forward or the backward block.
* We prefer coalescing with the lower numbered sibling so as
* to shrink an attribute list over time.
*/
/* start with smaller blk num */
forward = ichdr.forw < ichdr.back;
for (i = 0; i < 2; forward = !forward, i++) {
struct xfs_attr3_icleaf_hdr ichdr2;
if (forward)
blkno = ichdr.forw;
else
blkno = ichdr.back;
if (blkno == 0)
continue;
error = xfs_attr3_leaf_read(state->args->trans, state->args->dp,
blkno, -1, &bp);
if (error)
return error;
xfs_attr3_leaf_hdr_from_disk(state->args->geo, &ichdr2, bp->b_addr);
bytes = state->args->geo->blksize -
(state->args->geo->blksize >> 2) -
ichdr.usedbytes - ichdr2.usedbytes -
((ichdr.count + ichdr2.count) *
sizeof(xfs_attr_leaf_entry_t)) -
xfs_attr3_leaf_hdr_size(leaf);
xfs_trans_brelse(state->args->trans, bp);
if (bytes >= 0)
break; /* fits with at least 25% to spare */
}
if (i >= 2) {
*action = 0;
return 0;
}
/*
* Make altpath point to the block we want to keep (the lower
* numbered block) and path point to the block we want to drop.
*/
memcpy(&state->altpath, &state->path, sizeof(state->path));
if (blkno < blk->blkno) {
error = xfs_da3_path_shift(state, &state->altpath, forward,
0, &retval);
} else {
error = xfs_da3_path_shift(state, &state->path, forward,
0, &retval);
}
if (error)
return error;
if (retval) {
*action = 0;
} else {
*action = 1;
}
return 0;
}
/*
* Remove a name from the leaf attribute list structure.
*
* Return 1 if leaf is less than 37% full, 0 if >= 37% full.
* If two leaves are 37% full, when combined they will leave 25% free.
*/
int
xfs_attr3_leaf_remove(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
int before;
int after;
int smallest;
int entsize;
int tablesize;
int tmp;
int i;
trace_xfs_attr_leaf_remove(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
ASSERT(ichdr.count > 0 && ichdr.count < args->geo->blksize / 8);
ASSERT(args->index >= 0 && args->index < ichdr.count);
ASSERT(ichdr.firstused >= ichdr.count * sizeof(*entry) +
xfs_attr3_leaf_hdr_size(leaf));
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT(be16_to_cpu(entry->nameidx) >= ichdr.firstused);
ASSERT(be16_to_cpu(entry->nameidx) < args->geo->blksize);
/*
* Scan through free region table:
* check for adjacency of free'd entry with an existing one,
* find smallest free region in case we need to replace it,
* adjust any map that borders the entry table,
*/
tablesize = ichdr.count * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf);
tmp = ichdr.freemap[0].size;
before = after = -1;
smallest = XFS_ATTR_LEAF_MAPSIZE - 1;
entsize = xfs_attr_leaf_entsize(leaf, args->index);
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
ASSERT(ichdr.freemap[i].base < args->geo->blksize);
ASSERT(ichdr.freemap[i].size < args->geo->blksize);
if (ichdr.freemap[i].base == tablesize) {
ichdr.freemap[i].base -= sizeof(xfs_attr_leaf_entry_t);
ichdr.freemap[i].size += sizeof(xfs_attr_leaf_entry_t);
}
if (ichdr.freemap[i].base + ichdr.freemap[i].size ==
be16_to_cpu(entry->nameidx)) {
before = i;
} else if (ichdr.freemap[i].base ==
(be16_to_cpu(entry->nameidx) + entsize)) {
after = i;
} else if (ichdr.freemap[i].size < tmp) {
tmp = ichdr.freemap[i].size;
smallest = i;
}
}
/*
* Coalesce adjacent freemap regions,
* or replace the smallest region.
*/
if ((before >= 0) || (after >= 0)) {
if ((before >= 0) && (after >= 0)) {
ichdr.freemap[before].size += entsize;
ichdr.freemap[before].size += ichdr.freemap[after].size;
ichdr.freemap[after].base = 0;
ichdr.freemap[after].size = 0;
} else if (before >= 0) {
ichdr.freemap[before].size += entsize;
} else {
ichdr.freemap[after].base = be16_to_cpu(entry->nameidx);
ichdr.freemap[after].size += entsize;
}
} else {
/*
* Replace smallest region (if it is smaller than free'd entry)
*/
if (ichdr.freemap[smallest].size < entsize) {
ichdr.freemap[smallest].base = be16_to_cpu(entry->nameidx);
ichdr.freemap[smallest].size = entsize;
}
}
/*
* Did we remove the first entry?
*/
if (be16_to_cpu(entry->nameidx) == ichdr.firstused)
smallest = 1;
else
smallest = 0;
/*
* Compress the remaining entries and zero out the removed stuff.
*/
memset(xfs_attr3_leaf_name(leaf, args->index), 0, entsize);
ichdr.usedbytes -= entsize;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index),
entsize));
tmp = (ichdr.count - args->index) * sizeof(xfs_attr_leaf_entry_t);
memmove(entry, entry + 1, tmp);
ichdr.count--;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(xfs_attr_leaf_entry_t)));
entry = &xfs_attr3_leaf_entryp(leaf)[ichdr.count];
memset(entry, 0, sizeof(xfs_attr_leaf_entry_t));
/*
* If we removed the first entry, re-find the first used byte
* in the name area. Note that if the entry was the "firstused",
* then we don't have a "hole" in our block resulting from
* removing the name.
*/
if (smallest) {
tmp = args->geo->blksize;
entry = xfs_attr3_leaf_entryp(leaf);
for (i = ichdr.count - 1; i >= 0; entry++, i--) {
ASSERT(be16_to_cpu(entry->nameidx) >= ichdr.firstused);
ASSERT(be16_to_cpu(entry->nameidx) < args->geo->blksize);
if (be16_to_cpu(entry->nameidx) < tmp)
tmp = be16_to_cpu(entry->nameidx);
}
ichdr.firstused = tmp;
ASSERT(ichdr.firstused != 0);
} else {
ichdr.holes = 1; /* mark as needing compaction */
}
xfs_attr3_leaf_hdr_to_disk(args->geo, leaf, &ichdr);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, &leaf->hdr,
xfs_attr3_leaf_hdr_size(leaf)));
/*
* Check if leaf is less than 50% full, caller may want to
* "join" the leaf with a sibling if so.
*/
tmp = ichdr.usedbytes + xfs_attr3_leaf_hdr_size(leaf) +
ichdr.count * sizeof(xfs_attr_leaf_entry_t);
return tmp < args->geo->magicpct; /* leaf is < 37% full */
}
/*
* Move all the attribute list entries from drop_leaf into save_leaf.
*/
void
xfs_attr3_leaf_unbalance(
struct xfs_da_state *state,
struct xfs_da_state_blk *drop_blk,
struct xfs_da_state_blk *save_blk)
{
struct xfs_attr_leafblock *drop_leaf = drop_blk->bp->b_addr;
struct xfs_attr_leafblock *save_leaf = save_blk->bp->b_addr;
struct xfs_attr3_icleaf_hdr drophdr;
struct xfs_attr3_icleaf_hdr savehdr;
struct xfs_attr_leaf_entry *entry;
trace_xfs_attr_leaf_unbalance(state->args);
drop_leaf = drop_blk->bp->b_addr;
save_leaf = save_blk->bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(state->args->geo, &drophdr, drop_leaf);
xfs_attr3_leaf_hdr_from_disk(state->args->geo, &savehdr, save_leaf);
entry = xfs_attr3_leaf_entryp(drop_leaf);
/*
* Save last hashval from dying block for later Btree fixup.
*/
drop_blk->hashval = be32_to_cpu(entry[drophdr.count - 1].hashval);
/*
* Check if we need a temp buffer, or can we do it in place.
* Note that we don't check "leaf" for holes because we will
* always be dropping it, toosmall() decided that for us already.
*/
if (savehdr.holes == 0) {
/*
* dest leaf has no holes, so we add there. May need
* to make some room in the entry array.
*/
if (xfs_attr3_leaf_order(save_blk->bp, &savehdr,
drop_blk->bp, &drophdr)) {
xfs_attr3_leaf_moveents(state->args,
drop_leaf, &drophdr, 0,
save_leaf, &savehdr, 0,
drophdr.count);
} else {
xfs_attr3_leaf_moveents(state->args,
drop_leaf, &drophdr, 0,
save_leaf, &savehdr,
savehdr.count, drophdr.count);
}
} else {
/*
* Destination has holes, so we make a temporary copy
* of the leaf and add them both to that.
*/
struct xfs_attr_leafblock *tmp_leaf;
struct xfs_attr3_icleaf_hdr tmphdr;
tmp_leaf = kmem_zalloc(state->args->geo->blksize, KM_SLEEP);
/*
* Copy the header into the temp leaf so that all the stuff
* not in the incore header is present and gets copied back in
* once we've moved all the entries.
*/
memcpy(tmp_leaf, save_leaf, xfs_attr3_leaf_hdr_size(save_leaf));
memset(&tmphdr, 0, sizeof(tmphdr));
tmphdr.magic = savehdr.magic;
tmphdr.forw = savehdr.forw;
tmphdr.back = savehdr.back;
tmphdr.firstused = state->args->geo->blksize;
/* write the header to the temp buffer to initialise it */
xfs_attr3_leaf_hdr_to_disk(state->args->geo, tmp_leaf, &tmphdr);
if (xfs_attr3_leaf_order(save_blk->bp, &savehdr,
drop_blk->bp, &drophdr)) {
xfs_attr3_leaf_moveents(state->args,
drop_leaf, &drophdr, 0,
tmp_leaf, &tmphdr, 0,
drophdr.count);
xfs_attr3_leaf_moveents(state->args,
save_leaf, &savehdr, 0,
tmp_leaf, &tmphdr, tmphdr.count,
savehdr.count);
} else {
xfs_attr3_leaf_moveents(state->args,
save_leaf, &savehdr, 0,
tmp_leaf, &tmphdr, 0,
savehdr.count);
xfs_attr3_leaf_moveents(state->args,
drop_leaf, &drophdr, 0,
tmp_leaf, &tmphdr, tmphdr.count,
drophdr.count);
}
memcpy(save_leaf, tmp_leaf, state->args->geo->blksize);
savehdr = tmphdr; /* struct copy */
kmem_free(tmp_leaf);
}
xfs_attr3_leaf_hdr_to_disk(state->args->geo, save_leaf, &savehdr);
xfs_trans_log_buf(state->args->trans, save_blk->bp, 0,
state->args->geo->blksize - 1);
/*
* Copy out last hashval in each block for B-tree code.
*/
entry = xfs_attr3_leaf_entryp(save_leaf);
save_blk->hashval = be32_to_cpu(entry[savehdr.count - 1].hashval);
}
/*========================================================================
* Routines used for finding things in the Btree.
*========================================================================*/
/*
* Look up a name in a leaf attribute list structure.
* This is the internal routine, it uses the caller's buffer.
*
* Note that duplicate keys are allowed, but only check within the
* current leaf node. The Btree code must check in adjacent leaf nodes.
*
* Return in args->index the index into the entry[] array of either
* the found entry, or where the entry should have been (insert before
* that entry).
*
* Don't change the args->value unless we find the attribute.
*/
int
xfs_attr3_leaf_lookup_int(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_entry *entries;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
xfs_dahash_t hashval;
int probe;
int span;
trace_xfs_attr_leaf_lookup(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
if (ichdr.count >= args->geo->blksize / 8)
return -EFSCORRUPTED;
/*
* Binary search. (note: small blocks will skip this loop)
*/
hashval = args->hashval;
probe = span = ichdr.count / 2;
for (entry = &entries[probe]; span > 4; entry = &entries[probe]) {
span /= 2;
if (be32_to_cpu(entry->hashval) < hashval)
probe += span;
else if (be32_to_cpu(entry->hashval) > hashval)
probe -= span;
else
break;
}
if (!(probe >= 0 && (!ichdr.count || probe < ichdr.count)))
return -EFSCORRUPTED;
if (!(span <= 4 || be32_to_cpu(entry->hashval) == hashval))
return -EFSCORRUPTED;
/*
* Since we may have duplicate hashval's, find the first matching
* hashval in the leaf.
*/
while (probe > 0 && be32_to_cpu(entry->hashval) >= hashval) {
entry--;
probe--;
}
while (probe < ichdr.count &&
be32_to_cpu(entry->hashval) < hashval) {
entry++;
probe++;
}
if (probe == ichdr.count || be32_to_cpu(entry->hashval) != hashval) {
args->index = probe;
return -ENOATTR;
}
/*
* Duplicate keys may be present, so search all of them for a match.
*/
for (; probe < ichdr.count && (be32_to_cpu(entry->hashval) == hashval);
entry++, probe++) {
/*
* GROT: Add code to remove incomplete entries.
*/
/*
* If we are looking for INCOMPLETE entries, show only those.
* If we are looking for complete entries, show only those.
*/
if ((args->flags & XFS_ATTR_INCOMPLETE) !=
(entry->flags & XFS_ATTR_INCOMPLETE)) {
continue;
}
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, probe);
if (name_loc->namelen != args->namelen)
continue;
if (memcmp(args->name, name_loc->nameval,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
return -EEXIST;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, probe);
if (name_rmt->namelen != args->namelen)
continue;
if (memcmp(args->name, name_rmt->name,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
args->rmtvaluelen = be32_to_cpu(name_rmt->valuelen);
args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
args->rmtblkcnt = xfs_attr3_rmt_blocks(
args->dp->i_mount,
args->rmtvaluelen);
return -EEXIST;
}
}
args->index = probe;
return -ENOATTR;
}
/*
* Get the value associated with an attribute name from a leaf attribute
* list structure.
*/
int
xfs_attr3_leaf_getvalue(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
int valuelen;
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
ASSERT(ichdr.count < args->geo->blksize / 8);
ASSERT(args->index < ichdr.count);
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
ASSERT(name_loc->namelen == args->namelen);
ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0);
valuelen = be16_to_cpu(name_loc->valuelen);
if (args->flags & ATTR_KERNOVAL) {
args->valuelen = valuelen;
return 0;
}
if (args->valuelen < valuelen) {
args->valuelen = valuelen;
return -ERANGE;
}
args->valuelen = valuelen;
memcpy(args->value, &name_loc->nameval[args->namelen], valuelen);
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
ASSERT(name_rmt->namelen == args->namelen);
ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0);
args->rmtvaluelen = be32_to_cpu(name_rmt->valuelen);
args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount,
args->rmtvaluelen);
if (args->flags & ATTR_KERNOVAL) {
args->valuelen = args->rmtvaluelen;
return 0;
}
if (args->valuelen < args->rmtvaluelen) {
args->valuelen = args->rmtvaluelen;
return -ERANGE;
}
args->valuelen = args->rmtvaluelen;
}
return 0;
}
/*========================================================================
* Utility routines.
*========================================================================*/
/*
* Move the indicated entries from one leaf to another.
* NOTE: this routine modifies both source and destination leaves.
*/
/*ARGSUSED*/
STATIC void
xfs_attr3_leaf_moveents(
struct xfs_da_args *args,
struct xfs_attr_leafblock *leaf_s,
struct xfs_attr3_icleaf_hdr *ichdr_s,
int start_s,
struct xfs_attr_leafblock *leaf_d,
struct xfs_attr3_icleaf_hdr *ichdr_d,
int start_d,
int count)
{
struct xfs_attr_leaf_entry *entry_s;
struct xfs_attr_leaf_entry *entry_d;
int desti;
int tmp;
int i;
/*
* Check for nothing to do.
*/
if (count == 0)
return;
/*
* Set up environment.
*/
ASSERT(ichdr_s->magic == XFS_ATTR_LEAF_MAGIC ||
ichdr_s->magic == XFS_ATTR3_LEAF_MAGIC);
ASSERT(ichdr_s->magic == ichdr_d->magic);
ASSERT(ichdr_s->count > 0 && ichdr_s->count < args->geo->blksize / 8);
ASSERT(ichdr_s->firstused >= (ichdr_s->count * sizeof(*entry_s))
+ xfs_attr3_leaf_hdr_size(leaf_s));
ASSERT(ichdr_d->count < args->geo->blksize / 8);
ASSERT(ichdr_d->firstused >= (ichdr_d->count * sizeof(*entry_d))
+ xfs_attr3_leaf_hdr_size(leaf_d));
ASSERT(start_s < ichdr_s->count);
ASSERT(start_d <= ichdr_d->count);
ASSERT(count <= ichdr_s->count);
/*
* Move the entries in the destination leaf up to make a hole?
*/
if (start_d < ichdr_d->count) {
tmp = ichdr_d->count - start_d;
tmp *= sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_d)[start_d];
entry_d = &xfs_attr3_leaf_entryp(leaf_d)[start_d + count];
memmove(entry_d, entry_s, tmp);
}
/*
* Copy all entry's in the same (sorted) order,
* but allocate attribute info packed and in sequence.
*/
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
entry_d = &xfs_attr3_leaf_entryp(leaf_d)[start_d];
desti = start_d;
for (i = 0; i < count; entry_s++, entry_d++, desti++, i++) {
ASSERT(be16_to_cpu(entry_s->nameidx) >= ichdr_s->firstused);
tmp = xfs_attr_leaf_entsize(leaf_s, start_s + i);
#ifdef GROT
/*
* Code to drop INCOMPLETE entries. Difficult to use as we
* may also need to change the insertion index. Code turned
* off for 6.2, should be revisited later.
*/
if (entry_s->flags & XFS_ATTR_INCOMPLETE) { /* skip partials? */
memset(xfs_attr3_leaf_name(leaf_s, start_s + i), 0, tmp);
ichdr_s->usedbytes -= tmp;
ichdr_s->count -= 1;
entry_d--; /* to compensate for ++ in loop hdr */
desti--;
if ((start_s + i) < offset)
result++; /* insertion index adjustment */
} else {
#endif /* GROT */
ichdr_d->firstused -= tmp;
/* both on-disk, don't endian flip twice */
entry_d->hashval = entry_s->hashval;
entry_d->nameidx = cpu_to_be16(ichdr_d->firstused);
entry_d->flags = entry_s->flags;
ASSERT(be16_to_cpu(entry_d->nameidx) + tmp
<= args->geo->blksize);
memmove(xfs_attr3_leaf_name(leaf_d, desti),
xfs_attr3_leaf_name(leaf_s, start_s + i), tmp);
ASSERT(be16_to_cpu(entry_s->nameidx) + tmp
<= args->geo->blksize);
memset(xfs_attr3_leaf_name(leaf_s, start_s + i), 0, tmp);
ichdr_s->usedbytes -= tmp;
ichdr_d->usedbytes += tmp;
ichdr_s->count -= 1;
ichdr_d->count += 1;
tmp = ichdr_d->count * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf_d);
ASSERT(ichdr_d->firstused >= tmp);
#ifdef GROT
}
#endif /* GROT */
}
/*
* Zero out the entries we just copied.
*/
if (start_s == ichdr_s->count) {
tmp = count * sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
ASSERT(((char *)entry_s + tmp) <=
((char *)leaf_s + args->geo->blksize));
memset(entry_s, 0, tmp);
} else {
/*
* Move the remaining entries down to fill the hole,
* then zero the entries at the top.
*/
tmp = (ichdr_s->count - count) * sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s + count];
entry_d = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
memmove(entry_d, entry_s, tmp);
tmp = count * sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[ichdr_s->count];
ASSERT(((char *)entry_s + tmp) <=
((char *)leaf_s + args->geo->blksize));
memset(entry_s, 0, tmp);
}
/*
* Fill in the freemap information
*/
ichdr_d->freemap[0].base = xfs_attr3_leaf_hdr_size(leaf_d);
ichdr_d->freemap[0].base += ichdr_d->count * sizeof(xfs_attr_leaf_entry_t);
ichdr_d->freemap[0].size = ichdr_d->firstused - ichdr_d->freemap[0].base;
ichdr_d->freemap[1].base = 0;
ichdr_d->freemap[2].base = 0;
ichdr_d->freemap[1].size = 0;
ichdr_d->freemap[2].size = 0;
ichdr_s->holes = 1; /* leaf may not be compact */
}
/*
* Pick up the last hashvalue from a leaf block.
*/
xfs_dahash_t
xfs_attr_leaf_lasthash(
struct xfs_buf *bp,
int *count)
{
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entries;
struct xfs_mount *mp = bp->b_target->bt_mount;
xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &ichdr, bp->b_addr);
entries = xfs_attr3_leaf_entryp(bp->b_addr);
if (count)
*count = ichdr.count;
if (!ichdr.count)
return 0;
return be32_to_cpu(entries[ichdr.count - 1].hashval);
}
/*
* Calculate the number of bytes used to store the indicated attribute
* (whether local or remote only calculate bytes in this block).
*/
STATIC int
xfs_attr_leaf_entsize(xfs_attr_leafblock_t *leaf, int index)
{
struct xfs_attr_leaf_entry *entries;
xfs_attr_leaf_name_local_t *name_loc;
xfs_attr_leaf_name_remote_t *name_rmt;
int size;
entries = xfs_attr3_leaf_entryp(leaf);
if (entries[index].flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, index);
size = xfs_attr_leaf_entsize_local(name_loc->namelen,
be16_to_cpu(name_loc->valuelen));
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, index);
size = xfs_attr_leaf_entsize_remote(name_rmt->namelen);
}
return size;
}
/*
* Calculate the number of bytes that would be required to store the new
* attribute (whether local or remote only calculate bytes in this block).
* This routine decides as a side effect whether the attribute will be
* a "local" or a "remote" attribute.
*/
int
xfs_attr_leaf_newentsize(
struct xfs_da_args *args,
int *local)
{
int size;
size = xfs_attr_leaf_entsize_local(args->namelen, args->valuelen);
if (size < xfs_attr_leaf_entsize_local_max(args->geo->blksize)) {
if (local)
*local = 1;
return size;
}
if (local)
*local = 0;
return xfs_attr_leaf_entsize_remote(args->namelen);
}
/*========================================================================
* Manage the INCOMPLETE flag in a leaf entry
*========================================================================*/
/*
* Clear the INCOMPLETE flag on an entry in a leaf block.
*/
int
xfs_attr3_leaf_clearflag(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr;
xfs_attr_leaf_name_local_t *name_loc;
int namelen;
char *name;
#endif /* DEBUG */
trace_xfs_attr_leaf_clearflag(args);
/*
* Set up the operation.
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return error;
leaf = bp->b_addr;
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT(entry->flags & XFS_ATTR_INCOMPLETE);
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
ASSERT(args->index < ichdr.count);
ASSERT(args->index >= 0);
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
namelen = name_loc->namelen;
name = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
namelen = name_rmt->namelen;
name = (char *)name_rmt->name;
}
ASSERT(be32_to_cpu(entry->hashval) == args->hashval);
ASSERT(namelen == args->namelen);
ASSERT(memcmp(name, args->name, namelen) == 0);
#endif /* DEBUG */
entry->flags &= ~XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
if (args->rmtblkno) {
ASSERT((entry->flags & XFS_ATTR_LOCAL) == 0);
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
name_rmt->valuelen = cpu_to_be32(args->rmtvaluelen);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
return xfs_trans_roll_inode(&args->trans, args->dp);
}
/*
* Set the INCOMPLETE flag on an entry in a leaf block.
*/
int
xfs_attr3_leaf_setflag(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr;
#endif
trace_xfs_attr_leaf_setflag(args);
/*
* Set up the operation.
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return error;
leaf = bp->b_addr;
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
ASSERT(args->index < ichdr.count);
ASSERT(args->index >= 0);
#endif
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT((entry->flags & XFS_ATTR_INCOMPLETE) == 0);
entry->flags |= XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
if ((entry->flags & XFS_ATTR_LOCAL) == 0) {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->valueblk = 0;
name_rmt->valuelen = 0;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
return xfs_trans_roll_inode(&args->trans, args->dp);
}
/*
* In a single transaction, clear the INCOMPLETE flag on the leaf entry
* given by args->blkno/index and set the INCOMPLETE flag on the leaf
* entry given by args->blkno2/index2.
*
* Note that they could be in different blocks, or in the same block.
*/
int
xfs_attr3_leaf_flipflags(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf1;
struct xfs_attr_leafblock *leaf2;
struct xfs_attr_leaf_entry *entry1;
struct xfs_attr_leaf_entry *entry2;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp1;
struct xfs_buf *bp2;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr1;
struct xfs_attr3_icleaf_hdr ichdr2;
xfs_attr_leaf_name_local_t *name_loc;
int namelen1, namelen2;
char *name1, *name2;
#endif /* DEBUG */
trace_xfs_attr_leaf_flipflags(args);
/*
* Read the block containing the "old" attr
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp1);
if (error)
return error;
/*
* Read the block containing the "new" attr, if it is different
*/
if (args->blkno2 != args->blkno) {
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno2,
-1, &bp2);
if (error)
return error;
} else {
bp2 = bp1;
}
leaf1 = bp1->b_addr;
entry1 = &xfs_attr3_leaf_entryp(leaf1)[args->index];
leaf2 = bp2->b_addr;
entry2 = &xfs_attr3_leaf_entryp(leaf2)[args->index2];
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr1, leaf1);
ASSERT(args->index < ichdr1.count);
ASSERT(args->index >= 0);
xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr2, leaf2);
ASSERT(args->index2 < ichdr2.count);
ASSERT(args->index2 >= 0);
if (entry1->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf1, args->index);
namelen1 = name_loc->namelen;
name1 = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index);
namelen1 = name_rmt->namelen;
name1 = (char *)name_rmt->name;
}
if (entry2->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf2, args->index2);
namelen2 = name_loc->namelen;
name2 = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2);
namelen2 = name_rmt->namelen;
name2 = (char *)name_rmt->name;
}
ASSERT(be32_to_cpu(entry1->hashval) == be32_to_cpu(entry2->hashval));
ASSERT(namelen1 == namelen2);
ASSERT(memcmp(name1, name2, namelen1) == 0);
#endif /* DEBUG */
ASSERT(entry1->flags & XFS_ATTR_INCOMPLETE);
ASSERT((entry2->flags & XFS_ATTR_INCOMPLETE) == 0);
entry1->flags &= ~XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp1,
XFS_DA_LOGRANGE(leaf1, entry1, sizeof(*entry1)));
if (args->rmtblkno) {
ASSERT((entry1->flags & XFS_ATTR_LOCAL) == 0);
name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index);
name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
name_rmt->valuelen = cpu_to_be32(args->rmtvaluelen);
xfs_trans_log_buf(args->trans, bp1,
XFS_DA_LOGRANGE(leaf1, name_rmt, sizeof(*name_rmt)));
}
entry2->flags |= XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp2,
XFS_DA_LOGRANGE(leaf2, entry2, sizeof(*entry2)));
if ((entry2->flags & XFS_ATTR_LOCAL) == 0) {
name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2);
name_rmt->valueblk = 0;
name_rmt->valuelen = 0;
xfs_trans_log_buf(args->trans, bp2,
XFS_DA_LOGRANGE(leaf2, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
error = xfs_trans_roll_inode(&args->trans, args->dp);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_213_0 |
crossvul-cpp_data_good_2561_1 | /*
nicklist.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 "misc.h"
#include "servers.h"
#include "channels.h"
#include "nicklist.h"
#include "masks.h"
#define isalnumhigh(a) \
(i_isalnum(a) || (unsigned char) (a) >= 128)
static void nick_hash_add(CHANNEL_REC *channel, NICK_REC *nick)
{
NICK_REC *list;
nick->next = NULL;
list = g_hash_table_lookup(channel->nicks, nick->nick);
if (list == NULL)
g_hash_table_insert(channel->nicks, nick->nick, nick);
else {
/* multiple nicks with same name */
while (list->next != NULL)
list = list->next;
list->next = nick;
}
if (nick == channel->ownnick) {
/* move our own nick to beginning of the nick list.. */
nicklist_set_own(channel, nick);
}
}
static void nick_hash_remove(CHANNEL_REC *channel, NICK_REC *nick)
{
NICK_REC *list, *newlist;
list = g_hash_table_lookup(channel->nicks, nick->nick);
if (list == NULL)
return;
if (list == nick) {
newlist = nick->next;
} else {
newlist = list;
while (list->next != nick)
list = list->next;
list->next = nick->next;
}
g_hash_table_remove(channel->nicks, nick->nick);
if (newlist != NULL) {
g_hash_table_insert(channel->nicks, newlist->nick,
newlist);
}
}
/* Add new nick to list */
void nicklist_insert(CHANNEL_REC *channel, NICK_REC *nick)
{
/*MODULE_DATA_INIT(nick);*/
nick->type = module_get_uniq_id("NICK", 0);
nick->chat_type = channel->chat_type;
nick_hash_add(channel, nick);
signal_emit("nicklist new", 2, channel, nick);
}
/* Set host address for nick */
void nicklist_set_host(CHANNEL_REC *channel, NICK_REC *nick, const char *host)
{
g_return_if_fail(channel != NULL);
g_return_if_fail(nick != NULL);
g_return_if_fail(host != NULL);
g_free_not_null(nick->host);
nick->host = g_strdup(host);
signal_emit("nicklist host changed", 2, channel, nick);
}
static void nicklist_destroy(CHANNEL_REC *channel, NICK_REC *nick)
{
signal_emit("nicklist remove", 2, channel, nick);
if (channel->ownnick == nick)
channel->ownnick = NULL;
/*MODULE_DATA_DEINIT(nick);*/
g_free(nick->nick);
g_free_not_null(nick->realname);
g_free_not_null(nick->host);
g_free(nick);
}
/* Remove nick from list */
void nicklist_remove(CHANNEL_REC *channel, NICK_REC *nick)
{
g_return_if_fail(IS_CHANNEL(channel));
g_return_if_fail(nick != NULL);
nick_hash_remove(channel, nick);
nicklist_destroy(channel, nick);
}
static void nicklist_rename_list(SERVER_REC *server, void *new_nick_id,
const char *old_nick, const char *new_nick,
GSList *nicks)
{
CHANNEL_REC *channel;
NICK_REC *nickrec;
GSList *tmp;
for (tmp = nicks; tmp != NULL; tmp = tmp->next->next) {
channel = tmp->data;
nickrec = tmp->next->data;
/* remove old nick from hash table */
nick_hash_remove(channel, nickrec);
if (new_nick_id != NULL)
nickrec->unique_id = new_nick_id;
g_free(nickrec->nick);
nickrec->nick = g_strdup(new_nick);
/* add new nick to hash table */
nick_hash_add(channel, nickrec);
signal_emit("nicklist changed", 3, channel, nickrec, old_nick);
}
g_slist_free(nicks);
}
void nicklist_rename(SERVER_REC *server, const char *old_nick,
const char *new_nick)
{
nicklist_rename_list(server, NULL, old_nick, new_nick,
nicklist_get_same(server, old_nick));
}
void nicklist_rename_unique(SERVER_REC *server,
void *old_nick_id, const char *old_nick,
void *new_nick_id, const char *new_nick)
{
nicklist_rename_list(server, new_nick_id, old_nick, new_nick,
nicklist_get_same_unique(server, old_nick_id));
}
static NICK_REC *nicklist_find_wildcards(CHANNEL_REC *channel,
const char *mask)
{
NICK_REC *nick;
GHashTableIter iter;
g_hash_table_iter_init(&iter, channel->nicks);
while (g_hash_table_iter_next(&iter, NULL, (void*)&nick)) {
for (; nick != NULL; nick = nick->next) {
if (mask_match_address(channel->server, mask,
nick->nick, nick->host))
return nick;
}
}
return NULL;
}
GSList *nicklist_find_multiple(CHANNEL_REC *channel, const char *mask)
{
GSList *nicks;
NICK_REC *nick;
GHashTableIter iter;
g_return_val_if_fail(IS_CHANNEL(channel), NULL);
g_return_val_if_fail(mask != NULL, NULL);
nicks = NULL;
g_hash_table_iter_init(&iter, channel->nicks);
while (g_hash_table_iter_next(&iter, NULL, (void*)&nick)) {
for (; nick != NULL; nick = nick->next) {
if (mask_match_address(channel->server, mask,
nick->nick, nick->host))
nicks = g_slist_prepend(nicks, nick);
}
}
return nicks;
}
/* Find nick */
NICK_REC *nicklist_find(CHANNEL_REC *channel, const char *nick)
{
g_return_val_if_fail(IS_CHANNEL(channel), NULL);
g_return_val_if_fail(nick != NULL, NULL);
return g_hash_table_lookup(channel->nicks, nick);
}
NICK_REC *nicklist_find_unique(CHANNEL_REC *channel, const char *nick,
void *id)
{
NICK_REC *rec;
g_return_val_if_fail(IS_CHANNEL(channel), NULL);
g_return_val_if_fail(nick != NULL, NULL);
rec = g_hash_table_lookup(channel->nicks, nick);
while (rec != NULL && rec->unique_id != id)
rec = rec->next;
return rec;
}
/* Find nick mask, wildcards allowed */
NICK_REC *nicklist_find_mask(CHANNEL_REC *channel, const char *mask)
{
NICK_REC *nickrec;
char *nick, *host;
g_return_val_if_fail(IS_CHANNEL(channel), NULL);
g_return_val_if_fail(mask != NULL, NULL);
nick = g_strdup(mask);
host = strchr(nick, '!');
if (host != NULL) *host++ = '\0';
if (strchr(nick, '*') || strchr(nick, '?')) {
g_free(nick);
return nicklist_find_wildcards(channel, mask);
}
nickrec = g_hash_table_lookup(channel->nicks, nick);
if (host != NULL) {
while (nickrec != NULL) {
if (nickrec->host != NULL &&
match_wildcards(host, nickrec->host))
break; /* match */
nickrec = nickrec->next;
}
}
g_free(nick);
return nickrec;
}
static void get_nicks_hash(gpointer key, NICK_REC *rec, GSList **list)
{
while (rec != NULL) {
*list = g_slist_prepend(*list, rec);
rec = rec->next;
}
}
/* Get list of nicks */
GSList *nicklist_getnicks(CHANNEL_REC *channel)
{
GSList *list;
g_return_val_if_fail(IS_CHANNEL(channel), NULL);
list = NULL;
g_hash_table_foreach(channel->nicks, (GHFunc) get_nicks_hash, &list);
return list;
}
GSList *nicklist_get_same(SERVER_REC *server, const char *nick)
{
GSList *tmp;
GSList *list = NULL;
g_return_val_if_fail(IS_SERVER(server), NULL);
for (tmp = server->channels; tmp != NULL; tmp = tmp->next) {
NICK_REC *nick_rec;
CHANNEL_REC *channel = tmp->data;
for (nick_rec = g_hash_table_lookup(channel->nicks, nick);
nick_rec != NULL;
nick_rec = nick_rec->next) {
list = g_slist_append(list, channel);
list = g_slist_append(list, nick_rec);
}
}
return list;
}
typedef struct {
CHANNEL_REC *channel;
void *id;
GSList *list;
} NICKLIST_GET_SAME_UNIQUE_REC;
static void get_nicks_same_hash_unique(gpointer key, NICK_REC *nick,
NICKLIST_GET_SAME_UNIQUE_REC *rec)
{
while (nick != NULL) {
if (nick->unique_id == rec->id) {
rec->list = g_slist_append(rec->list, rec->channel);
rec->list = g_slist_append(rec->list, nick);
break;
}
nick = nick->next;
}
}
GSList *nicklist_get_same_unique(SERVER_REC *server, void *id)
{
NICKLIST_GET_SAME_UNIQUE_REC rec;
GSList *tmp;
g_return_val_if_fail(IS_SERVER(server), NULL);
g_return_val_if_fail(id != NULL, NULL);
rec.id = id;
rec.list = NULL;
for (tmp = server->channels; tmp != NULL; tmp = tmp->next) {
rec.channel = tmp->data;
g_hash_table_foreach(rec.channel->nicks,
(GHFunc) get_nicks_same_hash_unique,
&rec);
}
return rec.list;
}
/* nick record comparison for sort functions */
int nicklist_compare(NICK_REC *p1, NICK_REC *p2, const char *nick_prefix)
{
int i;
if (p1 == NULL) return -1;
if (p2 == NULL) return 1;
if (p1->prefixes[0] == p2->prefixes[0])
return g_ascii_strcasecmp(p1->nick, p2->nick);
if (!p1->prefixes[0])
return 1;
if (!p2->prefixes[0])
return -1;
/* They aren't equal. We've taken care of that already.
* The first one we encounter in this list is the greater.
*/
for (i = 0; nick_prefix[i] != '\0'; i++) {
if (p1->prefixes[0] == nick_prefix[i])
return -1;
if (p2->prefixes[0] == nick_prefix[i])
return 1;
}
/* we should never have gotten here... */
return g_ascii_strcasecmp(p1->nick, p2->nick);
}
static void nicklist_update_flags_list(SERVER_REC *server, int gone,
int serverop, GSList *nicks)
{
GSList *tmp;
CHANNEL_REC *channel;
NICK_REC *rec;
g_return_if_fail(IS_SERVER(server));
for (tmp = nicks; tmp != NULL; tmp = tmp->next->next) {
channel = tmp->data;
rec = tmp->next->data;
rec->last_check = time(NULL);
if (gone != -1 && (int)rec->gone != gone) {
rec->gone = gone;
signal_emit("nicklist gone changed", 2, channel, rec);
}
if (serverop != -1 && (int)rec->serverop != serverop) {
rec->serverop = serverop;
signal_emit("nicklist serverop changed", 2, channel, rec);
}
}
g_slist_free(nicks);
}
void nicklist_update_flags(SERVER_REC *server, const char *nick,
int gone, int serverop)
{
nicklist_update_flags_list(server, gone, serverop,
nicklist_get_same(server, nick));
}
void nicklist_update_flags_unique(SERVER_REC *server, void *id,
int gone, int serverop)
{
nicklist_update_flags_list(server, gone, serverop,
nicklist_get_same_unique(server, id));
}
/* Specify which nick in channel is ours */
void nicklist_set_own(CHANNEL_REC *channel, NICK_REC *nick)
{
NICK_REC *first, *next;
channel->ownnick = nick;
/* move our nick in the list to first, makes some things easier
(like handling multiple identical nicks in fe-messages.c) */
first = g_hash_table_lookup(channel->nicks, nick->nick);
if (first->next == NULL)
return;
next = nick->next;
nick->next = first;
while (first->next != nick)
first = first->next;
first->next = next;
g_hash_table_insert(channel->nicks, nick->nick, nick);
}
static void sig_channel_created(CHANNEL_REC *channel)
{
g_return_if_fail(IS_CHANNEL(channel));
channel->nicks = g_hash_table_new((GHashFunc) g_istr_hash,
(GCompareFunc) g_istr_equal);
}
static void nicklist_remove_hash(gpointer key, NICK_REC *nick,
CHANNEL_REC *channel)
{
NICK_REC *next;
while (nick != NULL) {
next = nick->next;
nicklist_destroy(channel, nick);
nick = next;
}
}
static void sig_channel_destroyed(CHANNEL_REC *channel)
{
g_return_if_fail(IS_CHANNEL(channel));
g_hash_table_foreach(channel->nicks,
(GHFunc) nicklist_remove_hash, channel);
g_hash_table_destroy(channel->nicks);
}
static NICK_REC *nick_nfind(CHANNEL_REC *channel, const char *nick, int len)
{
NICK_REC *rec;
char *tmpnick;
tmpnick = g_strndup(nick, len);
rec = g_hash_table_lookup(channel->nicks, tmpnick);
if (rec != NULL) {
/* if there's multiple, get the one with identical case */
while (rec->next != NULL) {
if (g_strcmp0(rec->nick, tmpnick) == 0)
break;
rec = rec->next;
}
}
g_free(tmpnick);
return rec;
}
/* Check is `msg' is meant for `nick'. */
int nick_match_msg(CHANNEL_REC *channel, const char *msg, const char *nick)
{
const char *msgstart, *orignick;
int len, fullmatch;
g_return_val_if_fail(nick != NULL, FALSE);
g_return_val_if_fail(msg != NULL, FALSE);
if (channel != NULL && channel->server->nick_match_msg != NULL)
return channel->server->nick_match_msg(msg, nick);
/* first check for identical match */
len = strlen(nick);
if (g_ascii_strncasecmp(msg, nick, len) == 0 &&
!isalnumhigh((int) msg[len]))
return TRUE;
orignick = nick;
for (;;) {
nick = orignick;
msgstart = msg;
fullmatch = TRUE;
/* check if it matches for alphanumeric parts of nick */
while (*nick != '\0' && *msg != '\0') {
if (i_toupper(*nick) == i_toupper(*msg)) {
/* total match */
msg++;
} else if (i_isalnum(*msg) && !i_isalnum(*nick)) {
/* some strange char in your nick, pass it */
fullmatch = FALSE;
} else
break;
nick++;
}
if (msg != msgstart && !isalnumhigh(*msg)) {
/* at least some of the chars in line matched the
nick, and msg continue with non-alphanum character,
this might be for us.. */
if (*nick != '\0') {
/* remove the rest of the non-alphanum chars
from nick and check if it then matches. */
fullmatch = FALSE;
while (*nick != '\0' && !i_isalnum(*nick))
nick++;
}
if (*nick == '\0') {
/* yes, match! */
break;
}
}
/* no match. check if this is a message to multiple people
(like nick1,nick2: text) */
while (*msg != '\0' && *msg != ' ' && *msg != ',') msg++;
if (*msg != ',') {
nick = orignick;
break;
}
msg++;
}
if (*nick != '\0')
return FALSE; /* didn't match */
if (fullmatch)
return TRUE; /* matched without fuzzyness */
if (channel != NULL) {
/* matched with some fuzzyness .. check if there's an exact match
for some other nick in the same channel. */
return nick_nfind(channel, msgstart, (int) (msg-msgstart)) == NULL;
} else {
return TRUE;
}
}
int nick_match_msg_everywhere(CHANNEL_REC *channel, const char *msg, const char *nick)
{
g_return_val_if_fail(nick != NULL, FALSE);
g_return_val_if_fail(msg != NULL, FALSE);
return stristr_full(msg, nick) != NULL;
}
void nicklist_init(void)
{
signal_add_first("channel created", (SIGNAL_FUNC) sig_channel_created);
signal_add("channel destroyed", (SIGNAL_FUNC) sig_channel_destroyed);
}
void nicklist_deinit(void)
{
signal_remove("channel created", (SIGNAL_FUNC) sig_channel_created);
signal_remove("channel destroyed", (SIGNAL_FUNC) sig_channel_destroyed);
module_uniq_destroy("NICK");
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_2561_1 |
crossvul-cpp_data_good_5514_0 | /*
+----------------------------------------------------------------------+
| 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: Wez Furlong <wez@php.net> |
| Marcus Boerger <helly@php.net> |
| Sterling Hughes <sterling@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* The PDO Statement Handle Class */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "ext/standard/php_var.h"
#include "php_pdo.h"
#include "php_pdo_driver.h"
#include "php_pdo_int.h"
#include "zend_exceptions.h"
#include "zend_interfaces.h"
#include "php_memory_streams.h"
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO(arginfo_pdostatement__void, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_pdostatement_execute, 0, 0, 0)
ZEND_ARG_INFO(0, bound_input_params) /* array */
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_pdostatement_fetch, 0, 0, 0)
ZEND_ARG_INFO(0, how)
ZEND_ARG_INFO(0, orientation)
ZEND_ARG_INFO(0, offset)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_pdostatement_fetchobject, 0, 0, 0)
ZEND_ARG_INFO(0, class_name)
ZEND_ARG_INFO(0, ctor_args) /* array */
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_pdostatement_fetchcolumn, 0, 0, 0)
ZEND_ARG_INFO(0, column_number)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_pdostatement_fetchall, 0, 0, 0)
ZEND_ARG_INFO(0, how)
ZEND_ARG_INFO(0, class_name)
ZEND_ARG_INFO(0, ctor_args) /* array */
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_pdostatement_bindvalue, 0, 0, 2)
ZEND_ARG_INFO(0, paramno)
ZEND_ARG_INFO(0, param)
ZEND_ARG_INFO(0, type)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_pdostatement_bindparam, 0, 0, 2)
ZEND_ARG_INFO(0, paramno)
ZEND_ARG_INFO(1, param)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, maxlen)
ZEND_ARG_INFO(0, driverdata)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_pdostatement_bindcolumn, 0, 0, 2)
ZEND_ARG_INFO(0, column)
ZEND_ARG_INFO(1, param)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, maxlen)
ZEND_ARG_INFO(0, driverdata)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_pdostatement_setattribute, 0)
ZEND_ARG_INFO(0, attribute)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_pdostatement_getattribute, 0)
ZEND_ARG_INFO(0, attribute)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_pdostatement_getcolumnmeta, 0)
ZEND_ARG_INFO(0, column)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_pdostatement_setfetchmode, 0, 0, 1)
ZEND_ARG_INFO(0, mode)
ZEND_ARG_INFO(0, params)
ZEND_END_ARG_INFO()
/* }}} */
#define PHP_STMT_GET_OBJ \
pdo_stmt_t *stmt = (pdo_stmt_t*)zend_object_store_get_object(getThis() TSRMLS_CC); \
if (!stmt->dbh) { \
RETURN_FALSE; \
} \
static PHP_FUNCTION(dbstmt_constructor) /* {{{ */
{
php_error_docref(NULL TSRMLS_CC, E_ERROR, "You should not create a PDOStatement manually");
}
/* }}} */
static inline int rewrite_name_to_position(pdo_stmt_t *stmt, struct pdo_bound_param_data *param TSRMLS_DC) /* {{{ */
{
if (stmt->bound_param_map) {
/* rewriting :name to ? style.
* We need to fixup the parameter numbers on the parameters.
* If we find that a given named parameter has been used twice,
* we will raise an error, as we can't be sure that it is safe
* to bind multiple parameters onto the same zval in the underlying
* driver */
char *name;
int position = 0;
if (stmt->named_rewrite_template) {
/* this is not an error here */
return 1;
}
if (!param->name) {
/* do the reverse; map the parameter number to the name */
if (SUCCESS == zend_hash_index_find(stmt->bound_param_map, param->paramno, (void**)&name)) {
param->name = estrdup(name);
param->namelen = strlen(param->name);
return 1;
}
pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "parameter was not defined" TSRMLS_CC);
return 0;
}
zend_hash_internal_pointer_reset(stmt->bound_param_map);
while (SUCCESS == zend_hash_get_current_data(stmt->bound_param_map, (void**)&name)) {
if (strcmp(name, param->name)) {
position++;
zend_hash_move_forward(stmt->bound_param_map);
continue;
}
if (param->paramno >= 0) {
pdo_raise_impl_error(stmt->dbh, stmt, "IM001", "PDO refuses to handle repeating the same :named parameter for multiple positions with this driver, as it might be unsafe to do so. Consider using a separate name for each parameter instead" TSRMLS_CC);
return -1;
}
param->paramno = position;
return 1;
}
pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "parameter was not defined" TSRMLS_CC);
return 0;
}
return 1;
}
/* }}} */
/* trigger callback hook for parameters */
static int dispatch_param_event(pdo_stmt_t *stmt, enum pdo_param_event event_type TSRMLS_DC) /* {{{ */
{
int ret = 1, is_param = 1;
struct pdo_bound_param_data *param;
HashTable *ht;
if (!stmt->methods->param_hook) {
return 1;
}
ht = stmt->bound_params;
iterate:
if (ht) {
zend_hash_internal_pointer_reset(ht);
while (SUCCESS == zend_hash_get_current_data(ht, (void**)¶m)) {
if (!stmt->methods->param_hook(stmt, param, event_type TSRMLS_CC)) {
ret = 0;
break;
}
zend_hash_move_forward(ht);
}
}
if (ret && is_param) {
ht = stmt->bound_columns;
is_param = 0;
goto iterate;
}
return ret;
}
/* }}} */
int pdo_stmt_describe_columns(pdo_stmt_t *stmt TSRMLS_DC) /* {{{ */
{
int col;
stmt->columns = ecalloc(stmt->column_count, sizeof(struct pdo_column_data));
for (col = 0; col < stmt->column_count; col++) {
if (!stmt->methods->describer(stmt, col TSRMLS_CC)) {
return 0;
}
/* if we are applying case conversions on column names, do so now */
if (stmt->dbh->native_case != stmt->dbh->desired_case && stmt->dbh->desired_case != PDO_CASE_NATURAL) {
char *s = stmt->columns[col].name;
switch (stmt->dbh->desired_case) {
case PDO_CASE_UPPER:
while (*s != '\0') {
*s = toupper(*s);
s++;
}
break;
case PDO_CASE_LOWER:
while (*s != '\0') {
*s = tolower(*s);
s++;
}
break;
default:
;
}
}
#if 0
/* update the column index on named bound parameters */
if (stmt->bound_params) {
struct pdo_bound_param_data *param;
if (SUCCESS == zend_hash_find(stmt->bound_params, stmt->columns[col].name,
stmt->columns[col].namelen, (void**)¶m)) {
param->paramno = col;
}
}
#endif
if (stmt->bound_columns) {
struct pdo_bound_param_data *param;
if (SUCCESS == zend_hash_find(stmt->bound_columns, stmt->columns[col].name,
stmt->columns[col].namelen, (void**)¶m)) {
param->paramno = col;
}
}
}
return 1;
}
/* }}} */
static void get_lazy_object(pdo_stmt_t *stmt, zval *return_value TSRMLS_DC) /* {{{ */
{
if (Z_TYPE(stmt->lazy_object_ref) == IS_NULL) {
Z_TYPE(stmt->lazy_object_ref) = IS_OBJECT;
Z_OBJ_HANDLE(stmt->lazy_object_ref) = zend_objects_store_put(stmt, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t)pdo_row_free_storage, NULL TSRMLS_CC);
Z_OBJ_HT(stmt->lazy_object_ref) = &pdo_row_object_handlers;
stmt->refcount++;
}
Z_TYPE_P(return_value) = IS_OBJECT;
Z_OBJ_HANDLE_P(return_value) = Z_OBJ_HANDLE(stmt->lazy_object_ref);
Z_OBJ_HT_P(return_value) = Z_OBJ_HT(stmt->lazy_object_ref);
zend_objects_store_add_ref(return_value TSRMLS_CC);
}
/* }}} */
static void param_dtor(void *data) /* {{{ */
{
struct pdo_bound_param_data *param = (struct pdo_bound_param_data *)data;
TSRMLS_FETCH();
/* tell the driver that it is going away */
if (param->stmt->methods->param_hook) {
param->stmt->methods->param_hook(param->stmt, param, PDO_PARAM_EVT_FREE TSRMLS_CC);
}
if (param->name) {
efree(param->name);
}
if (param->parameter) {
zval_ptr_dtor(&(param->parameter));
param->parameter = NULL;
}
if (param->driver_params) {
zval_ptr_dtor(&(param->driver_params));
}
}
/* }}} */
static int really_register_bound_param(struct pdo_bound_param_data *param, pdo_stmt_t *stmt, int is_param TSRMLS_DC) /* {{{ */
{
HashTable *hash;
struct pdo_bound_param_data *pparam = NULL;
hash = is_param ? stmt->bound_params : stmt->bound_columns;
if (!hash) {
ALLOC_HASHTABLE(hash);
zend_hash_init(hash, 13, NULL, param_dtor, 0);
if (is_param) {
stmt->bound_params = hash;
} else {
stmt->bound_columns = hash;
}
}
if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_STR && param->max_value_len <= 0 && ! ZVAL_IS_NULL(param->parameter)) {
if (Z_TYPE_P(param->parameter) == IS_DOUBLE) {
char *p;
int len = spprintf(&p, 0, "%.*H", (int) EG(precision), Z_DVAL_P(param->parameter));
ZVAL_STRINGL(param->parameter, p, len, 0);
} else {
convert_to_string(param->parameter);
}
} else if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_INT && Z_TYPE_P(param->parameter) == IS_BOOL) {
convert_to_long(param->parameter);
} else if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_BOOL && Z_TYPE_P(param->parameter) == IS_LONG) {
convert_to_boolean(param->parameter);
}
param->stmt = stmt;
param->is_param = is_param;
if (param->driver_params) {
Z_ADDREF_P(param->driver_params);
}
if (!is_param && param->name && stmt->columns) {
/* try to map the name to the column */
int i;
for (i = 0; i < stmt->column_count; i++) {
if (strcmp(stmt->columns[i].name, param->name) == 0) {
param->paramno = i;
break;
}
}
/* if you prepare and then execute passing an array of params keyed by names,
* then this will trigger, and we don't want that */
if (param->paramno == -1) {
char *tmp;
spprintf(&tmp, 0, "Did not find column name '%s' in the defined columns; it will not be bound", param->name);
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", tmp TSRMLS_CC);
efree(tmp);
}
}
if (param->name) {
if (is_param && param->name[0] != ':') {
char *temp = emalloc(++param->namelen + 1);
temp[0] = ':';
memmove(temp+1, param->name, param->namelen);
param->name = temp;
} else {
param->name = estrndup(param->name, param->namelen);
}
}
if (is_param && !rewrite_name_to_position(stmt, param TSRMLS_CC)) {
if (param->name) {
efree(param->name);
param->name = NULL;
}
return 0;
}
/* ask the driver to perform any normalization it needs on the
* parameter name. Note that it is illegal for the driver to take
* a reference to param, as it resides in transient storage only
* at this time. */
if (stmt->methods->param_hook) {
if (!stmt->methods->param_hook(stmt, param, PDO_PARAM_EVT_NORMALIZE
TSRMLS_CC)) {
if (param->name) {
efree(param->name);
param->name = NULL;
}
return 0;
}
}
/* delete any other parameter registered with this number.
* If the parameter is named, it will be removed and correctly
* disposed of by the hash_update call that follows */
if (param->paramno >= 0) {
zend_hash_index_del(hash, param->paramno);
}
/* allocate storage for the parameter, keyed by its "canonical" name */
if (param->name) {
zend_hash_update(hash, param->name, param->namelen, param,
sizeof(*param), (void**)&pparam);
} else {
zend_hash_index_update(hash, param->paramno, param, sizeof(*param),
(void**)&pparam);
}
/* tell the driver we just created a parameter */
if (stmt->methods->param_hook) {
if (!stmt->methods->param_hook(stmt, pparam, PDO_PARAM_EVT_ALLOC
TSRMLS_CC)) {
/* undo storage allocation; the hash will free the parameter
* name if required */
if (pparam->name) {
zend_hash_del(hash, pparam->name, pparam->namelen);
} else {
zend_hash_index_del(hash, pparam->paramno);
}
/* param->parameter is freed by hash dtor */
param->parameter = NULL;
return 0;
}
}
return 1;
}
/* }}} */
/* {{{ proto bool PDOStatement::execute([array $bound_input_params])
Execute a prepared statement, optionally binding parameters */
static PHP_METHOD(PDOStatement, execute)
{
zval *input_params = NULL;
int ret = 1;
PHP_STMT_GET_OBJ;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a!", &input_params)) {
RETURN_FALSE;
}
PDO_STMT_CLEAR_ERR();
if (input_params) {
struct pdo_bound_param_data param;
zval **tmp;
uint str_length;
ulong num_index;
if (stmt->bound_params) {
zend_hash_destroy(stmt->bound_params);
FREE_HASHTABLE(stmt->bound_params);
stmt->bound_params = NULL;
}
zend_hash_internal_pointer_reset(Z_ARRVAL_P(input_params));
while (SUCCESS == zend_hash_get_current_data(Z_ARRVAL_P(input_params), (void*)&tmp)) {
memset(¶m, 0, sizeof(param));
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_P(input_params),
¶m.name, &str_length, &num_index, 0, NULL)) {
/* yes this is correct. we don't want to count the null byte. ask wez */
param.namelen = str_length - 1;
param.paramno = -1;
} else {
/* we're okay to be zero based here */
if (num_index < 0) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY093", NULL TSRMLS_CC);
RETURN_FALSE;
}
param.paramno = num_index;
}
param.param_type = PDO_PARAM_STR;
MAKE_STD_ZVAL(param.parameter);
MAKE_COPY_ZVAL(tmp, param.parameter);
if (!really_register_bound_param(¶m, stmt, 1 TSRMLS_CC)) {
if (param.parameter) {
zval_ptr_dtor(¶m.parameter);
}
RETURN_FALSE;
}
zend_hash_move_forward(Z_ARRVAL_P(input_params));
}
}
if (PDO_PLACEHOLDER_NONE == stmt->supports_placeholders) {
/* handle the emulated parameter binding,
* stmt->active_query_string holds the query with binds expanded and
* quoted.
*/
ret = pdo_parse_params(stmt, stmt->query_string, stmt->query_stringlen,
&stmt->active_query_string, &stmt->active_query_stringlen TSRMLS_CC);
if (ret == 0) {
/* no changes were made */
stmt->active_query_string = stmt->query_string;
stmt->active_query_stringlen = stmt->query_stringlen;
ret = 1;
} else if (ret == -1) {
/* something broke */
PDO_HANDLE_STMT_ERR();
RETURN_FALSE;
}
} else if (!dispatch_param_event(stmt, PDO_PARAM_EVT_EXEC_PRE TSRMLS_CC)) {
PDO_HANDLE_STMT_ERR();
RETURN_FALSE;
}
if (stmt->methods->executer(stmt TSRMLS_CC)) {
if (stmt->active_query_string && stmt->active_query_string != stmt->query_string) {
efree(stmt->active_query_string);
}
stmt->active_query_string = NULL;
if (!stmt->executed) {
/* this is the first execute */
if (stmt->dbh->alloc_own_columns && !stmt->columns) {
/* for "big boy" drivers, we need to allocate memory to fetch
* the results into, so lets do that now */
ret = pdo_stmt_describe_columns(stmt TSRMLS_CC);
}
stmt->executed = 1;
}
if (ret && !dispatch_param_event(stmt, PDO_PARAM_EVT_EXEC_POST TSRMLS_CC)) {
RETURN_FALSE;
}
RETURN_BOOL(ret);
}
if (stmt->active_query_string && stmt->active_query_string != stmt->query_string) {
efree(stmt->active_query_string);
}
stmt->active_query_string = NULL;
PDO_HANDLE_STMT_ERR();
RETURN_FALSE;
}
/* }}} */
static inline void fetch_value(pdo_stmt_t *stmt, zval *dest, int colno, int *type_override TSRMLS_DC) /* {{{ */
{
struct pdo_column_data *col;
char *value = NULL;
unsigned long value_len = 0;
int caller_frees = 0;
int type, new_type;
col = &stmt->columns[colno];
type = PDO_PARAM_TYPE(col->param_type);
new_type = type_override ? PDO_PARAM_TYPE(*type_override) : type;
value = NULL;
value_len = 0;
stmt->methods->get_col(stmt, colno, &value, &value_len, &caller_frees TSRMLS_CC);
switch (type) {
case PDO_PARAM_ZVAL:
if (value && value_len == sizeof(zval)) {
int need_copy = (new_type != PDO_PARAM_ZVAL || stmt->dbh->stringify) ? 1 : 0;
zval *zv = *(zval**)value;
ZVAL_ZVAL(dest, zv, need_copy, 1);
} else {
ZVAL_NULL(dest);
}
if (Z_TYPE_P(dest) == IS_NULL) {
type = new_type;
}
break;
case PDO_PARAM_INT:
if (value && value_len == sizeof(long)) {
ZVAL_LONG(dest, *(long*)value);
break;
}
ZVAL_NULL(dest);
break;
case PDO_PARAM_BOOL:
if (value && value_len == sizeof(zend_bool)) {
ZVAL_BOOL(dest, *(zend_bool*)value);
break;
}
ZVAL_NULL(dest);
break;
case PDO_PARAM_LOB:
if (value == NULL) {
ZVAL_NULL(dest);
} else if (value_len == 0) {
/* Warning, empty strings need to be passed as stream */
if (stmt->dbh->stringify || new_type == PDO_PARAM_STR) {
char *buf = NULL;
size_t len;
len = php_stream_copy_to_mem((php_stream*)value, &buf, PHP_STREAM_COPY_ALL, 0);
if(buf == NULL) {
ZVAL_EMPTY_STRING(dest);
} else {
ZVAL_STRINGL(dest, buf, len, 0);
}
php_stream_close((php_stream*)value);
} else {
php_stream_to_zval((php_stream*)value, dest);
}
} else if (!stmt->dbh->stringify && new_type != PDO_PARAM_STR) {
/* they gave us a string, but LOBs are represented as streams in PDO */
php_stream *stm;
#ifdef TEMP_STREAM_TAKE_BUFFER
if (caller_frees) {
stm = php_stream_memory_open(TEMP_STREAM_TAKE_BUFFER, value, value_len);
if (stm) {
caller_frees = 0;
}
} else
#endif
{
stm = php_stream_memory_open(TEMP_STREAM_READONLY, value, value_len);
}
if (stm) {
php_stream_to_zval(stm, dest);
} else {
ZVAL_NULL(dest);
}
} else {
ZVAL_STRINGL(dest, value, value_len, !caller_frees);
if (caller_frees) {
caller_frees = 0;
}
}
break;
case PDO_PARAM_STR:
if (value && !(value_len == 0 && stmt->dbh->oracle_nulls == PDO_NULL_EMPTY_STRING)) {
ZVAL_STRINGL(dest, value, value_len, !caller_frees);
if (caller_frees) {
caller_frees = 0;
}
break;
}
default:
ZVAL_NULL(dest);
}
if (type != new_type) {
switch (new_type) {
case PDO_PARAM_INT:
convert_to_long_ex(&dest);
break;
case PDO_PARAM_BOOL:
convert_to_boolean_ex(&dest);
break;
case PDO_PARAM_STR:
convert_to_string_ex(&dest);
break;
case PDO_PARAM_NULL:
convert_to_null_ex(&dest);
break;
default:
;
}
}
if (caller_frees && value) {
efree(value);
}
if (stmt->dbh->stringify) {
switch (Z_TYPE_P(dest)) {
case IS_LONG:
case IS_DOUBLE:
convert_to_string(dest);
break;
}
}
if (Z_TYPE_P(dest) == IS_NULL && stmt->dbh->oracle_nulls == PDO_NULL_TO_STRING) {
ZVAL_EMPTY_STRING(dest);
}
}
/* }}} */
static int do_fetch_common(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori,
long offset, int do_bind TSRMLS_DC) /* {{{ */
{
if (!stmt->executed) {
return 0;
}
if (!dispatch_param_event(stmt, PDO_PARAM_EVT_FETCH_PRE TSRMLS_CC)) {
return 0;
}
if (!stmt->methods->fetcher(stmt, ori, offset TSRMLS_CC)) {
return 0;
}
/* some drivers might need to describe the columns now */
if (!stmt->columns && !pdo_stmt_describe_columns(stmt TSRMLS_CC)) {
return 0;
}
if (!dispatch_param_event(stmt, PDO_PARAM_EVT_FETCH_POST TSRMLS_CC)) {
return 0;
}
if (do_bind && stmt->bound_columns) {
/* update those bound column variables now */
struct pdo_bound_param_data *param;
zend_hash_internal_pointer_reset(stmt->bound_columns);
while (SUCCESS == zend_hash_get_current_data(stmt->bound_columns, (void**)¶m)) {
if (param->paramno >= 0) {
convert_to_string(param->parameter);
/* delete old value */
zval_dtor(param->parameter);
/* set new value */
fetch_value(stmt, param->parameter, param->paramno, (int *)¶m->param_type TSRMLS_CC);
/* TODO: some smart thing that avoids duplicating the value in the
* general loop below. For now, if you're binding output columns,
* it's better to use LAZY or BOUND fetches if you want to shave
* off those cycles */
}
zend_hash_move_forward(stmt->bound_columns);
}
}
return 1;
}
/* }}} */
static int do_fetch_class_prepare(pdo_stmt_t *stmt TSRMLS_DC) /* {{{ */
{
zend_class_entry * ce = stmt->fetch.cls.ce;
zend_fcall_info * fci = &stmt->fetch.cls.fci;
zend_fcall_info_cache * fcc = &stmt->fetch.cls.fcc;
fci->size = sizeof(zend_fcall_info);
if (!ce) {
stmt->fetch.cls.ce = ZEND_STANDARD_CLASS_DEF_PTR;
ce = ZEND_STANDARD_CLASS_DEF_PTR;
}
if (ce->constructor) {
fci->function_table = &ce->function_table;
fci->function_name = NULL;
fci->symbol_table = NULL;
fci->retval_ptr_ptr = &stmt->fetch.cls.retval_ptr;
fci->params = NULL;
fci->no_separation = 1;
zend_fcall_info_args(fci, stmt->fetch.cls.ctor_args TSRMLS_CC);
fcc->initialized = 1;
fcc->function_handler = ce->constructor;
fcc->calling_scope = EG(scope);
fcc->called_scope = ce;
return 1;
} else if (stmt->fetch.cls.ctor_args) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "user-supplied class does not have a constructor, use NULL for the ctor_params parameter, or simply omit it" TSRMLS_CC);
return 0;
} else {
return 1; /* no ctor no args is also ok */
}
}
/* }}} */
static int make_callable_ex(pdo_stmt_t *stmt, zval *callable, zend_fcall_info * fci, zend_fcall_info_cache * fcc, int num_args TSRMLS_DC) /* {{{ */
{
char *is_callable_error = NULL;
if (zend_fcall_info_init(callable, 0, fci, fcc, NULL, &is_callable_error TSRMLS_CC) == FAILURE) {
if (is_callable_error) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", is_callable_error TSRMLS_CC);
efree(is_callable_error);
} else {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "user-supplied function must be a valid callback" TSRMLS_CC);
}
return 0;
}
if (is_callable_error) {
/* Possible E_STRICT error message */
efree(is_callable_error);
}
fci->param_count = num_args; /* probably less */
fci->params = safe_emalloc(sizeof(zval**), num_args, 0);
return 1;
}
/* }}} */
static int do_fetch_func_prepare(pdo_stmt_t *stmt TSRMLS_DC) /* {{{ */
{
zend_fcall_info * fci = &stmt->fetch.cls.fci;
zend_fcall_info_cache * fcc = &stmt->fetch.cls.fcc;
if (!make_callable_ex(stmt, stmt->fetch.func.function, fci, fcc, stmt->column_count TSRMLS_CC)) {
return 0;
} else {
stmt->fetch.func.values = safe_emalloc(sizeof(zval*), stmt->column_count, 0);
return 1;
}
}
/* }}} */
static int do_fetch_opt_finish(pdo_stmt_t *stmt, int free_ctor_agrs TSRMLS_DC) /* {{{ */
{
/* fci.size is used to check if it is valid */
if (stmt->fetch.cls.fci.size && stmt->fetch.cls.fci.params) {
efree(stmt->fetch.cls.fci.params);
stmt->fetch.cls.fci.params = NULL;
}
stmt->fetch.cls.fci.size = 0;
if (stmt->fetch.cls.ctor_args && free_ctor_agrs) {
zval_ptr_dtor(&stmt->fetch.cls.ctor_args);
stmt->fetch.cls.ctor_args = NULL;
stmt->fetch.cls.fci.param_count = 0;
}
if (stmt->fetch.func.values) {
efree(stmt->fetch.func.values);
stmt->fetch.func.values = NULL;
}
return 1;
}
/* }}} */
/* perform a fetch. If do_bind is true, update any bound columns.
* If return_value is not null, store values into it according to HOW. */
static int do_fetch(pdo_stmt_t *stmt, int do_bind, zval *return_value,
enum pdo_fetch_type how, enum pdo_fetch_orientation ori, long offset, zval *return_all TSRMLS_DC) /* {{{ */
{
int flags, idx, old_arg_count = 0;
zend_class_entry *ce = NULL, *old_ce = NULL;
zval grp_val, *grp, **pgrp, *retval, *old_ctor_args = NULL;
int colno;
if (how == PDO_FETCH_USE_DEFAULT) {
how = stmt->default_fetch_type;
}
flags = how & PDO_FETCH_FLAGS;
how = how & ~PDO_FETCH_FLAGS;
if (!do_fetch_common(stmt, ori, offset, do_bind TSRMLS_CC)) {
return 0;
}
if (how == PDO_FETCH_BOUND) {
RETVAL_TRUE;
return 1;
}
if (flags & PDO_FETCH_GROUP && stmt->fetch.column == -1) {
colno = 1;
} else {
colno = stmt->fetch.column;
}
if (return_value) {
int i = 0;
if (how == PDO_FETCH_LAZY) {
get_lazy_object(stmt, return_value TSRMLS_CC);
return 1;
}
RETVAL_FALSE;
switch (how) {
case PDO_FETCH_USE_DEFAULT:
case PDO_FETCH_ASSOC:
case PDO_FETCH_BOTH:
case PDO_FETCH_NUM:
case PDO_FETCH_NAMED:
if (!return_all) {
ALLOC_HASHTABLE(return_value->value.ht);
zend_hash_init(return_value->value.ht, stmt->column_count, NULL, ZVAL_PTR_DTOR, 0);
Z_TYPE_P(return_value) = IS_ARRAY;
} else {
array_init(return_value);
}
break;
case PDO_FETCH_KEY_PAIR:
if (stmt->column_count != 2) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "PDO::FETCH_KEY_PAIR fetch mode requires the result set to contain extactly 2 columns." TSRMLS_CC);
return 0;
}
if (!return_all) {
array_init(return_value);
}
break;
case PDO_FETCH_COLUMN:
if (colno >= 0 && colno < stmt->column_count) {
if (flags == PDO_FETCH_GROUP && stmt->fetch.column == -1) {
fetch_value(stmt, return_value, 1, NULL TSRMLS_CC);
} else if (flags == PDO_FETCH_GROUP && colno) {
fetch_value(stmt, return_value, 0, NULL TSRMLS_CC);
} else {
fetch_value(stmt, return_value, colno, NULL TSRMLS_CC);
}
if (!return_all) {
return 1;
} else {
break;
}
} else {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "Invalid column index" TSRMLS_CC);
}
return 0;
case PDO_FETCH_OBJ:
object_init_ex(return_value, ZEND_STANDARD_CLASS_DEF_PTR);
break;
case PDO_FETCH_CLASS:
if (flags & PDO_FETCH_CLASSTYPE) {
zval val;
zend_class_entry **cep;
old_ce = stmt->fetch.cls.ce;
old_ctor_args = stmt->fetch.cls.ctor_args;
old_arg_count = stmt->fetch.cls.fci.param_count;
do_fetch_opt_finish(stmt, 0 TSRMLS_CC);
INIT_PZVAL(&val);
fetch_value(stmt, &val, i++, NULL TSRMLS_CC);
if (Z_TYPE(val) != IS_NULL) {
convert_to_string(&val);
if (zend_lookup_class(Z_STRVAL(val), Z_STRLEN(val), &cep TSRMLS_CC) == FAILURE) {
stmt->fetch.cls.ce = ZEND_STANDARD_CLASS_DEF_PTR;
} else {
stmt->fetch.cls.ce = *cep;
}
}
do_fetch_class_prepare(stmt TSRMLS_CC);
zval_dtor(&val);
}
ce = stmt->fetch.cls.ce;
if (!ce) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "No fetch class specified" TSRMLS_CC);
return 0;
}
if ((flags & PDO_FETCH_SERIALIZE) == 0) {
object_init_ex(return_value, ce);
if (!stmt->fetch.cls.fci.size) {
if (!do_fetch_class_prepare(stmt TSRMLS_CC))
{
return 0;
}
}
if (ce->constructor && (flags & PDO_FETCH_PROPS_LATE)) {
stmt->fetch.cls.fci.object_ptr = return_value;
stmt->fetch.cls.fcc.object_ptr = return_value;
if (zend_call_function(&stmt->fetch.cls.fci, &stmt->fetch.cls.fcc TSRMLS_CC) == FAILURE) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "could not call class constructor" TSRMLS_CC);
return 0;
} else {
if (stmt->fetch.cls.retval_ptr) {
zval_ptr_dtor(&stmt->fetch.cls.retval_ptr);
}
}
}
}
break;
case PDO_FETCH_INTO:
if (!stmt->fetch.into) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "No fetch-into object specified." TSRMLS_CC);
return 0;
break;
}
Z_TYPE_P(return_value) = IS_OBJECT;
Z_OBJ_HANDLE_P(return_value) = Z_OBJ_HANDLE_P(stmt->fetch.into);
Z_OBJ_HT_P(return_value) = Z_OBJ_HT_P(stmt->fetch.into);
zend_objects_store_add_ref(stmt->fetch.into TSRMLS_CC);
if (zend_get_class_entry(return_value TSRMLS_CC) == ZEND_STANDARD_CLASS_DEF_PTR) {
how = PDO_FETCH_OBJ;
}
break;
case PDO_FETCH_FUNC:
if (!stmt->fetch.func.function) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "No fetch function specified" TSRMLS_CC);
return 0;
}
if (!stmt->fetch.func.fci.size) {
if (!do_fetch_func_prepare(stmt TSRMLS_CC))
{
return 0;
}
}
break;
default:
/* shouldn't happen */
return 0;
}
if (return_all && how != PDO_FETCH_KEY_PAIR) {
INIT_PZVAL(&grp_val);
if (flags == PDO_FETCH_GROUP && how == PDO_FETCH_COLUMN && stmt->fetch.column > 0) {
fetch_value(stmt, &grp_val, colno, NULL TSRMLS_CC);
} else {
fetch_value(stmt, &grp_val, i, NULL TSRMLS_CC);
}
convert_to_string(&grp_val);
if (how == PDO_FETCH_COLUMN) {
i = stmt->column_count; /* no more data to fetch */
} else {
i++;
}
}
for (idx = 0; i < stmt->column_count; i++, idx++) {
zval *val;
MAKE_STD_ZVAL(val);
fetch_value(stmt, val, i, NULL TSRMLS_CC);
switch (how) {
case PDO_FETCH_ASSOC:
add_assoc_zval(return_value, stmt->columns[i].name, val);
break;
case PDO_FETCH_KEY_PAIR:
{
zval *tmp;
MAKE_STD_ZVAL(tmp);
fetch_value(stmt, tmp, ++i, NULL TSRMLS_CC);
if (Z_TYPE_P(val) == IS_LONG) {
zend_hash_index_update((return_all ? Z_ARRVAL_P(return_all) : Z_ARRVAL_P(return_value)), Z_LVAL_P(val), &tmp, sizeof(zval *), NULL);
} else {
convert_to_string(val);
zend_symtable_update((return_all ? Z_ARRVAL_P(return_all) : Z_ARRVAL_P(return_value)), Z_STRVAL_P(val), Z_STRLEN_P(val) + 1, &tmp, sizeof(zval *), NULL);
}
zval_ptr_dtor(&val);
return 1;
}
break;
case PDO_FETCH_USE_DEFAULT:
case PDO_FETCH_BOTH:
add_assoc_zval(return_value, stmt->columns[i].name, val);
Z_ADDREF_P(val);
add_next_index_zval(return_value, val);
break;
case PDO_FETCH_NAMED:
/* already have an item with this name? */
{
zval **curr_val = NULL;
if (zend_hash_find(Z_ARRVAL_P(return_value), stmt->columns[i].name,
strlen(stmt->columns[i].name)+1,
(void**)&curr_val) == SUCCESS) {
zval *arr;
if (Z_TYPE_PP(curr_val) != IS_ARRAY) {
/* a little bit of black magic here:
* we're creating a new array and swapping it for the
* zval that's already stored in the hash under the name
* we want. We then add that zval to the array.
* This is effectively the same thing as:
* if (!is_array($hash[$name])) {
* $hash[$name] = array($hash[$name]);
* }
* */
zval *cur;
MAKE_STD_ZVAL(arr);
array_init(arr);
cur = *curr_val;
*curr_val = arr;
add_next_index_zval(arr, cur);
} else {
arr = *curr_val;
}
add_next_index_zval(arr, val);
} else {
add_assoc_zval(return_value, stmt->columns[i].name, val);
}
}
break;
case PDO_FETCH_NUM:
add_next_index_zval(return_value, val);
break;
case PDO_FETCH_OBJ:
case PDO_FETCH_INTO:
zend_update_property(NULL, return_value,
stmt->columns[i].name, stmt->columns[i].namelen,
val TSRMLS_CC);
zval_ptr_dtor(&val);
break;
case PDO_FETCH_CLASS:
if ((flags & PDO_FETCH_SERIALIZE) == 0 || idx) {
zend_update_property(ce, return_value,
stmt->columns[i].name, stmt->columns[i].namelen,
val TSRMLS_CC);
zval_ptr_dtor(&val);
} else {
#ifdef MBO_0
php_unserialize_data_t var_hash;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (php_var_unserialize(&return_value, (const unsigned char**)&Z_STRVAL_P(val), Z_STRVAL_P(val)+Z_STRLEN_P(val), NULL TSRMLS_CC) == FAILURE) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "cannot unserialize data" TSRMLS_CC);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return 0;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#endif
if (!ce->unserialize) {
zval_ptr_dtor(&val);
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "cannot unserialize class" TSRMLS_CC);
return 0;
} else if (ce->unserialize(&return_value, ce, (unsigned char *)(Z_TYPE_P(val) == IS_STRING ? Z_STRVAL_P(val) : ""), Z_TYPE_P(val) == IS_STRING ? Z_STRLEN_P(val) : 0, NULL TSRMLS_CC) == FAILURE) {
zval_ptr_dtor(&val);
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "cannot unserialize class" TSRMLS_CC);
zval_dtor(return_value);
ZVAL_NULL(return_value);
return 0;
} else {
zval_ptr_dtor(&val);
}
}
break;
case PDO_FETCH_FUNC:
stmt->fetch.func.values[idx] = val;
stmt->fetch.cls.fci.params[idx] = &stmt->fetch.func.values[idx];
break;
default:
zval_ptr_dtor(&val);
pdo_raise_impl_error(stmt->dbh, stmt, "22003", "mode is out of range" TSRMLS_CC);
return 0;
break;
}
}
switch (how) {
case PDO_FETCH_CLASS:
if (ce->constructor && !(flags & (PDO_FETCH_PROPS_LATE | PDO_FETCH_SERIALIZE))) {
stmt->fetch.cls.fci.object_ptr = return_value;
stmt->fetch.cls.fcc.object_ptr = return_value;
if (zend_call_function(&stmt->fetch.cls.fci, &stmt->fetch.cls.fcc TSRMLS_CC) == FAILURE) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "could not call class constructor" TSRMLS_CC);
return 0;
} else {
if (stmt->fetch.cls.retval_ptr) {
zval_ptr_dtor(&stmt->fetch.cls.retval_ptr);
}
}
}
if (flags & PDO_FETCH_CLASSTYPE) {
do_fetch_opt_finish(stmt, 0 TSRMLS_CC);
stmt->fetch.cls.ce = old_ce;
stmt->fetch.cls.ctor_args = old_ctor_args;
stmt->fetch.cls.fci.param_count = old_arg_count;
}
break;
case PDO_FETCH_FUNC:
stmt->fetch.func.fci.param_count = idx;
stmt->fetch.func.fci.retval_ptr_ptr = &retval;
if (zend_call_function(&stmt->fetch.func.fci, &stmt->fetch.func.fcc TSRMLS_CC) == FAILURE) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "could not call user-supplied function" TSRMLS_CC);
return 0;
} else {
if (return_all) {
zval_ptr_dtor(&return_value); /* we don't need that */
return_value = retval;
} else if (retval) {
MAKE_COPY_ZVAL(&retval, return_value);
zval_ptr_dtor(&retval);
}
}
while(idx--) {
zval_ptr_dtor(&stmt->fetch.func.values[idx]);
}
break;
default:
break;
}
if (return_all) {
if ((flags & PDO_FETCH_UNIQUE) == PDO_FETCH_UNIQUE) {
add_assoc_zval(return_all, Z_STRVAL(grp_val), return_value);
} else {
if (zend_symtable_find(Z_ARRVAL_P(return_all), Z_STRVAL(grp_val), Z_STRLEN(grp_val)+1, (void**)&pgrp) == FAILURE) {
MAKE_STD_ZVAL(grp);
array_init(grp);
add_assoc_zval(return_all, Z_STRVAL(grp_val), grp);
} else {
grp = *pgrp;
}
add_next_index_zval(grp, return_value);
}
zval_dtor(&grp_val);
}
}
return 1;
}
/* }}} */
static int pdo_stmt_verify_mode(pdo_stmt_t *stmt, long mode, int fetch_all TSRMLS_DC) /* {{{ */
{
int flags = mode & PDO_FETCH_FLAGS;
mode = mode & ~PDO_FETCH_FLAGS;
if (mode < 0 || mode > PDO_FETCH__MAX) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "invalid fetch mode" TSRMLS_CC);
return 0;
}
if (mode == PDO_FETCH_USE_DEFAULT) {
flags = stmt->default_fetch_type & PDO_FETCH_FLAGS;
mode = stmt->default_fetch_type & ~PDO_FETCH_FLAGS;
}
switch(mode) {
case PDO_FETCH_FUNC:
if (!fetch_all) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "PDO::FETCH_FUNC is only allowed in PDOStatement::fetchAll()" TSRMLS_CC);
return 0;
}
return 1;
case PDO_FETCH_LAZY:
if (fetch_all) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "PDO::FETCH_LAZY can't be used with PDOStatement::fetchAll()" TSRMLS_CC);
return 0;
}
/* fall through */
default:
if ((flags & PDO_FETCH_SERIALIZE) == PDO_FETCH_SERIALIZE) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "PDO::FETCH_SERIALIZE can only be used together with PDO::FETCH_CLASS" TSRMLS_CC);
return 0;
}
if ((flags & PDO_FETCH_CLASSTYPE) == PDO_FETCH_CLASSTYPE) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "PDO::FETCH_CLASSTYPE can only be used together with PDO::FETCH_CLASS" TSRMLS_CC);
return 0;
}
if (mode >= PDO_FETCH__MAX) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "invalid fetch mode" TSRMLS_CC);
return 0;
}
/* no break; */
case PDO_FETCH_CLASS:
return 1;
}
}
/* }}} */
/* {{{ proto mixed PDOStatement::fetch([int $how = PDO_FETCH_BOTH [, int $orientation [, int $offset]]])
Fetches the next row and returns it, or false if there are no more rows */
static PHP_METHOD(PDOStatement, fetch)
{
long how = PDO_FETCH_USE_DEFAULT;
long ori = PDO_FETCH_ORI_NEXT;
long off = 0;
PHP_STMT_GET_OBJ;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lll", &how,
&ori, &off)) {
RETURN_FALSE;
}
PDO_STMT_CLEAR_ERR();
if (!pdo_stmt_verify_mode(stmt, how, 0 TSRMLS_CC)) {
RETURN_FALSE;
}
if (!do_fetch(stmt, TRUE, return_value, how, ori, off, 0 TSRMLS_CC)) {
PDO_HANDLE_STMT_ERR();
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto mixed PDOStatement::fetchObject([string class_name [, NULL|array ctor_args]])
Fetches the next row and returns it as an object. */
static PHP_METHOD(PDOStatement, fetchObject)
{
long how = PDO_FETCH_CLASS;
long ori = PDO_FETCH_ORI_NEXT;
long off = 0;
char *class_name = NULL;
int class_name_len;
zend_class_entry *old_ce;
zval *old_ctor_args, *ctor_args = NULL;
int error = 0, old_arg_count;
PHP_STMT_GET_OBJ;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!a", &class_name, &class_name_len, &ctor_args)) {
RETURN_FALSE;
}
PDO_STMT_CLEAR_ERR();
if (!pdo_stmt_verify_mode(stmt, how, 0 TSRMLS_CC)) {
RETURN_FALSE;
}
old_ce = stmt->fetch.cls.ce;
old_ctor_args = stmt->fetch.cls.ctor_args;
old_arg_count = stmt->fetch.cls.fci.param_count;
do_fetch_opt_finish(stmt, 0 TSRMLS_CC);
if (ctor_args) {
if (Z_TYPE_P(ctor_args) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_P(ctor_args))) {
ALLOC_ZVAL(stmt->fetch.cls.ctor_args);
*stmt->fetch.cls.ctor_args = *ctor_args;
zval_copy_ctor(stmt->fetch.cls.ctor_args);
} else {
stmt->fetch.cls.ctor_args = NULL;
}
}
if (class_name && !error) {
stmt->fetch.cls.ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
if (!stmt->fetch.cls.ce) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "Could not find user-supplied class" TSRMLS_CC);
error = 1;
}
} else if (!error) {
stmt->fetch.cls.ce = zend_standard_class_def;
}
if (!error && !do_fetch(stmt, TRUE, return_value, how, ori, off, 0 TSRMLS_CC)) {
error = 1;
}
if (error) {
PDO_HANDLE_STMT_ERR();
}
do_fetch_opt_finish(stmt, 1 TSRMLS_CC);
stmt->fetch.cls.ce = old_ce;
stmt->fetch.cls.ctor_args = old_ctor_args;
stmt->fetch.cls.fci.param_count = old_arg_count;
if (error) {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string PDOStatement::fetchColumn([int column_number])
Returns a data of the specified column in the result set. */
static PHP_METHOD(PDOStatement, fetchColumn)
{
long col_n = 0;
PHP_STMT_GET_OBJ;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &col_n)) {
RETURN_FALSE;
}
PDO_STMT_CLEAR_ERR();
if (!do_fetch_common(stmt, PDO_FETCH_ORI_NEXT, 0, TRUE TSRMLS_CC)) {
PDO_HANDLE_STMT_ERR();
RETURN_FALSE;
}
fetch_value(stmt, return_value, col_n, NULL TSRMLS_CC);
}
/* }}} */
/* {{{ proto array PDOStatement::fetchAll([int $how = PDO_FETCH_BOTH [, string class_name [, NULL|array ctor_args]]])
Returns an array of all of the results. */
static PHP_METHOD(PDOStatement, fetchAll)
{
long how = PDO_FETCH_USE_DEFAULT;
zval *data, *return_all;
zval *arg2;
zend_class_entry *old_ce;
zval *old_ctor_args, *ctor_args = NULL;
int error = 0, flags, old_arg_count;
PHP_STMT_GET_OBJ;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lzz", &how, &arg2, &ctor_args)) {
RETURN_FALSE;
}
if (!pdo_stmt_verify_mode(stmt, how, 1 TSRMLS_CC)) {
RETURN_FALSE;
}
old_ce = stmt->fetch.cls.ce;
old_ctor_args = stmt->fetch.cls.ctor_args;
old_arg_count = stmt->fetch.cls.fci.param_count;
do_fetch_opt_finish(stmt, 0 TSRMLS_CC);
switch(how & ~PDO_FETCH_FLAGS) {
case PDO_FETCH_CLASS:
switch(ZEND_NUM_ARGS()) {
case 0:
case 1:
stmt->fetch.cls.ce = zend_standard_class_def;
break;
case 3:
if (Z_TYPE_P(ctor_args) != IS_NULL && Z_TYPE_P(ctor_args) != IS_ARRAY) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "ctor_args must be either NULL or an array" TSRMLS_CC);
error = 1;
break;
}
if (Z_TYPE_P(ctor_args) != IS_ARRAY || !zend_hash_num_elements(Z_ARRVAL_P(ctor_args))) {
ctor_args = NULL;
}
/* no break */
case 2:
stmt->fetch.cls.ctor_args = ctor_args; /* we're not going to free these */
if (Z_TYPE_P(arg2) != IS_STRING) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "Invalid class name (should be a string)" TSRMLS_CC);
error = 1;
break;
} else {
stmt->fetch.cls.ce = zend_fetch_class(Z_STRVAL_P(arg2), Z_STRLEN_P(arg2), ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
if (!stmt->fetch.cls.ce) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "could not find user-specified class" TSRMLS_CC);
error = 1;
break;
}
}
}
if (!error) {
do_fetch_class_prepare(stmt TSRMLS_CC);
}
break;
case PDO_FETCH_FUNC:
switch(ZEND_NUM_ARGS()) {
case 0:
case 1:
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "no fetch function specified" TSRMLS_CC);
error = 1;
break;
case 3:
case 2:
stmt->fetch.func.function = arg2;
if (do_fetch_func_prepare(stmt TSRMLS_CC) == 0) {
error = 1;
}
break;
}
break;
case PDO_FETCH_COLUMN:
switch(ZEND_NUM_ARGS()) {
case 0:
case 1:
stmt->fetch.column = how & PDO_FETCH_GROUP ? -1 : 0;
break;
case 2:
convert_to_long(arg2);
stmt->fetch.column = Z_LVAL_P(arg2);
break;
case 3:
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "Third parameter not allowed for PDO::FETCH_COLUMN" TSRMLS_CC);
error = 1;
}
break;
default:
if (ZEND_NUM_ARGS() > 1) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "Extraneous additional parameters" TSRMLS_CC);
error = 1;
}
}
flags = how & PDO_FETCH_FLAGS;
if ((how & ~PDO_FETCH_FLAGS) == PDO_FETCH_USE_DEFAULT) {
flags |= stmt->default_fetch_type & PDO_FETCH_FLAGS;
how |= stmt->default_fetch_type & ~PDO_FETCH_FLAGS;
}
if (!error) {
PDO_STMT_CLEAR_ERR();
MAKE_STD_ZVAL(data);
if ( (how & PDO_FETCH_GROUP) || how == PDO_FETCH_KEY_PAIR ||
(how == PDO_FETCH_USE_DEFAULT && stmt->default_fetch_type == PDO_FETCH_KEY_PAIR)
) {
array_init(return_value);
return_all = return_value;
} else {
return_all = 0;
}
if (!do_fetch(stmt, TRUE, data, how | flags, PDO_FETCH_ORI_NEXT, 0, return_all TSRMLS_CC)) {
FREE_ZVAL(data);
error = 2;
}
}
if (!error) {
if ((how & PDO_FETCH_GROUP)) {
do {
MAKE_STD_ZVAL(data);
} while (do_fetch(stmt, TRUE, data, how | flags, PDO_FETCH_ORI_NEXT, 0, return_all TSRMLS_CC));
} else if (how == PDO_FETCH_KEY_PAIR || (how == PDO_FETCH_USE_DEFAULT && stmt->default_fetch_type == PDO_FETCH_KEY_PAIR)) {
while (do_fetch(stmt, TRUE, data, how | flags, PDO_FETCH_ORI_NEXT, 0, return_all TSRMLS_CC));
} else {
array_init(return_value);
do {
add_next_index_zval(return_value, data);
MAKE_STD_ZVAL(data);
} while (do_fetch(stmt, TRUE, data, how | flags, PDO_FETCH_ORI_NEXT, 0, 0 TSRMLS_CC));
}
FREE_ZVAL(data);
}
do_fetch_opt_finish(stmt, 0 TSRMLS_CC);
stmt->fetch.cls.ce = old_ce;
stmt->fetch.cls.ctor_args = old_ctor_args;
stmt->fetch.cls.fci.param_count = old_arg_count;
if (error) {
PDO_HANDLE_STMT_ERR();
if (error != 2) {
RETURN_FALSE;
} else { /* on no results, return an empty array */
if (Z_TYPE_P(return_value) != IS_ARRAY) {
array_init(return_value);
}
return;
}
}
}
/* }}} */
static int register_bound_param(INTERNAL_FUNCTION_PARAMETERS, pdo_stmt_t *stmt, int is_param) /* {{{ */
{
struct pdo_bound_param_data param = {0};
long param_type = PDO_PARAM_STR;
param.paramno = -1;
if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC,
"lz|llz!", ¶m.paramno, ¶m.parameter, ¶m_type, ¶m.max_value_len,
¶m.driver_params)) {
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|llz!", ¶m.name,
¶m.namelen, ¶m.parameter, ¶m_type, ¶m.max_value_len,
¶m.driver_params)) {
return 0;
}
}
param.param_type = (int) param_type;
if (param.paramno > 0) {
--param.paramno; /* make it zero-based internally */
} else if (!param.name) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "Columns/Parameters are 1-based" TSRMLS_CC);
return 0;
}
Z_ADDREF_P(param.parameter);
if (!really_register_bound_param(¶m, stmt, is_param TSRMLS_CC)) {
if (param.parameter) {
zval_ptr_dtor(&(param.parameter));
param.parameter = NULL;
}
return 0;
}
return 1;
} /* }}} */
/* {{{ proto bool PDOStatement::bindValue(mixed $paramno, mixed $param [, int $type ])
bind an input parameter to the value of a PHP variable. $paramno is the 1-based position of the placeholder in the SQL statement (but can be the parameter name for drivers that support named placeholders). It should be called prior to execute(). */
static PHP_METHOD(PDOStatement, bindValue)
{
struct pdo_bound_param_data param = {0};
long param_type = PDO_PARAM_STR;
PHP_STMT_GET_OBJ;
param.paramno = -1;
if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC,
"lz/|l", ¶m.paramno, ¶m.parameter, ¶m_type)) {
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz/|l", ¶m.name,
¶m.namelen, ¶m.parameter, ¶m_type)) {
RETURN_FALSE;
}
}
param.param_type = (int) param_type;
if (param.paramno > 0) {
--param.paramno; /* make it zero-based internally */
} else if (!param.name) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "Columns/Parameters are 1-based" TSRMLS_CC);
RETURN_FALSE;
}
Z_ADDREF_P(param.parameter);
if (!really_register_bound_param(¶m, stmt, TRUE TSRMLS_CC)) {
if (param.parameter) {
zval_ptr_dtor(&(param.parameter));
param.parameter = NULL;
}
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool PDOStatement::bindParam(mixed $paramno, mixed &$param [, int $type [, int $maxlen [, mixed $driverdata]]])
bind a parameter to a PHP variable. $paramno is the 1-based position of the placeholder in the SQL statement (but can be the parameter name for drivers that support named placeholders). This isn't supported by all drivers. It should be called prior to execute(). */
static PHP_METHOD(PDOStatement, bindParam)
{
PHP_STMT_GET_OBJ;
RETURN_BOOL(register_bound_param(INTERNAL_FUNCTION_PARAM_PASSTHRU, stmt, TRUE));
}
/* }}} */
/* {{{ proto bool PDOStatement::bindColumn(mixed $column, mixed &$param [, int $type [, int $maxlen [, mixed $driverdata]]])
bind a column to a PHP variable. On each row fetch $param will contain the value of the corresponding column. $column is the 1-based offset of the column, or the column name. For portability, don't call this before execute(). */
static PHP_METHOD(PDOStatement, bindColumn)
{
PHP_STMT_GET_OBJ;
RETURN_BOOL(register_bound_param(INTERNAL_FUNCTION_PARAM_PASSTHRU, stmt, FALSE));
}
/* }}} */
/* {{{ proto int PDOStatement::rowCount()
Returns the number of rows in a result set, or the number of rows affected by the last execute(). It is not always meaningful. */
static PHP_METHOD(PDOStatement, rowCount)
{
PHP_STMT_GET_OBJ;
RETURN_LONG(stmt->row_count);
}
/* }}} */
/* {{{ proto string PDOStatement::errorCode()
Fetch the error code associated with the last operation on the statement handle */
static PHP_METHOD(PDOStatement, errorCode)
{
PHP_STMT_GET_OBJ;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (stmt->error_code[0] == '\0') {
RETURN_NULL();
}
RETURN_STRING(stmt->error_code, 1);
}
/* }}} */
/* {{{ proto array PDOStatement::errorInfo()
Fetch extended error information associated with the last operation on the statement handle */
static PHP_METHOD(PDOStatement, errorInfo)
{
int error_count;
int error_count_diff = 0;
int error_expected_count = 3;
PHP_STMT_GET_OBJ;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_string(return_value, stmt->error_code, 1);
if (stmt->dbh->methods->fetch_err) {
stmt->dbh->methods->fetch_err(stmt->dbh, stmt, return_value TSRMLS_CC);
}
error_count = zend_hash_num_elements(Z_ARRVAL_P(return_value));
if (error_expected_count > error_count) {
int current_index;
error_count_diff = error_expected_count - error_count;
for (current_index = 0; current_index < error_count_diff; current_index++) {
add_next_index_null(return_value);
}
}
}
/* }}} */
/* {{{ proto bool PDOStatement::setAttribute(long attribute, mixed value)
Set an attribute */
static PHP_METHOD(PDOStatement, setAttribute)
{
long attr;
zval *value = NULL;
PHP_STMT_GET_OBJ;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lz!", &attr, &value)) {
RETURN_FALSE;
}
if (!stmt->methods->set_attribute) {
goto fail;
}
PDO_STMT_CLEAR_ERR();
if (stmt->methods->set_attribute(stmt, attr, value TSRMLS_CC)) {
RETURN_TRUE;
}
fail:
if (!stmt->methods->set_attribute) {
pdo_raise_impl_error(stmt->dbh, stmt, "IM001", "This driver doesn't support setting attributes" TSRMLS_CC);
} else {
PDO_HANDLE_STMT_ERR();
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto mixed PDOStatement::getAttribute(long attribute)
Get an attribute */
static int generic_stmt_attr_get(pdo_stmt_t *stmt, zval *return_value, long attr)
{
switch (attr) {
case PDO_ATTR_EMULATE_PREPARES:
RETVAL_BOOL(stmt->supports_placeholders == PDO_PLACEHOLDER_NONE);
return 1;
}
return 0;
}
static PHP_METHOD(PDOStatement, getAttribute)
{
long attr;
PHP_STMT_GET_OBJ;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &attr)) {
RETURN_FALSE;
}
if (!stmt->methods->get_attribute) {
if (!generic_stmt_attr_get(stmt, return_value, attr)) {
pdo_raise_impl_error(stmt->dbh, stmt, "IM001",
"This driver doesn't support getting attributes" TSRMLS_CC);
RETURN_FALSE;
}
return;
}
PDO_STMT_CLEAR_ERR();
switch (stmt->methods->get_attribute(stmt, attr, return_value TSRMLS_CC)) {
case -1:
PDO_HANDLE_STMT_ERR();
RETURN_FALSE;
case 0:
if (!generic_stmt_attr_get(stmt, return_value, attr)) {
/* XXX: should do something better here */
pdo_raise_impl_error(stmt->dbh, stmt, "IM001",
"driver doesn't support getting that attribute" TSRMLS_CC);
RETURN_FALSE;
}
return;
default:
return;
}
}
/* }}} */
/* {{{ proto int PDOStatement::columnCount()
Returns the number of columns in the result set */
static PHP_METHOD(PDOStatement, columnCount)
{
PHP_STMT_GET_OBJ;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(stmt->column_count);
}
/* }}} */
/* {{{ proto array PDOStatement::getColumnMeta(int $column)
Returns meta data for a numbered column */
static PHP_METHOD(PDOStatement, getColumnMeta)
{
long colno;
struct pdo_column_data *col;
PHP_STMT_GET_OBJ;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &colno)) {
RETURN_FALSE;
}
if(colno < 0) {
pdo_raise_impl_error(stmt->dbh, stmt, "42P10", "column number must be non-negative" TSRMLS_CC);
RETURN_FALSE;
}
if (!stmt->methods->get_column_meta) {
pdo_raise_impl_error(stmt->dbh, stmt, "IM001", "driver doesn't support meta data" TSRMLS_CC);
RETURN_FALSE;
}
PDO_STMT_CLEAR_ERR();
if (FAILURE == stmt->methods->get_column_meta(stmt, colno, return_value TSRMLS_CC)) {
PDO_HANDLE_STMT_ERR();
RETURN_FALSE;
}
/* add stock items */
col = &stmt->columns[colno];
add_assoc_string(return_value, "name", col->name, 1);
add_assoc_long(return_value, "len", col->maxlen); /* FIXME: unsigned ? */
add_assoc_long(return_value, "precision", col->precision);
if (col->param_type != PDO_PARAM_ZVAL) {
/* if param_type is PDO_PARAM_ZVAL the driver has to provide correct data */
add_assoc_long(return_value, "pdo_type", col->param_type);
}
}
/* }}} */
/* {{{ proto bool PDOStatement::setFetchMode(int mode [mixed* params])
Changes the default fetch mode for subsequent fetches (params have different meaning for different fetch modes) */
int pdo_stmt_setup_fetch_mode(INTERNAL_FUNCTION_PARAMETERS, pdo_stmt_t *stmt, int skip)
{
long mode = PDO_FETCH_BOTH;
int flags = 0, argc = ZEND_NUM_ARGS() - skip;
zval ***args;
zend_class_entry **cep;
int retval;
do_fetch_opt_finish(stmt, 1 TSRMLS_CC);
switch (stmt->default_fetch_type) {
case PDO_FETCH_INTO:
if (stmt->fetch.into) {
zval_ptr_dtor(&stmt->fetch.into);
stmt->fetch.into = NULL;
}
break;
default:
;
}
stmt->default_fetch_type = PDO_FETCH_BOTH;
if (argc == 0) {
return SUCCESS;
}
args = safe_emalloc(ZEND_NUM_ARGS(), sizeof(zval*), 0);
retval = zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args);
if (SUCCESS == retval) {
if (Z_TYPE_PP(args[skip]) != IS_LONG) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "mode must be an integer" TSRMLS_CC);
retval = FAILURE;
} else {
mode = Z_LVAL_PP(args[skip]);
flags = mode & PDO_FETCH_FLAGS;
retval = pdo_stmt_verify_mode(stmt, mode, 0 TSRMLS_CC);
}
}
if (FAILURE == retval) {
PDO_STMT_CLEAR_ERR();
efree(args);
return FAILURE;
}
retval = FAILURE;
switch (mode & ~PDO_FETCH_FLAGS) {
case PDO_FETCH_USE_DEFAULT:
case PDO_FETCH_LAZY:
case PDO_FETCH_ASSOC:
case PDO_FETCH_NUM:
case PDO_FETCH_BOTH:
case PDO_FETCH_OBJ:
case PDO_FETCH_BOUND:
case PDO_FETCH_NAMED:
case PDO_FETCH_KEY_PAIR:
if (argc != 1) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode doesn't allow any extra arguments" TSRMLS_CC);
} else {
retval = SUCCESS;
}
break;
case PDO_FETCH_COLUMN:
if (argc != 2) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode requires the colno argument" TSRMLS_CC);
} else if (Z_TYPE_PP(args[skip+1]) != IS_LONG) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "colno must be an integer" TSRMLS_CC);
} else {
stmt->fetch.column = Z_LVAL_PP(args[skip+1]);
retval = SUCCESS;
}
break;
case PDO_FETCH_CLASS:
/* Gets its class name from 1st column */
if ((flags & PDO_FETCH_CLASSTYPE) == PDO_FETCH_CLASSTYPE) {
if (argc != 1) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode doesn't allow any extra arguments" TSRMLS_CC);
} else {
stmt->fetch.cls.ce = NULL;
retval = SUCCESS;
}
} else {
if (argc < 2) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode requires the classname argument" TSRMLS_CC);
} else if (argc > 3) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "too many arguments" TSRMLS_CC);
} else if (Z_TYPE_PP(args[skip+1]) != IS_STRING) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "classname must be a string" TSRMLS_CC);
} else {
retval = zend_lookup_class(Z_STRVAL_PP(args[skip+1]),
Z_STRLEN_PP(args[skip+1]), &cep TSRMLS_CC);
if (SUCCESS == retval && cep && *cep) {
stmt->fetch.cls.ce = *cep;
}
}
}
if (SUCCESS == retval) {
stmt->fetch.cls.ctor_args = NULL;
#ifdef ilia_0 /* we'll only need this when we have persistent statements, if ever */
if (stmt->dbh->is_persistent) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "PHP might crash if you don't call $stmt->setFetchMode() to reset to defaults on this persistent statement. This will be fixed in a later release");
}
#endif
if (argc == 3) {
if (Z_TYPE_PP(args[skip+2]) != IS_NULL && Z_TYPE_PP(args[skip+2]) != IS_ARRAY) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "ctor_args must be either NULL or an array" TSRMLS_CC);
retval = FAILURE;
} else if (Z_TYPE_PP(args[skip+2]) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_PP(args[skip+2]))) {
ALLOC_ZVAL(stmt->fetch.cls.ctor_args);
*stmt->fetch.cls.ctor_args = **args[skip+2];
zval_copy_ctor(stmt->fetch.cls.ctor_args);
}
}
if (SUCCESS == retval) {
do_fetch_class_prepare(stmt TSRMLS_CC);
}
}
break;
case PDO_FETCH_INTO:
if (argc != 2) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode requires the object parameter" TSRMLS_CC);
} else if (Z_TYPE_PP(args[skip+1]) != IS_OBJECT) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "object must be an object" TSRMLS_CC);
} else {
retval = SUCCESS;
}
if (SUCCESS == retval) {
#ifdef ilia_0 /* we'll only need this when we have persistent statements, if ever */
if (stmt->dbh->is_persistent) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "PHP might crash if you don't call $stmt->setFetchMode() to reset to defaults on this persistent statement. This will be fixed in a later release");
}
#endif
MAKE_STD_ZVAL(stmt->fetch.into);
Z_TYPE_P(stmt->fetch.into) = IS_OBJECT;
Z_OBJ_HANDLE_P(stmt->fetch.into) = Z_OBJ_HANDLE_PP(args[skip+1]);
Z_OBJ_HT_P(stmt->fetch.into) = Z_OBJ_HT_PP(args[skip+1]);
zend_objects_store_add_ref(stmt->fetch.into TSRMLS_CC);
}
break;
default:
pdo_raise_impl_error(stmt->dbh, stmt, "22003", "Invalid fetch mode specified" TSRMLS_CC);
}
if (SUCCESS == retval) {
stmt->default_fetch_type = mode;
}
/*
* PDO error (if any) has already been raised at this point.
*
* The error_code is cleared, otherwise the caller will read the
* last error message from the driver.
*
*/
PDO_STMT_CLEAR_ERR();
efree(args);
return retval;
}
static PHP_METHOD(PDOStatement, setFetchMode)
{
PHP_STMT_GET_OBJ;
RETVAL_BOOL(
pdo_stmt_setup_fetch_mode(INTERNAL_FUNCTION_PARAM_PASSTHRU,
stmt, 0) == SUCCESS ? 1 : 0
);
}
/* }}} */
/* {{{ proto bool PDOStatement::nextRowset()
Advances to the next rowset in a multi-rowset statement handle. Returns true if it succeeded, false otherwise */
static int pdo_stmt_do_next_rowset(pdo_stmt_t *stmt TSRMLS_DC)
{
/* un-describe */
if (stmt->columns) {
int i;
struct pdo_column_data *cols = stmt->columns;
for (i = 0; i < stmt->column_count; i++) {
efree(cols[i].name);
}
efree(stmt->columns);
stmt->columns = NULL;
stmt->column_count = 0;
}
if (!stmt->methods->next_rowset(stmt TSRMLS_CC)) {
/* Set the executed flag to 0 to reallocate columns on next execute */
stmt->executed = 0;
return 0;
}
pdo_stmt_describe_columns(stmt TSRMLS_CC);
return 1;
}
static PHP_METHOD(PDOStatement, nextRowset)
{
PHP_STMT_GET_OBJ;
if (!stmt->methods->next_rowset) {
pdo_raise_impl_error(stmt->dbh, stmt, "IM001", "driver does not support multiple rowsets" TSRMLS_CC);
RETURN_FALSE;
}
PDO_STMT_CLEAR_ERR();
if (!pdo_stmt_do_next_rowset(stmt TSRMLS_CC)) {
PDO_HANDLE_STMT_ERR();
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool PDOStatement::closeCursor()
Closes the cursor, leaving the statement ready for re-execution. */
static PHP_METHOD(PDOStatement, closeCursor)
{
PHP_STMT_GET_OBJ;
if (!stmt->methods->cursor_closer) {
/* emulate it by fetching and discarding rows */
do {
while (stmt->methods->fetcher(stmt, PDO_FETCH_ORI_NEXT, 0 TSRMLS_CC))
;
if (!stmt->methods->next_rowset) {
break;
}
if (!pdo_stmt_do_next_rowset(stmt TSRMLS_CC)) {
break;
}
} while (1);
stmt->executed = 0;
RETURN_TRUE;
}
PDO_STMT_CLEAR_ERR();
if (!stmt->methods->cursor_closer(stmt TSRMLS_CC)) {
PDO_HANDLE_STMT_ERR();
RETURN_FALSE;
}
stmt->executed = 0;
RETURN_TRUE;
}
/* }}} */
/* {{{ proto void PDOStatement::debugDumpParams()
A utility for internals hackers to debug parameter internals */
static PHP_METHOD(PDOStatement, debugDumpParams)
{
php_stream *out = php_stream_open_wrapper("php://output", "w", 0, NULL);
HashPosition pos;
struct pdo_bound_param_data *param;
PHP_STMT_GET_OBJ;
if (out == NULL) {
RETURN_FALSE;
}
php_stream_printf(out TSRMLS_CC, "SQL: [%d] %.*s\n",
stmt->query_stringlen,
stmt->query_stringlen, stmt->query_string);
php_stream_printf(out TSRMLS_CC, "Params: %d\n",
stmt->bound_params ? zend_hash_num_elements(stmt->bound_params) : 0);
if (stmt->bound_params) {
zend_hash_internal_pointer_reset_ex(stmt->bound_params, &pos);
while (SUCCESS == zend_hash_get_current_data_ex(stmt->bound_params,
(void**)¶m, &pos)) {
char *str;
uint len;
ulong num;
int res;
res = zend_hash_get_current_key_ex(stmt->bound_params, &str, &len, &num, 0, &pos);
if (res == HASH_KEY_IS_LONG) {
php_stream_printf(out TSRMLS_CC, "Key: Position #%ld:\n", num);
} else if (res == HASH_KEY_IS_STRING) {
php_stream_printf(out TSRMLS_CC, "Key: Name: [%d] %.*s\n", len, len, str);
}
php_stream_printf(out TSRMLS_CC, "paramno=%ld\nname=[%d] \"%.*s\"\nis_param=%d\nparam_type=%d\n",
param->paramno, param->namelen, param->namelen, param->name ? param->name : "",
param->is_param,
param->param_type);
zend_hash_move_forward_ex(stmt->bound_params, &pos);
}
}
php_stream_close(out);
}
/* }}} */
/* {{{ proto int PDOStatement::__wakeup()
Prevents use of a PDOStatement instance that has been unserialized */
static PHP_METHOD(PDOStatement, __wakeup)
{
zend_throw_exception_ex(php_pdo_get_exception(), 0 TSRMLS_CC, "You cannot serialize or unserialize PDOStatement instances");
}
/* }}} */
/* {{{ proto int PDOStatement::__sleep()
Prevents serialization of a PDOStatement instance */
static PHP_METHOD(PDOStatement, __sleep)
{
zend_throw_exception_ex(php_pdo_get_exception(), 0 TSRMLS_CC, "You cannot serialize or unserialize PDOStatement instances");
}
/* }}} */
const zend_function_entry pdo_dbstmt_functions[] = {
PHP_ME(PDOStatement, execute, arginfo_pdostatement_execute, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, fetch, arginfo_pdostatement_fetch, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, bindParam, arginfo_pdostatement_bindparam, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, bindColumn, arginfo_pdostatement_bindcolumn, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, bindValue, arginfo_pdostatement_bindvalue, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, rowCount, arginfo_pdostatement__void, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, fetchColumn, arginfo_pdostatement_fetchcolumn, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, fetchAll, arginfo_pdostatement_fetchall, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, fetchObject, arginfo_pdostatement_fetchobject, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, errorCode, arginfo_pdostatement__void, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, errorInfo, arginfo_pdostatement__void, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, setAttribute, arginfo_pdostatement_setattribute, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, getAttribute, arginfo_pdostatement_getattribute, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, columnCount, arginfo_pdostatement__void, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, getColumnMeta, arginfo_pdostatement_getcolumnmeta, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, setFetchMode, arginfo_pdostatement_setfetchmode, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, nextRowset, arginfo_pdostatement__void, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, closeCursor, arginfo_pdostatement__void, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, debugDumpParams, arginfo_pdostatement__void, ZEND_ACC_PUBLIC)
PHP_ME(PDOStatement, __wakeup, arginfo_pdostatement__void, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
PHP_ME(PDOStatement, __sleep, arginfo_pdostatement__void, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
{NULL, NULL, NULL}
};
/* {{{ overloaded handlers for PDOStatement class */
static void dbstmt_prop_write(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC)
{
pdo_stmt_t * stmt = (pdo_stmt_t *) zend_object_store_get_object(object TSRMLS_CC);
convert_to_string(member);
if(strcmp(Z_STRVAL_P(member), "queryString") == 0) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "property queryString is read only" TSRMLS_CC);
} else {
std_object_handlers.write_property(object, member, value, key TSRMLS_CC);
}
}
static void dbstmt_prop_delete(zval *object, zval *member, const zend_literal *key TSRMLS_DC)
{
pdo_stmt_t * stmt = (pdo_stmt_t *) zend_object_store_get_object(object TSRMLS_CC);
convert_to_string(member);
if(strcmp(Z_STRVAL_P(member), "queryString") == 0) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "property queryString is read only" TSRMLS_CC);
} else {
std_object_handlers.unset_property(object, member, key TSRMLS_CC);
}
}
static union _zend_function *dbstmt_method_get(zval **object_pp, char *method_name, int method_len, const zend_literal *key TSRMLS_DC)
{
zend_function *fbc = NULL;
char *lc_method_name;
zval *object = *object_pp;
lc_method_name = emalloc(method_len + 1);
zend_str_tolower_copy(lc_method_name, method_name, method_len);
if (zend_hash_find(&Z_OBJCE_P(object)->function_table, lc_method_name,
method_len+1, (void**)&fbc) == FAILURE) {
pdo_stmt_t *stmt = (pdo_stmt_t*)zend_object_store_get_object(object TSRMLS_CC);
/* instance not created by PDO object */
if (!stmt->dbh) {
goto out;
}
/* not a pre-defined method, nor a user-defined method; check
* the driver specific methods */
if (!stmt->dbh->cls_methods[PDO_DBH_DRIVER_METHOD_KIND_STMT]) {
if (!pdo_hash_methods(stmt->dbh,
PDO_DBH_DRIVER_METHOD_KIND_STMT TSRMLS_CC)
|| !stmt->dbh->cls_methods[PDO_DBH_DRIVER_METHOD_KIND_STMT]) {
goto out;
}
}
if (zend_hash_find(stmt->dbh->cls_methods[PDO_DBH_DRIVER_METHOD_KIND_STMT],
lc_method_name, method_len+1, (void**)&fbc) == FAILURE) {
goto out;
}
/* got it */
}
out:
if (!fbc) {
fbc = std_object_handlers.get_method(object_pp, method_name, method_len, key TSRMLS_CC);
}
efree(lc_method_name);
return fbc;
}
static int dbstmt_compare(zval *object1, zval *object2 TSRMLS_DC)
{
return -1;
}
static zend_object_value dbstmt_clone_obj(zval *zobject TSRMLS_DC)
{
zend_object_value retval;
pdo_stmt_t *stmt;
pdo_stmt_t *old_stmt;
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
stmt = ecalloc(1, sizeof(*stmt));
zend_object_std_init(&stmt->std, Z_OBJCE_P(zobject) TSRMLS_CC);
object_properties_init(&stmt->std, Z_OBJCE_P(zobject));
stmt->refcount = 1;
old_stmt = (pdo_stmt_t *)zend_object_store_get_object(zobject TSRMLS_CC);
retval.handle = zend_objects_store_put(stmt, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t)pdo_dbstmt_free_storage, (zend_objects_store_clone_t)dbstmt_clone_obj TSRMLS_CC);
retval.handlers = Z_OBJ_HT_P(zobject);
zend_objects_clone_members((zend_object *)stmt, retval, (zend_object *)old_stmt, handle TSRMLS_CC);
zend_objects_store_add_ref(&old_stmt->database_object_handle TSRMLS_CC);
stmt->database_object_handle = old_stmt->database_object_handle;
return retval;
}
zend_object_handlers pdo_dbstmt_object_handlers;
static int pdo_row_serialize(zval *object, unsigned char **buffer, zend_uint *buf_len, zend_serialize_data *data TSRMLS_DC);
void pdo_stmt_init(TSRMLS_D)
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "PDOStatement", pdo_dbstmt_functions);
pdo_dbstmt_ce = zend_register_internal_class(&ce TSRMLS_CC);
pdo_dbstmt_ce->get_iterator = pdo_stmt_iter_get;
pdo_dbstmt_ce->create_object = pdo_dbstmt_new;
zend_class_implements(pdo_dbstmt_ce TSRMLS_CC, 1, zend_ce_traversable);
zend_declare_property_null(pdo_dbstmt_ce, "queryString", sizeof("queryString")-1, ZEND_ACC_PUBLIC TSRMLS_CC);
memcpy(&pdo_dbstmt_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
pdo_dbstmt_object_handlers.write_property = dbstmt_prop_write;
pdo_dbstmt_object_handlers.unset_property = dbstmt_prop_delete;
pdo_dbstmt_object_handlers.get_method = dbstmt_method_get;
pdo_dbstmt_object_handlers.compare_objects = dbstmt_compare;
pdo_dbstmt_object_handlers.clone_obj = dbstmt_clone_obj;
INIT_CLASS_ENTRY(ce, "PDORow", pdo_row_functions);
pdo_row_ce = zend_register_internal_class(&ce TSRMLS_CC);
pdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */
pdo_row_ce->create_object = pdo_row_new;
pdo_row_ce->serialize = pdo_row_serialize;
pdo_row_ce->unserialize = zend_class_unserialize_deny;
}
static void free_statement(pdo_stmt_t *stmt TSRMLS_DC)
{
if (stmt->bound_params) {
zend_hash_destroy(stmt->bound_params);
FREE_HASHTABLE(stmt->bound_params);
stmt->bound_params = NULL;
}
if (stmt->bound_param_map) {
zend_hash_destroy(stmt->bound_param_map);
FREE_HASHTABLE(stmt->bound_param_map);
stmt->bound_param_map = NULL;
}
if (stmt->bound_columns) {
zend_hash_destroy(stmt->bound_columns);
FREE_HASHTABLE(stmt->bound_columns);
stmt->bound_columns = NULL;
}
if (stmt->methods && stmt->methods->dtor) {
stmt->methods->dtor(stmt TSRMLS_CC);
}
if (stmt->query_string) {
efree(stmt->query_string);
}
if (stmt->columns) {
int i;
struct pdo_column_data *cols = stmt->columns;
for (i = 0; i < stmt->column_count; i++) {
if (cols[i].name) {
efree(cols[i].name);
cols[i].name = NULL;
}
}
efree(stmt->columns);
stmt->columns = NULL;
}
if (stmt->fetch.into && stmt->default_fetch_type == PDO_FETCH_INTO) {
FREE_ZVAL(stmt->fetch.into);
stmt->fetch.into = NULL;
}
do_fetch_opt_finish(stmt, 1 TSRMLS_CC);
zend_objects_store_del_ref(&stmt->database_object_handle TSRMLS_CC);
if (stmt->dbh) {
php_pdo_dbh_delref(stmt->dbh TSRMLS_CC);
}
zend_object_std_dtor(&stmt->std TSRMLS_CC);
efree(stmt);
}
PDO_API void php_pdo_stmt_addref(pdo_stmt_t *stmt TSRMLS_DC)
{
stmt->refcount++;
}
PDO_API void php_pdo_stmt_delref(pdo_stmt_t *stmt TSRMLS_DC)
{
if (--stmt->refcount == 0) {
free_statement(stmt TSRMLS_CC);
}
}
void pdo_dbstmt_free_storage(pdo_stmt_t *stmt TSRMLS_DC)
{
php_pdo_stmt_delref(stmt TSRMLS_CC);
}
zend_object_value pdo_dbstmt_new(zend_class_entry *ce TSRMLS_DC)
{
zend_object_value retval;
pdo_stmt_t *stmt;
stmt = emalloc(sizeof(*stmt));
memset(stmt, 0, sizeof(*stmt));
zend_object_std_init(&stmt->std, ce TSRMLS_CC);
object_properties_init(&stmt->std, ce);
stmt->refcount = 1;
retval.handle = zend_objects_store_put(stmt, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t)pdo_dbstmt_free_storage, (zend_objects_store_clone_t)dbstmt_clone_obj TSRMLS_CC);
retval.handlers = &pdo_dbstmt_object_handlers;
return retval;
}
/* }}} */
/* {{{ statement iterator */
struct php_pdo_iterator {
zend_object_iterator iter;
pdo_stmt_t *stmt;
ulong key;
zval *fetch_ahead;
};
static void pdo_stmt_iter_dtor(zend_object_iterator *iter TSRMLS_DC)
{
struct php_pdo_iterator *I = (struct php_pdo_iterator*)iter->data;
if (--I->stmt->refcount == 0) {
free_statement(I->stmt TSRMLS_CC);
}
if (I->fetch_ahead) {
zval_ptr_dtor(&I->fetch_ahead);
}
efree(I);
}
static int pdo_stmt_iter_valid(zend_object_iterator *iter TSRMLS_DC)
{
struct php_pdo_iterator *I = (struct php_pdo_iterator*)iter->data;
return I->fetch_ahead ? SUCCESS : FAILURE;
}
static void pdo_stmt_iter_get_data(zend_object_iterator *iter, zval ***data TSRMLS_DC)
{
struct php_pdo_iterator *I = (struct php_pdo_iterator*)iter->data;
/* sanity */
if (!I->fetch_ahead) {
*data = NULL;
return;
}
*data = &I->fetch_ahead;
}
static void pdo_stmt_iter_get_key(zend_object_iterator *iter, zval *key TSRMLS_DC)
{
struct php_pdo_iterator *I = (struct php_pdo_iterator*)iter->data;
if (I->key == (ulong)-1) {
ZVAL_NULL(key);
} else {
ZVAL_LONG(key, I->key);
}
}
static void pdo_stmt_iter_move_forwards(zend_object_iterator *iter TSRMLS_DC)
{
struct php_pdo_iterator *I = (struct php_pdo_iterator*)iter->data;
if (I->fetch_ahead) {
zval_ptr_dtor(&I->fetch_ahead);
I->fetch_ahead = NULL;
}
MAKE_STD_ZVAL(I->fetch_ahead);
if (!do_fetch(I->stmt, TRUE, I->fetch_ahead, PDO_FETCH_USE_DEFAULT,
PDO_FETCH_ORI_NEXT, 0, 0 TSRMLS_CC)) {
pdo_stmt_t *stmt = I->stmt; /* for PDO_HANDLE_STMT_ERR() */
PDO_HANDLE_STMT_ERR();
I->key = (ulong)-1;
FREE_ZVAL(I->fetch_ahead);
I->fetch_ahead = NULL;
return;
}
I->key++;
}
static zend_object_iterator_funcs pdo_stmt_iter_funcs = {
pdo_stmt_iter_dtor,
pdo_stmt_iter_valid,
pdo_stmt_iter_get_data,
pdo_stmt_iter_get_key,
pdo_stmt_iter_move_forwards,
NULL
};
zend_object_iterator *pdo_stmt_iter_get(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
{
pdo_stmt_t *stmt = (pdo_stmt_t*)zend_object_store_get_object(object TSRMLS_CC);
struct php_pdo_iterator *I;
if (by_ref) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
I = ecalloc(1, sizeof(*I));
I->iter.funcs = &pdo_stmt_iter_funcs;
I->iter.data = I;
I->stmt = stmt;
stmt->refcount++;
MAKE_STD_ZVAL(I->fetch_ahead);
if (!do_fetch(I->stmt, TRUE, I->fetch_ahead, PDO_FETCH_USE_DEFAULT,
PDO_FETCH_ORI_NEXT, 0, 0 TSRMLS_CC)) {
PDO_HANDLE_STMT_ERR();
I->key = (ulong)-1;
FREE_ZVAL(I->fetch_ahead);
I->fetch_ahead = NULL;
}
return &I->iter;
}
/* }}} */
/* {{{ overloaded handlers for PDORow class (used by PDO_FETCH_LAZY) */
const zend_function_entry pdo_row_functions[] = {
{NULL, NULL, NULL}
};
static zval *row_prop_read(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC)
{
zval *return_value;
pdo_stmt_t * stmt = (pdo_stmt_t *) zend_object_store_get_object(object TSRMLS_CC);
int colno = -1;
MAKE_STD_ZVAL(return_value);
RETVAL_NULL();
if (stmt) {
if (Z_TYPE_P(member) == IS_LONG) {
if (Z_LVAL_P(member) >= 0 && Z_LVAL_P(member) < stmt->column_count) {
fetch_value(stmt, return_value, Z_LVAL_P(member), NULL TSRMLS_CC);
}
} else {
convert_to_string(member);
/* TODO: replace this with a hash of available column names to column
* numbers */
for (colno = 0; colno < stmt->column_count; colno++) {
if (strcmp(stmt->columns[colno].name, Z_STRVAL_P(member)) == 0) {
fetch_value(stmt, return_value, colno, NULL TSRMLS_CC);
Z_SET_REFCOUNT_P(return_value, 0);
Z_UNSET_ISREF_P(return_value);
return return_value;
}
}
if (strcmp(Z_STRVAL_P(member), "queryString") == 0) {
zval_ptr_dtor(&return_value);
return std_object_handlers.read_property(object, member, type, key TSRMLS_CC);
}
}
}
Z_SET_REFCOUNT_P(return_value, 0);
Z_UNSET_ISREF_P(return_value);
return return_value;
}
static zval *row_dim_read(zval *object, zval *member, int type TSRMLS_DC)
{
return row_prop_read(object, member, type, NULL TSRMLS_CC);
}
static void row_prop_write(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC)
{
php_error_docref(NULL TSRMLS_CC, E_WARNING, "This PDORow is not from a writable result set");
}
static void row_dim_write(zval *object, zval *member, zval *value TSRMLS_DC)
{
php_error_docref(NULL TSRMLS_CC, E_WARNING, "This PDORow is not from a writable result set");
}
static int row_prop_exists(zval *object, zval *member, int check_empty, const zend_literal *key TSRMLS_DC)
{
pdo_stmt_t * stmt = (pdo_stmt_t *) zend_object_store_get_object(object TSRMLS_CC);
int colno = -1;
if (stmt) {
if (Z_TYPE_P(member) == IS_LONG) {
return Z_LVAL_P(member) >= 0 && Z_LVAL_P(member) < stmt->column_count;
} else {
convert_to_string(member);
/* TODO: replace this with a hash of available column names to column
* numbers */
for (colno = 0; colno < stmt->column_count; colno++) {
if (strcmp(stmt->columns[colno].name, Z_STRVAL_P(member)) == 0) {
int res;
zval *val;
MAKE_STD_ZVAL(val);
fetch_value(stmt, val, colno, NULL TSRMLS_CC);
res = check_empty ? i_zend_is_true(val) : Z_TYPE_P(val) != IS_NULL;
zval_ptr_dtor(&val);
return res;
}
}
}
}
return 0;
}
static int row_dim_exists(zval *object, zval *member, int check_empty TSRMLS_DC)
{
return row_prop_exists(object, member, check_empty, NULL TSRMLS_CC);
}
static void row_prop_delete(zval *object, zval *offset, const zend_literal *key TSRMLS_DC)
{
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot delete properties from a PDORow");
}
static void row_dim_delete(zval *object, zval *offset TSRMLS_DC)
{
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot delete properties from a PDORow");
}
static HashTable *row_get_properties(zval *object TSRMLS_DC)
{
pdo_stmt_t * stmt = (pdo_stmt_t *) zend_object_store_get_object(object TSRMLS_CC);
int i;
if (stmt == NULL) {
return NULL;
}
if (!stmt->std.properties) {
rebuild_object_properties(&stmt->std);
}
for (i = 0; i < stmt->column_count; i++) {
zval *val;
MAKE_STD_ZVAL(val);
fetch_value(stmt, val, i, NULL TSRMLS_CC);
zend_hash_update(stmt->std.properties, stmt->columns[i].name, stmt->columns[i].namelen + 1, (void *)&val, sizeof(zval *), NULL);
}
return stmt->std.properties;
}
static union _zend_function *row_method_get(
zval **object_pp,
char *method_name, int method_len, const zend_literal *key TSRMLS_DC)
{
zend_function *fbc;
char *lc_method_name;
lc_method_name = emalloc(method_len + 1);
zend_str_tolower_copy(lc_method_name, method_name, method_len);
if (zend_hash_find(&pdo_row_ce->function_table, lc_method_name, method_len+1, (void**)&fbc) == FAILURE) {
efree(lc_method_name);
return NULL;
}
efree(lc_method_name);
return fbc;
}
static int row_call_method(const char *method, INTERNAL_FUNCTION_PARAMETERS)
{
return FAILURE;
}
static union _zend_function *row_get_ctor(zval *object TSRMLS_DC)
{
static zend_internal_function ctor = {0};
ctor.type = ZEND_INTERNAL_FUNCTION;
ctor.function_name = "__construct";
ctor.scope = pdo_row_ce;
ctor.handler = ZEND_FN(dbstmt_constructor);
ctor.fn_flags = ZEND_ACC_PUBLIC;
return (union _zend_function*)&ctor;
}
static zend_class_entry *row_get_ce(const zval *object TSRMLS_DC)
{
return pdo_row_ce;
}
static int row_get_classname(const zval *object, const char **class_name, zend_uint *class_name_len, int parent TSRMLS_DC)
{
if (parent) {
return FAILURE;
} else {
*class_name = estrndup("PDORow", sizeof("PDORow")-1);
*class_name_len = sizeof("PDORow")-1;
return SUCCESS;
}
}
static int row_compare(zval *object1, zval *object2 TSRMLS_DC)
{
return -1;
}
zend_object_handlers pdo_row_object_handlers = {
zend_objects_store_add_ref,
zend_objects_store_del_ref,
NULL,
row_prop_read,
row_prop_write,
row_dim_read,
row_dim_write,
NULL,
NULL,
NULL,
row_prop_exists,
row_prop_delete,
row_dim_exists,
row_dim_delete,
row_get_properties,
row_method_get,
row_call_method,
row_get_ctor,
row_get_ce,
row_get_classname,
row_compare,
NULL, /* cast */
NULL
};
void pdo_row_free_storage(pdo_stmt_t *stmt TSRMLS_DC)
{
if (stmt) {
ZVAL_NULL(&stmt->lazy_object_ref);
if (--stmt->refcount == 0) {
free_statement(stmt TSRMLS_CC);
}
}
}
zend_object_value pdo_row_new(zend_class_entry *ce TSRMLS_DC)
{
zend_object_value retval;
retval.handle = zend_objects_store_put(NULL, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t)pdo_row_free_storage, NULL TSRMLS_CC);
retval.handlers = &pdo_row_object_handlers;
return retval;
}
static int pdo_row_serialize(zval *object, unsigned char **buffer, zend_uint *buf_len, zend_serialize_data *data TSRMLS_DC)
{
php_error_docref(NULL TSRMLS_CC, E_WARNING, "PDORow instances may not be serialized");
return FAILURE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5514_0 |
crossvul-cpp_data_bad_321_0 | /************************************************************
* Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of Silicon Graphics not be
* used in advertising or publicity pertaining to distribution
* of the software without specific prior written permission.
* Silicon Graphics makes no representation about the suitability
* of this software for any purpose. It is provided "as is"
* without any express or implied warranty.
*
* SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS BE LIABLE FOR 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.
*
********************************************************/
#include "xkbcomp-priv.h"
#include "text.h"
#include "expr.h"
#include "include.h"
typedef struct {
enum merge_mode merge;
xkb_atom_t alias;
xkb_atom_t real;
} AliasInfo;
typedef struct {
enum merge_mode merge;
xkb_atom_t name;
} LedNameInfo;
typedef struct {
char *name;
int errorCount;
xkb_keycode_t min_key_code;
xkb_keycode_t max_key_code;
darray(xkb_atom_t) key_names;
LedNameInfo led_names[XKB_MAX_LEDS];
unsigned int num_led_names;
darray(AliasInfo) aliases;
struct xkb_context *ctx;
} KeyNamesInfo;
/***====================================================================***/
static void
InitAliasInfo(AliasInfo *info, enum merge_mode merge,
xkb_atom_t alias, xkb_atom_t real)
{
memset(info, 0, sizeof(*info));
info->merge = merge;
info->alias = alias;
info->real = real;
}
static LedNameInfo *
FindLedByName(KeyNamesInfo *info, xkb_atom_t name,
xkb_led_index_t *idx_out)
{
for (xkb_led_index_t idx = 0; idx < info->num_led_names; idx++) {
LedNameInfo *ledi = &info->led_names[idx];
if (ledi->name == name) {
*idx_out = idx;
return ledi;
}
}
return NULL;
}
static bool
AddLedName(KeyNamesInfo *info, enum merge_mode merge, bool same_file,
LedNameInfo *new, xkb_led_index_t new_idx)
{
xkb_led_index_t old_idx;
LedNameInfo *old;
const int verbosity = xkb_context_get_log_verbosity(info->ctx);
const bool report = (same_file && verbosity > 0) || verbosity > 9;
const bool replace = (merge == MERGE_REPLACE || merge == MERGE_OVERRIDE);
/* LED with the same name already exists. */
old = FindLedByName(info, new->name, &old_idx);
if (old) {
if (old_idx == new_idx) {
log_warn(info->ctx,
"Multiple indicators named \"%s\"; "
"Identical definitions ignored\n",
xkb_atom_text(info->ctx, new->name));
return true;
}
if (report) {
xkb_led_index_t use = (replace ? new_idx + 1 : old_idx + 1);
xkb_led_index_t ignore = (replace ? old_idx + 1 : new_idx + 1);
log_warn(info->ctx,
"Multiple indicators named %s; Using %d, ignoring %d\n",
xkb_atom_text(info->ctx, new->name), use, ignore);
}
if (replace)
*old = *new;
return true;
}
if (new_idx >= info->num_led_names)
info->num_led_names = new_idx + 1;
/* LED with the same index already exists. */
old = &info->led_names[new_idx];
if (old->name != XKB_ATOM_NONE) {
if (report) {
const xkb_atom_t use = (replace ? new->name : old->name);
const xkb_atom_t ignore = (replace ? old->name : new->name);
log_warn(info->ctx, "Multiple names for indicator %d; "
"Using %s, ignoring %s\n", new_idx + 1,
xkb_atom_text(info->ctx, use),
xkb_atom_text(info->ctx, ignore));
}
if (replace)
*old = *new;
return true;
}
*old = *new;
return true;
}
static void
ClearKeyNamesInfo(KeyNamesInfo *info)
{
free(info->name);
darray_free(info->key_names);
darray_free(info->aliases);
}
static void
InitKeyNamesInfo(KeyNamesInfo *info, struct xkb_context *ctx)
{
memset(info, 0, sizeof(*info));
info->ctx = ctx;
info->min_key_code = XKB_KEYCODE_INVALID;
#if XKB_KEYCODE_INVALID < XKB_KEYCODE_MAX
#error "Hey, you can't be changing stuff like that."
#endif
}
static xkb_keycode_t
FindKeyByName(KeyNamesInfo *info, xkb_atom_t name)
{
xkb_keycode_t i;
for (i = info->min_key_code; i <= info->max_key_code; i++)
if (darray_item(info->key_names, i) == name)
return i;
return XKB_KEYCODE_INVALID;
}
static bool
AddKeyName(KeyNamesInfo *info, xkb_keycode_t kc, xkb_atom_t name,
enum merge_mode merge, bool same_file, bool report)
{
xkb_atom_t old_name;
xkb_keycode_t old_kc;
const int verbosity = xkb_context_get_log_verbosity(info->ctx);
report = report && ((same_file && verbosity > 0) || verbosity > 7);
if (kc >= darray_size(info->key_names))
darray_resize0(info->key_names, kc + 1);
info->min_key_code = MIN(info->min_key_code, kc);
info->max_key_code = MAX(info->max_key_code, kc);
/* There's already a key with this keycode. */
old_name = darray_item(info->key_names, kc);
if (old_name != XKB_ATOM_NONE) {
const char *lname = KeyNameText(info->ctx, old_name);
const char *kname = KeyNameText(info->ctx, name);
if (old_name == name) {
if (report)
log_warn(info->ctx,
"Multiple identical key name definitions; "
"Later occurrences of \"%s = %d\" ignored\n",
lname, kc);
return true;
}
else if (merge == MERGE_AUGMENT) {
if (report)
log_warn(info->ctx,
"Multiple names for keycode %d; "
"Using %s, ignoring %s\n", kc, lname, kname);
return true;
}
else {
if (report)
log_warn(info->ctx,
"Multiple names for keycode %d; "
"Using %s, ignoring %s\n", kc, kname, lname);
darray_item(info->key_names, kc) = XKB_ATOM_NONE;
}
}
/* There's already a key with this name. */
old_kc = FindKeyByName(info, name);
if (old_kc != XKB_KEYCODE_INVALID && old_kc != kc) {
const char *kname = KeyNameText(info->ctx, name);
if (merge == MERGE_OVERRIDE) {
darray_item(info->key_names, old_kc) = XKB_ATOM_NONE;
if (report)
log_warn(info->ctx,
"Key name %s assigned to multiple keys; "
"Using %d, ignoring %d\n", kname, kc, old_kc);
}
else {
if (report)
log_vrb(info->ctx, 3,
"Key name %s assigned to multiple keys; "
"Using %d, ignoring %d\n", kname, old_kc, kc);
return true;
}
}
darray_item(info->key_names, kc) = name;
return true;
}
/***====================================================================***/
static bool
HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge);
static void
MergeIncludedKeycodes(KeyNamesInfo *into, KeyNamesInfo *from,
enum merge_mode merge)
{
if (from->errorCount > 0) {
into->errorCount += from->errorCount;
return;
}
if (into->name == NULL) {
into->name = from->name;
from->name = NULL;
}
/* Merge key names. */
if (darray_empty(into->key_names)) {
into->key_names = from->key_names;
darray_init(from->key_names);
into->min_key_code = from->min_key_code;
into->max_key_code = from->max_key_code;
}
else {
if (darray_size(into->key_names) < darray_size(from->key_names))
darray_resize0(into->key_names, darray_size(from->key_names));
for (unsigned i = from->min_key_code; i <= from->max_key_code; i++) {
xkb_atom_t name = darray_item(from->key_names, i);
if (name == XKB_ATOM_NONE)
continue;
if (!AddKeyName(into, i, name, merge, true, false))
into->errorCount++;
}
}
/* Merge key aliases. */
if (darray_empty(into->aliases)) {
into->aliases = from->aliases;
darray_init(from->aliases);
}
else {
AliasInfo *alias;
darray_foreach(alias, from->aliases) {
KeyAliasDef def;
def.merge = (merge == MERGE_DEFAULT ? alias->merge : merge);
def.alias = alias->alias;
def.real = alias->real;
if (!HandleAliasDef(into, &def, def.merge))
into->errorCount++;
}
}
/* Merge LED names. */
if (into->num_led_names == 0) {
memcpy(into->led_names, from->led_names,
sizeof(*from->led_names) * from->num_led_names);
into->num_led_names = from->num_led_names;
from->num_led_names = 0;
}
else {
for (xkb_led_index_t idx = 0; idx < from->num_led_names; idx++) {
LedNameInfo *ledi = &from->led_names[idx];
if (ledi->name == XKB_ATOM_NONE)
continue;
ledi->merge = (merge == MERGE_DEFAULT ? ledi->merge : merge);
if (!AddLedName(into, ledi->merge, false, ledi, idx))
into->errorCount++;
}
}
}
static void
HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge);
static bool
HandleIncludeKeycodes(KeyNamesInfo *info, IncludeStmt *include)
{
KeyNamesInfo included;
InitKeyNamesInfo(&included, info->ctx);
included.name = include->stmt;
include->stmt = NULL;
for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) {
KeyNamesInfo next_incl;
XkbFile *file;
file = ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_KEYCODES);
if (!file) {
info->errorCount += 10;
ClearKeyNamesInfo(&included);
return false;
}
InitKeyNamesInfo(&next_incl, info->ctx);
HandleKeycodesFile(&next_incl, file, MERGE_OVERRIDE);
MergeIncludedKeycodes(&included, &next_incl, stmt->merge);
ClearKeyNamesInfo(&next_incl);
FreeXkbFile(file);
}
MergeIncludedKeycodes(info, &included, include->merge);
ClearKeyNamesInfo(&included);
return (info->errorCount == 0);
}
static bool
HandleKeycodeDef(KeyNamesInfo *info, KeycodeDef *stmt, enum merge_mode merge)
{
if (stmt->merge != MERGE_DEFAULT) {
if (stmt->merge == MERGE_REPLACE)
merge = MERGE_OVERRIDE;
else
merge = stmt->merge;
}
if (stmt->value < 0 || stmt->value > XKB_KEYCODE_MAX) {
log_err(info->ctx,
"Illegal keycode %lld: must be between 0..%u; "
"Key ignored\n", (long long) stmt->value, XKB_KEYCODE_MAX);
return false;
}
return AddKeyName(info, stmt->value, stmt->name, merge, false, true);
}
static bool
HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge)
{
AliasInfo *old, new;
darray_foreach(old, info->aliases) {
if (old->alias == def->alias) {
if (def->real == old->real) {
log_vrb(info->ctx, 1,
"Alias of %s for %s declared more than once; "
"First definition ignored\n",
KeyNameText(info->ctx, def->alias),
KeyNameText(info->ctx, def->real));
}
else {
xkb_atom_t use, ignore;
use = (merge == MERGE_AUGMENT ? old->real : def->real);
ignore = (merge == MERGE_AUGMENT ? def->real : old->real);
log_warn(info->ctx,
"Multiple definitions for alias %s; "
"Using %s, ignoring %s\n",
KeyNameText(info->ctx, old->alias),
KeyNameText(info->ctx, use),
KeyNameText(info->ctx, ignore));
old->real = use;
}
old->merge = merge;
return true;
}
}
InitAliasInfo(&new, merge, def->alias, def->real);
darray_append(info->aliases, new);
return true;
}
static bool
HandleKeyNameVar(KeyNamesInfo *info, VarDef *stmt)
{
const char *elem, *field;
ExprDef *arrayNdx;
if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &arrayNdx))
return false;
if (elem) {
log_err(info->ctx, "Unknown element %s encountered; "
"Default for field %s ignored\n", elem, field);
return false;
}
if (!istreq(field, "minimum") && !istreq(field, "maximum")) {
log_err(info->ctx, "Unknown field encountered; "
"Assignment to field %s ignored\n", field);
return false;
}
/* We ignore explicit min/max statements, we always use computed. */
return true;
}
static bool
HandleLedNameDef(KeyNamesInfo *info, LedNameDef *def,
enum merge_mode merge)
{
LedNameInfo ledi;
xkb_atom_t name;
if (def->ndx < 1 || def->ndx > XKB_MAX_LEDS) {
info->errorCount++;
log_err(info->ctx,
"Illegal indicator index (%d) specified; must be between 1 .. %d; "
"Ignored\n", def->ndx, XKB_MAX_LEDS);
return false;
}
if (!ExprResolveString(info->ctx, def->name, &name)) {
char buf[20];
snprintf(buf, sizeof(buf), "%u", def->ndx);
info->errorCount++;
return ReportBadType(info->ctx, "indicator", "name", buf, "string");
}
ledi.merge = merge;
ledi.name = name;
return AddLedName(info, merge, true, &ledi, def->ndx - 1);
}
static void
HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge)
{
bool ok;
free(info->name);
info->name = strdup_safe(file->name);
for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) {
switch (stmt->type) {
case STMT_INCLUDE:
ok = HandleIncludeKeycodes(info, (IncludeStmt *) stmt);
break;
case STMT_KEYCODE:
ok = HandleKeycodeDef(info, (KeycodeDef *) stmt, merge);
break;
case STMT_ALIAS:
ok = HandleAliasDef(info, (KeyAliasDef *) stmt, merge);
break;
case STMT_VAR:
ok = HandleKeyNameVar(info, (VarDef *) stmt);
break;
case STMT_LED_NAME:
ok = HandleLedNameDef(info, (LedNameDef *) stmt, merge);
break;
default:
log_err(info->ctx,
"Keycode files may define key and indicator names only; "
"Ignoring %s\n", stmt_type_to_string(stmt->type));
ok = false;
break;
}
if (!ok)
info->errorCount++;
if (info->errorCount > 10) {
log_err(info->ctx, "Abandoning keycodes file \"%s\"\n",
file->name);
break;
}
}
}
/***====================================================================***/
static bool
CopyKeyNamesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
{
struct xkb_key *keys;
xkb_keycode_t min_key_code, max_key_code, kc;
min_key_code = info->min_key_code;
max_key_code = info->max_key_code;
/* If the keymap has no keys, let's just use the safest pair we know. */
if (min_key_code == XKB_KEYCODE_INVALID) {
min_key_code = 8;
max_key_code = 255;
}
keys = calloc(max_key_code + 1, sizeof(*keys));
if (!keys)
return false;
for (kc = min_key_code; kc <= max_key_code; kc++)
keys[kc].keycode = kc;
for (kc = info->min_key_code; kc <= info->max_key_code; kc++)
keys[kc].name = darray_item(info->key_names, kc);
keymap->min_key_code = min_key_code;
keymap->max_key_code = max_key_code;
keymap->keys = keys;
return true;
}
static bool
CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
{
AliasInfo *alias;
unsigned i, num_key_aliases;
struct xkb_key_alias *key_aliases;
/*
* Do some sanity checking on the aliases. We can't do it before
* because keys and their aliases may be added out-of-order.
*/
num_key_aliases = 0;
darray_foreach(alias, info->aliases) {
/* Check that ->real is a key. */
if (!XkbKeyByName(keymap, alias->real, false)) {
log_vrb(info->ctx, 5,
"Attempt to alias %s to non-existent key %s; Ignored\n",
KeyNameText(info->ctx, alias->alias),
KeyNameText(info->ctx, alias->real));
alias->real = XKB_ATOM_NONE;
continue;
}
/* Check that ->alias is not a key. */
if (XkbKeyByName(keymap, alias->alias, false)) {
log_vrb(info->ctx, 5,
"Attempt to create alias with the name of a real key; "
"Alias \"%s = %s\" ignored\n",
KeyNameText(info->ctx, alias->alias),
KeyNameText(info->ctx, alias->real));
alias->real = XKB_ATOM_NONE;
continue;
}
num_key_aliases++;
}
/* Copy key aliases. */
key_aliases = NULL;
if (num_key_aliases > 0) {
key_aliases = calloc(num_key_aliases, sizeof(*key_aliases));
if (!key_aliases)
return false;
}
i = 0;
darray_foreach(alias, info->aliases) {
if (alias->real != XKB_ATOM_NONE) {
key_aliases[i].alias = alias->alias;
key_aliases[i].real = alias->real;
i++;
}
}
keymap->num_key_aliases = num_key_aliases;
keymap->key_aliases = key_aliases;
return true;
}
static bool
CopyLedNamesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
{
keymap->num_leds = info->num_led_names;
for (xkb_led_index_t idx = 0; idx < info->num_led_names; idx++) {
LedNameInfo *ledi = &info->led_names[idx];
if (ledi->name == XKB_ATOM_NONE)
continue;
keymap->leds[idx].name = ledi->name;
}
return true;
}
static bool
CopyKeyNamesInfoToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
{
/* This function trashes keymap on error, but that's OK. */
if (!CopyKeyNamesToKeymap(keymap, info) ||
!CopyKeyAliasesToKeymap(keymap, info) ||
!CopyLedNamesToKeymap(keymap, info))
return false;
keymap->keycodes_section_name = strdup_safe(info->name);
XkbEscapeMapName(keymap->keycodes_section_name);
return true;
}
/***====================================================================***/
bool
CompileKeycodes(XkbFile *file, struct xkb_keymap *keymap,
enum merge_mode merge)
{
KeyNamesInfo info;
InitKeyNamesInfo(&info, keymap->ctx);
HandleKeycodesFile(&info, file, merge);
if (info.errorCount != 0)
goto err_info;
if (!CopyKeyNamesInfoToKeymap(keymap, &info))
goto err_info;
ClearKeyNamesInfo(&info);
return true;
err_info:
ClearKeyNamesInfo(&info);
return false;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_321_0 |
crossvul-cpp_data_good_5714_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* RDP Core
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <winpr/crt.h>
#include "rdp.h"
#include "info.h"
#include "redirection.h"
#include <freerdp/crypto/per.h>
#ifdef WITH_DEBUG_RDP
static const char* const DATA_PDU_TYPE_STRINGS[] =
{
"?", "?", /* 0x00 - 0x01 */
"Update", /* 0x02 */
"?", "?", "?", "?", "?", "?", "?", "?", /* 0x03 - 0x0A */
"?", "?", "?", "?", "?", "?", "?", "?", "?", /* 0x0B - 0x13 */
"Control", /* 0x14 */
"?", "?", "?", "?", "?", "?", /* 0x15 - 0x1A */
"Pointer", /* 0x1B */
"Input", /* 0x1C */
"?", "?", /* 0x1D - 0x1E */
"Synchronize", /* 0x1F */
"?", /* 0x20 */
"Refresh Rect", /* 0x21 */
"Play Sound", /* 0x22 */
"Suppress Output", /* 0x23 */
"Shutdown Request", /* 0x24 */
"Shutdown Denied", /* 0x25 */
"Save Session Info", /* 0x26 */
"Font List", /* 0x27 */
"Font Map", /* 0x28 */
"Set Keyboard Indicators", /* 0x29 */
"?", /* 0x2A */
"Bitmap Cache Persistent List", /* 0x2B */
"Bitmap Cache Error", /* 0x2C */
"Set Keyboard IME Status", /* 0x2D */
"Offscreen Cache Error", /* 0x2E */
"Set Error Info", /* 0x2F */
"Draw Nine Grid Error", /* 0x30 */
"Draw GDI+ Error", /* 0x31 */
"ARC Status", /* 0x32 */
"?", "?", "?", /* 0x33 - 0x35 */
"Status Info", /* 0x36 */
"Monitor Layout" /* 0x37 */
"?", "?", "?", /* 0x38 - 0x40 */
"?", "?", "?", "?", "?", "?" /* 0x41 - 0x46 */
};
#endif
/**
* Read RDP Security Header.\n
* @msdn{cc240579}
* @param s stream
* @param flags security flags
*/
BOOL rdp_read_security_header(STREAM* s, UINT16* flags)
{
/* Basic Security Header */
if(stream_get_left(s) < 4)
return FALSE;
stream_read_UINT16(s, *flags); /* flags */
stream_seek(s, 2); /* flagsHi (unused) */
return TRUE;
}
/**
* Write RDP Security Header.\n
* @msdn{cc240579}
* @param s stream
* @param flags security flags
*/
void rdp_write_security_header(STREAM* s, UINT16 flags)
{
/* Basic Security Header */
stream_write_UINT16(s, flags); /* flags */
stream_write_UINT16(s, 0); /* flagsHi (unused) */
}
BOOL rdp_read_share_control_header(STREAM* s, UINT16* length, UINT16* type, UINT16* channel_id)
{
if (stream_get_left(s) < 2)
return FALSE;
/* Share Control Header */
stream_read_UINT16(s, *length); /* totalLength */
if (*length - 2 > stream_get_left(s))
return FALSE;
stream_read_UINT16(s, *type); /* pduType */
*type &= 0x0F; /* type is in the 4 least significant bits */
if (*length > 4)
stream_read_UINT16(s, *channel_id); /* pduSource */
else
*channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */
return TRUE;
}
void rdp_write_share_control_header(STREAM* s, UINT16 length, UINT16 type, UINT16 channel_id)
{
length -= RDP_PACKET_HEADER_MAX_LENGTH;
/* Share Control Header */
stream_write_UINT16(s, length); /* totalLength */
stream_write_UINT16(s, type | 0x10); /* pduType */
stream_write_UINT16(s, channel_id); /* pduSource */
}
BOOL rdp_read_share_data_header(STREAM* s, UINT16* length, BYTE* type, UINT32* share_id,
BYTE *compressed_type, UINT16 *compressed_len)
{
if (stream_get_left(s) < 12)
return FALSE;
/* Share Data Header */
stream_read_UINT32(s, *share_id); /* shareId (4 bytes) */
stream_seek_BYTE(s); /* pad1 (1 byte) */
stream_seek_BYTE(s); /* streamId (1 byte) */
stream_read_UINT16(s, *length); /* uncompressedLength (2 bytes) */
stream_read_BYTE(s, *type); /* pduType2, Data PDU Type (1 byte) */
stream_read_BYTE(s, *compressed_type); /* compressedType (1 byte) */
stream_read_UINT16(s, *compressed_len); /* compressedLength (2 bytes) */
return TRUE;
}
void rdp_write_share_data_header(STREAM* s, UINT16 length, BYTE type, UINT32 share_id)
{
length -= RDP_PACKET_HEADER_MAX_LENGTH;
length -= RDP_SHARE_CONTROL_HEADER_LENGTH;
length -= RDP_SHARE_DATA_HEADER_LENGTH;
/* Share Data Header */
stream_write_UINT32(s, share_id); /* shareId (4 bytes) */
stream_write_BYTE(s, 0); /* pad1 (1 byte) */
stream_write_BYTE(s, STREAM_LOW); /* streamId (1 byte) */
stream_write_UINT16(s, length); /* uncompressedLength (2 bytes) */
stream_write_BYTE(s, type); /* pduType2, Data PDU Type (1 byte) */
stream_write_BYTE(s, 0); /* compressedType (1 byte) */
stream_write_UINT16(s, 0); /* compressedLength (2 bytes) */
}
static int rdp_security_stream_init(rdpRdp* rdp, STREAM* s)
{
if (rdp->do_crypt)
{
stream_seek(s, 12);
if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
stream_seek(s, 4);
rdp->sec_flags |= SEC_ENCRYPT;
if (rdp->do_secure_checksum)
rdp->sec_flags |= SEC_SECURE_CHECKSUM;
}
else if (rdp->sec_flags != 0)
{
stream_seek(s, 4);
}
return 0;
}
/**
* Initialize an RDP packet stream.\n
* @param rdp rdp module
* @return
*/
STREAM* rdp_send_stream_init(rdpRdp* rdp)
{
STREAM* s;
s = transport_send_stream_init(rdp->transport, 2048);
stream_seek(s, RDP_PACKET_HEADER_MAX_LENGTH);
rdp_security_stream_init(rdp, s);
return s;
}
STREAM* rdp_pdu_init(rdpRdp* rdp)
{
STREAM* s;
s = transport_send_stream_init(rdp->transport, 2048);
stream_seek(s, RDP_PACKET_HEADER_MAX_LENGTH);
rdp_security_stream_init(rdp, s);
stream_seek(s, RDP_SHARE_CONTROL_HEADER_LENGTH);
return s;
}
STREAM* rdp_data_pdu_init(rdpRdp* rdp)
{
STREAM* s;
s = transport_send_stream_init(rdp->transport, 2048);
stream_seek(s, RDP_PACKET_HEADER_MAX_LENGTH);
rdp_security_stream_init(rdp, s);
stream_seek(s, RDP_SHARE_CONTROL_HEADER_LENGTH);
stream_seek(s, RDP_SHARE_DATA_HEADER_LENGTH);
return s;
}
/**
* Read an RDP packet header.\n
* @param rdp rdp module
* @param s stream
* @param length RDP packet length
* @param channel_id channel id
*/
BOOL rdp_read_header(rdpRdp* rdp, STREAM* s, UINT16* length, UINT16* channel_id)
{
UINT16 initiator;
enum DomainMCSPDU MCSPDU;
MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataRequest : DomainMCSPDU_SendDataIndication;
if (!mcs_read_domain_mcspdu_header(s, &MCSPDU, length))
{
if (MCSPDU != DomainMCSPDU_DisconnectProviderUltimatum)
return FALSE;
}
if (*length - 8 > stream_get_left(s))
return FALSE;
if (MCSPDU == DomainMCSPDU_DisconnectProviderUltimatum)
{
BYTE reason;
(void) per_read_enumerated(s, &reason, 0);
DEBUG_RDP("DisconnectProviderUltimatum from server, reason code 0x%02x\n", reason);
rdp->disconnect = TRUE;
return TRUE;
}
if(stream_get_left(s) < 5)
return FALSE;
per_read_integer16(s, &initiator, MCS_BASE_CHANNEL_ID); /* initiator (UserId) */
per_read_integer16(s, channel_id, 0); /* channelId */
stream_seek(s, 1); /* dataPriority + Segmentation (0x70) */
if(!per_read_length(s, length)) /* userData (OCTET_STRING) */
return FALSE;
if (*length > stream_get_left(s))
return FALSE;
return TRUE;
}
/**
* Write an RDP packet header.\n
* @param rdp rdp module
* @param s stream
* @param length RDP packet length
* @param channel_id channel id
*/
void rdp_write_header(rdpRdp* rdp, STREAM* s, UINT16 length, UINT16 channel_id)
{
int body_length;
enum DomainMCSPDU MCSPDU;
MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataIndication : DomainMCSPDU_SendDataRequest;
if ((rdp->sec_flags & SEC_ENCRYPT) && (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS))
{
int pad;
body_length = length - RDP_PACKET_HEADER_MAX_LENGTH - 16;
pad = 8 - (body_length % 8);
if (pad != 8)
length += pad;
}
mcs_write_domain_mcspdu_header(s, MCSPDU, length, 0);
per_write_integer16(s, rdp->mcs->user_id, MCS_BASE_CHANNEL_ID); /* initiator */
per_write_integer16(s, channel_id, 0); /* channelId */
stream_write_BYTE(s, 0x70); /* dataPriority + segmentation */
/*
* We always encode length in two bytes, eventhough we could use
* only one byte if length <= 0x7F. It is just easier that way,
* because we can leave room for fixed-length header, store all
* the data first and then store the header.
*/
length = (length - RDP_PACKET_HEADER_MAX_LENGTH) | 0x8000;
stream_write_UINT16_be(s, length); /* userData (OCTET_STRING) */
}
static UINT32 rdp_security_stream_out(rdpRdp* rdp, STREAM* s, int length)
{
BYTE* data;
UINT32 sec_flags;
UINT32 pad = 0;
sec_flags = rdp->sec_flags;
if (sec_flags != 0)
{
rdp_write_security_header(s, sec_flags);
if (sec_flags & SEC_ENCRYPT)
{
if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
{
data = s->p + 12;
length = length - (data - s->data);
stream_write_UINT16(s, 0x10); /* length */
stream_write_BYTE(s, 0x1); /* TSFIPS_VERSION 1*/
/* handle padding */
pad = 8 - (length % 8);
if (pad == 8)
pad = 0;
if (pad)
memset(data+length, 0, pad);
stream_write_BYTE(s, pad);
security_hmac_signature(data, length, s->p, rdp);
stream_seek(s, 8);
security_fips_encrypt(data, length + pad, rdp);
}
else
{
data = s->p + 8;
length = length - (data - s->data);
if (sec_flags & SEC_SECURE_CHECKSUM)
security_salted_mac_signature(rdp, data, length, TRUE, s->p);
else
security_mac_signature(rdp, data, length, s->p);
stream_seek(s, 8);
security_encrypt(s->p, length, rdp);
}
}
rdp->sec_flags = 0;
}
return pad;
}
static UINT32 rdp_get_sec_bytes(rdpRdp* rdp)
{
UINT32 sec_bytes;
if (rdp->sec_flags & SEC_ENCRYPT)
{
sec_bytes = 12;
if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
sec_bytes += 4;
}
else if (rdp->sec_flags != 0)
{
sec_bytes = 4;
}
else
{
sec_bytes = 0;
}
return sec_bytes;
}
/**
* Send an RDP packet.\n
* @param rdp RDP module
* @param s stream
* @param channel_id channel id
*/
BOOL rdp_send(rdpRdp* rdp, STREAM* s, UINT16 channel_id)
{
UINT16 length;
UINT32 sec_bytes;
BYTE* sec_hold;
length = stream_get_length(s);
stream_set_pos(s, 0);
rdp_write_header(rdp, s, length, channel_id);
sec_bytes = rdp_get_sec_bytes(rdp);
sec_hold = s->p;
stream_seek(s, sec_bytes);
s->p = sec_hold;
length += rdp_security_stream_out(rdp, s, length);
stream_set_pos(s, length);
if (transport_write(rdp->transport, s) < 0)
return FALSE;
return TRUE;
}
BOOL rdp_send_pdu(rdpRdp* rdp, STREAM* s, UINT16 type, UINT16 channel_id)
{
UINT16 length;
UINT32 sec_bytes;
BYTE* sec_hold;
length = stream_get_length(s);
stream_set_pos(s, 0);
rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID);
sec_bytes = rdp_get_sec_bytes(rdp);
sec_hold = s->p;
stream_seek(s, sec_bytes);
rdp_write_share_control_header(s, length - sec_bytes, type, channel_id);
s->p = sec_hold;
length += rdp_security_stream_out(rdp, s, length);
stream_set_pos(s, length);
if (transport_write(rdp->transport, s) < 0)
return FALSE;
return TRUE;
}
BOOL rdp_send_data_pdu(rdpRdp* rdp, STREAM* s, BYTE type, UINT16 channel_id)
{
UINT16 length;
UINT32 sec_bytes;
BYTE* sec_hold;
length = stream_get_length(s);
stream_set_pos(s, 0);
rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID);
sec_bytes = rdp_get_sec_bytes(rdp);
sec_hold = s->p;
stream_seek(s, sec_bytes);
rdp_write_share_control_header(s, length - sec_bytes, PDU_TYPE_DATA, channel_id);
rdp_write_share_data_header(s, length - sec_bytes, type, rdp->settings->ShareId);
s->p = sec_hold;
length += rdp_security_stream_out(rdp, s, length);
stream_set_pos(s, length);
if (transport_write(rdp->transport, s) < 0)
return FALSE;
return TRUE;
}
BOOL rdp_recv_set_error_info_data_pdu(rdpRdp* rdp, STREAM* s)
{
if (stream_get_left(s) < 4)
return FALSE;
stream_read_UINT32(s, rdp->errorInfo); /* errorInfo (4 bytes) */
if (rdp->errorInfo != ERRINFO_SUCCESS)
rdp_print_errinfo(rdp->errorInfo);
return TRUE;
}
int rdp_recv_data_pdu(rdpRdp* rdp, STREAM* s)
{
BYTE type;
UINT16 length;
UINT32 share_id;
BYTE compressed_type;
UINT16 compressed_len;
UINT32 roff;
UINT32 rlen;
STREAM* comp_stream;
if (!rdp_read_share_data_header(s, &length, &type, &share_id, &compressed_type, &compressed_len))
return -1;
comp_stream = s;
if (compressed_type & PACKET_COMPRESSED)
{
if (stream_get_left(s) < compressed_len - 18)
{
printf("decompress_rdp: not enough bytes for compressed_len=%d\n", compressed_len);
return -1;
}
if (decompress_rdp(rdp->mppc_dec, s->p, compressed_len - 18, compressed_type, &roff, &rlen))
{
comp_stream = stream_new(0);
comp_stream->data = rdp->mppc_dec->history_buf + roff;
comp_stream->p = comp_stream->data;
comp_stream->size = rlen;
}
else
{
printf("decompress_rdp() failed\n");
return -1;
}
stream_seek(s, compressed_len - 18);
}
#ifdef WITH_DEBUG_RDP
/* if (type != DATA_PDU_TYPE_UPDATE) */
DEBUG_RDP("recv %s Data PDU (0x%02X), length:%d",
type < ARRAYSIZE(DATA_PDU_TYPE_STRINGS) ? DATA_PDU_TYPE_STRINGS[type] : "???", type, length);
#endif
switch (type)
{
case DATA_PDU_TYPE_UPDATE:
if (!update_recv(rdp->update, comp_stream))
return -1;
break;
case DATA_PDU_TYPE_CONTROL:
if (!rdp_recv_server_control_pdu(rdp, comp_stream))
return -1;
break;
case DATA_PDU_TYPE_POINTER:
if (!update_recv_pointer(rdp->update, comp_stream))
return -1;
break;
case DATA_PDU_TYPE_INPUT:
break;
case DATA_PDU_TYPE_SYNCHRONIZE:
if (!rdp_recv_synchronize_pdu(rdp, comp_stream))
return -1;
break;
case DATA_PDU_TYPE_REFRESH_RECT:
break;
case DATA_PDU_TYPE_PLAY_SOUND:
if (!update_recv_play_sound(rdp->update, comp_stream))
return -1;
break;
case DATA_PDU_TYPE_SUPPRESS_OUTPUT:
break;
case DATA_PDU_TYPE_SHUTDOWN_REQUEST:
break;
case DATA_PDU_TYPE_SHUTDOWN_DENIED:
break;
case DATA_PDU_TYPE_SAVE_SESSION_INFO:
if(!rdp_recv_save_session_info(rdp, comp_stream))
return -1;
break;
case DATA_PDU_TYPE_FONT_LIST:
break;
case DATA_PDU_TYPE_FONT_MAP:
if(!rdp_recv_font_map_pdu(rdp, comp_stream))
return -1;
break;
case DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS:
break;
case DATA_PDU_TYPE_BITMAP_CACHE_PERSISTENT_LIST:
break;
case DATA_PDU_TYPE_BITMAP_CACHE_ERROR:
break;
case DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS:
break;
case DATA_PDU_TYPE_OFFSCREEN_CACHE_ERROR:
break;
case DATA_PDU_TYPE_SET_ERROR_INFO:
if (!rdp_recv_set_error_info_data_pdu(rdp, comp_stream))
return -1;
break;
case DATA_PDU_TYPE_DRAW_NINEGRID_ERROR:
break;
case DATA_PDU_TYPE_DRAW_GDIPLUS_ERROR:
break;
case DATA_PDU_TYPE_ARC_STATUS:
break;
case DATA_PDU_TYPE_STATUS_INFO:
break;
case DATA_PDU_TYPE_MONITOR_LAYOUT:
break;
default:
break;
}
if (comp_stream != s)
{
stream_detach(comp_stream);
stream_free(comp_stream);
}
return 0;
}
BOOL rdp_recv_out_of_sequence_pdu(rdpRdp* rdp, STREAM* s)
{
UINT16 type;
UINT16 length;
UINT16 channelId;
if (!rdp_read_share_control_header(s, &length, &type, &channelId))
return FALSE;
if (type == PDU_TYPE_DATA)
{
return (rdp_recv_data_pdu(rdp, s) < 0) ? FALSE : TRUE;
}
else if (type == PDU_TYPE_SERVER_REDIRECTION)
{
return rdp_recv_enhanced_security_redirection_packet(rdp, s);
}
else
{
return FALSE;
}
}
/**
* Decrypt an RDP packet.\n
* @param rdp RDP module
* @param s stream
* @param length int
*/
BOOL rdp_decrypt(rdpRdp* rdp, STREAM* s, int length, UINT16 securityFlags)
{
BYTE cmac[8];
BYTE wmac[8];
if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
{
UINT16 len;
BYTE version, pad;
BYTE* sig;
if (stream_get_left(s) < 12)
return FALSE;
stream_read_UINT16(s, len); /* 0x10 */
stream_read_BYTE(s, version); /* 0x1 */
stream_read_BYTE(s, pad);
sig = s->p;
stream_seek(s, 8); /* signature */
length -= 12;
if (!security_fips_decrypt(s->p, length, rdp))
{
printf("FATAL: cannot decrypt\n");
return FALSE; /* TODO */
}
if (!security_fips_check_signature(s->p, length - pad, sig, rdp))
{
printf("FATAL: invalid packet signature\n");
return FALSE; /* TODO */
}
/* is this what needs adjusting? */
s->size -= pad;
return TRUE;
}
if (stream_get_left(s) < 8)
return FALSE;
stream_read(s, wmac, sizeof(wmac));
length -= sizeof(wmac);
if (!security_decrypt(s->p, length, rdp))
return FALSE;
if (securityFlags & SEC_SECURE_CHECKSUM)
security_salted_mac_signature(rdp, s->p, length, FALSE, cmac);
else
security_mac_signature(rdp, s->p, length, cmac);
if (memcmp(wmac, cmac, sizeof(wmac)) != 0)
{
printf("WARNING: invalid packet signature\n");
/*
* Because Standard RDP Security is totally broken,
* and cannot protect against MITM, don't treat signature
* verification failure as critical. This at least enables
* us to work with broken RDP clients and servers that
* generate invalid signatures.
*/
//return FALSE;
}
return TRUE;
}
/**
* Process an RDP packet.\n
* @param rdp RDP module
* @param s stream
*/
static int rdp_recv_tpkt_pdu(rdpRdp* rdp, STREAM* s)
{
UINT16 length;
UINT16 pduType;
UINT16 pduLength;
UINT16 pduSource;
UINT16 channelId;
UINT16 securityFlags;
BYTE* nextp;
if (!rdp_read_header(rdp, s, &length, &channelId))
{
printf("Incorrect RDP header.\n");
return -1;
}
if (rdp->settings->DisableEncryption)
{
if (!rdp_read_security_header(s, &securityFlags))
return -1;
if (securityFlags & (SEC_ENCRYPT | SEC_REDIRECTION_PKT))
{
if (!rdp_decrypt(rdp, s, length - 4, securityFlags))
{
printf("rdp_decrypt failed\n");
return -1;
}
}
if (securityFlags & SEC_REDIRECTION_PKT)
{
/*
* [MS-RDPBCGR] 2.2.13.2.1
* - no share control header, nor the 2 byte pad
*/
s->p -= 2;
rdp_recv_enhanced_security_redirection_packet(rdp, s);
return -1;
}
}
if (channelId != MCS_GLOBAL_CHANNEL_ID)
{
if (!freerdp_channel_process(rdp->instance, s, channelId))
return -1;
}
else
{
while (stream_get_left(s) > 3)
{
stream_get_mark(s, nextp);
if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource))
return -1;
nextp += pduLength;
rdp->settings->PduSource = pduSource;
switch (pduType)
{
case PDU_TYPE_DATA:
if (rdp_recv_data_pdu(rdp, s) < 0)
{
printf("rdp_recv_data_pdu failed\n");
return -1;
}
break;
case PDU_TYPE_DEACTIVATE_ALL:
if (!rdp_recv_deactivate_all(rdp, s))
return -1;
break;
case PDU_TYPE_SERVER_REDIRECTION:
if (!rdp_recv_enhanced_security_redirection_packet(rdp, s))
return -1;
break;
default:
printf("incorrect PDU type: 0x%04X\n", pduType);
break;
}
stream_set_mark(s, nextp);
}
}
return 0;
}
static int rdp_recv_fastpath_pdu(rdpRdp* rdp, STREAM* s)
{
UINT16 length;
rdpFastPath* fastpath;
fastpath = rdp->fastpath;
if (!fastpath_read_header_rdp(fastpath, s, &length))
return -1;
if ((length == 0) || (length > stream_get_left(s)))
{
printf("incorrect FastPath PDU header length %d\n", length);
return -1;
}
if (fastpath->encryptionFlags & FASTPATH_OUTPUT_ENCRYPTED)
{
UINT16 flags = (fastpath->encryptionFlags & FASTPATH_OUTPUT_SECURE_CHECKSUM) ? SEC_SECURE_CHECKSUM : 0;
if (!rdp_decrypt(rdp, s, length, flags))
return -1;
}
return fastpath_recv_updates(rdp->fastpath, s);
}
static int rdp_recv_pdu(rdpRdp* rdp, STREAM* s)
{
if (tpkt_verify_header(s))
return rdp_recv_tpkt_pdu(rdp, s);
else
return rdp_recv_fastpath_pdu(rdp, s);
}
/**
* Receive an RDP packet.\n
* @param rdp RDP module
*/
void rdp_recv(rdpRdp* rdp)
{
STREAM* s;
s = transport_recv_stream_init(rdp->transport, 4096);
transport_read(rdp->transport, s);
rdp_recv_pdu(rdp, s);
}
static int rdp_recv_callback(rdpTransport* transport, STREAM* s, void* extra)
{
int status = 0;
rdpRdp* rdp = (rdpRdp*) extra;
switch (rdp->state)
{
case CONNECTION_STATE_NEGO:
if (!rdp_client_connect_mcs_connect_response(rdp, s))
status = -1;
break;
case CONNECTION_STATE_MCS_ATTACH_USER:
if (!rdp_client_connect_mcs_attach_user_confirm(rdp, s))
status = -1;
break;
case CONNECTION_STATE_MCS_CHANNEL_JOIN:
if (!rdp_client_connect_mcs_channel_join_confirm(rdp, s))
status = -1;
break;
case CONNECTION_STATE_LICENSE:
if (!rdp_client_connect_license(rdp, s))
status = -1;
break;
case CONNECTION_STATE_CAPABILITY:
if (!rdp_client_connect_demand_active(rdp, s))
status = -1;
break;
case CONNECTION_STATE_FINALIZATION:
status = rdp_recv_pdu(rdp, s);
if ((status >= 0) && (rdp->finalize_sc_pdus == FINALIZE_SC_COMPLETE))
rdp->state = CONNECTION_STATE_ACTIVE;
break;
case CONNECTION_STATE_ACTIVE:
status = rdp_recv_pdu(rdp, s);
break;
default:
printf("Invalid state %d\n", rdp->state);
status = -1;
break;
}
return status;
}
int rdp_send_channel_data(rdpRdp* rdp, int channel_id, BYTE* data, int size)
{
return freerdp_channel_send(rdp, channel_id, data, size);
}
/**
* Set non-blocking mode information.
* @param rdp RDP module
* @param blocking blocking mode
*/
void rdp_set_blocking_mode(rdpRdp* rdp, BOOL blocking)
{
rdp->transport->ReceiveCallback = rdp_recv_callback;
rdp->transport->ReceiveExtra = rdp;
transport_set_blocking_mode(rdp->transport, blocking);
}
int rdp_check_fds(rdpRdp* rdp)
{
return transport_check_fds(&(rdp->transport));
}
/**
* Instantiate new RDP module.
* @return new RDP module
*/
rdpRdp* rdp_new(freerdp* instance)
{
rdpRdp* rdp;
rdp = (rdpRdp*) malloc(sizeof(rdpRdp));
if (rdp != NULL)
{
ZeroMemory(rdp, sizeof(rdpRdp));
rdp->instance = instance;
rdp->settings = freerdp_settings_new((void*) instance);
if (instance != NULL)
instance->settings = rdp->settings;
rdp->extension = extension_new(instance);
rdp->transport = transport_new(rdp->settings);
rdp->license = license_new(rdp);
rdp->input = input_new(rdp);
rdp->update = update_new(rdp);
rdp->fastpath = fastpath_new(rdp);
rdp->nego = nego_new(rdp->transport);
rdp->mcs = mcs_new(rdp->transport);
rdp->redirection = redirection_new();
rdp->mppc_dec = mppc_dec_new();
rdp->mppc_enc = mppc_enc_new(PROTO_RDP_50);
}
return rdp;
}
/**
* Free RDP module.
* @param rdp RDP module to be freed
*/
void rdp_free(rdpRdp* rdp)
{
if (rdp != NULL)
{
crypto_rc4_free(rdp->rc4_decrypt_key);
crypto_rc4_free(rdp->rc4_encrypt_key);
crypto_des3_free(rdp->fips_encrypt);
crypto_des3_free(rdp->fips_decrypt);
crypto_hmac_free(rdp->fips_hmac);
freerdp_settings_free(rdp->settings);
extension_free(rdp->extension);
transport_free(rdp->transport);
license_free(rdp->license);
input_free(rdp->input);
update_free(rdp->update);
fastpath_free(rdp->fastpath);
nego_free(rdp->nego);
mcs_free(rdp->mcs);
redirection_free(rdp->redirection);
mppc_dec_free(rdp->mppc_dec);
mppc_enc_free(rdp->mppc_enc);
free(rdp);
}
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5714_0 |
crossvul-cpp_data_good_5370_0 | /*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2002 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__
*/
/*
* Sequence/Matrix Library
*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "jasper/jas_seq.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_math.h"
/******************************************************************************\
* Constructors and destructors.
\******************************************************************************/
jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend)
{
jas_matrix_t *matrix;
assert(xstart <= xend && ystart <= yend);
if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) {
return 0;
}
matrix->xstart_ = xstart;
matrix->ystart_ = ystart;
matrix->xend_ = xend;
matrix->yend_ = yend;
return matrix;
}
jas_matrix_t *jas_matrix_create(int numrows, int numcols)
{
jas_matrix_t *matrix;
int i;
if (numrows < 0 || numcols < 0) {
return 0;
}
if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
return 0;
}
matrix->flags_ = 0;
matrix->numrows_ = numrows;
matrix->numcols_ = numcols;
matrix->rows_ = 0;
matrix->maxrows_ = numrows;
matrix->data_ = 0;
matrix->datasize_ = numrows * numcols;
if (matrix->maxrows_ > 0) {
if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,
sizeof(jas_seqent_t *)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
if (matrix->datasize_ > 0) {
if (!(matrix->data_ = jas_alloc2(matrix->datasize_,
sizeof(jas_seqent_t)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
for (i = 0; i < numrows; ++i) {
matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
}
for (i = 0; i < matrix->datasize_; ++i) {
matrix->data_[i] = 0;
}
matrix->xstart_ = 0;
matrix->ystart_ = 0;
matrix->xend_ = matrix->numcols_;
matrix->yend_ = matrix->numrows_;
return matrix;
}
void jas_matrix_destroy(jas_matrix_t *matrix)
{
if (matrix->data_) {
assert(!(matrix->flags_ & JAS_MATRIX_REF));
jas_free(matrix->data_);
matrix->data_ = 0;
}
if (matrix->rows_) {
jas_free(matrix->rows_);
matrix->rows_ = 0;
}
jas_free(matrix);
}
jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)
{
jas_matrix_t *y;
int i;
int j;
y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x),
jas_seq2d_yend(x));
assert(y);
for (i = 0; i < x->numrows_; ++i) {
for (j = 0; j < x->numcols_; ++j) {
*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
}
}
return y;
}
jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)
{
jas_matrix_t *y;
int i;
int j;
y = jas_matrix_create(x->numrows_, x->numcols_);
for (i = 0; i < x->numrows_; ++i) {
for (j = 0; j < x->numcols_; ++j) {
*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
}
}
return y;
}
/******************************************************************************\
* Bind operations.
\******************************************************************************/
void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart, int ystart,
int xend, int yend)
{
jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_,
yend - s1->ystart_ - 1, xend - s1->xstart_ - 1);
}
void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0,
int r1, int c1)
{
int i;
if (mat0->data_) {
if (!(mat0->flags_ & JAS_MATRIX_REF)) {
jas_free(mat0->data_);
}
mat0->data_ = 0;
mat0->datasize_ = 0;
}
if (mat0->rows_) {
jas_free(mat0->rows_);
mat0->rows_ = 0;
}
mat0->flags_ |= JAS_MATRIX_REF;
mat0->numrows_ = r1 - r0 + 1;
mat0->numcols_ = c1 - c0 + 1;
mat0->maxrows_ = mat0->numrows_;
if (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) {
/*
There is no way to indicate failure to the caller.
So, we have no choice but to abort.
Ideally, this function should have a non-void return type.
In practice, a non-void return type probably would not help
much anyways as the caller would just have to terminate anyways.
*/
abort();
}
for (i = 0; i < mat0->numrows_; ++i) {
mat0->rows_[i] = mat1->rows_[r0 + i] + c0;
}
mat0->xstart_ = mat1->xstart_ + c0;
mat0->ystart_ = mat1->ystart_ + r0;
mat0->xend_ = mat0->xstart_ + mat0->numcols_;
mat0->yend_ = mat0->ystart_ + mat0->numrows_;
}
/******************************************************************************\
* Arithmetic operations.
\******************************************************************************/
int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1)
{
int i;
int j;
if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=
mat1->numcols_) {
return 1;
}
for (i = 0; i < mat0->numrows_; i++) {
for (j = 0; j < mat0->numcols_; j++) {
if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {
return 1;
}
}
}
return 0;
}
void jas_matrix_divpow2(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = (*data >= 0) ? ((*data) >> n) :
(-((-(*data)) >> n));
}
}
}
}
void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval, jas_seqent_t maxval)
{
int i;
int j;
jas_seqent_t v;
jas_seqent_t *rowstart;
jas_seqent_t *data;
int rowstep;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
data = rowstart;
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
v = *data;
if (v < minval) {
*data = minval;
} else if (v > maxval) {
*data = maxval;
}
}
}
}
}
void jas_matrix_asr(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
assert(n >= 0);
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
//*data >>= n;
*data = jas_seqent_asr(*data, n);
}
}
}
}
void jas_matrix_asl(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
//*data <<= n;
*data = jas_seqent_asl(*data, n);
}
}
}
}
/******************************************************************************\
* Code.
\******************************************************************************/
int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols)
{
int size;
int i;
size = numrows * numcols;
if (size > matrix->datasize_ || numrows > matrix->maxrows_) {
return -1;
}
matrix->numrows_ = numrows;
matrix->numcols_ = numcols;
for (i = 0; i < numrows; ++i) {
matrix->rows_[i] = &matrix->data_[numcols * i];
}
return 0;
}
void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = val;
}
}
}
}
jas_matrix_t *jas_seq2d_input(FILE *in)
{
jas_matrix_t *matrix;
int i;
int j;
long x;
int numrows;
int numcols;
int xoff;
int yoff;
if (fscanf(in, "%d %d", &xoff, &yoff) != 2)
return 0;
if (fscanf(in, "%d %d", &numcols, &numrows) != 2)
return 0;
if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows)))
return 0;
if (jas_matrix_numrows(matrix) != numrows || jas_matrix_numcols(matrix) != numcols) {
abort();
}
/* Get matrix data. */
for (i = 0; i < jas_matrix_numrows(matrix); i++) {
for (j = 0; j < jas_matrix_numcols(matrix); j++) {
if (fscanf(in, "%ld", &x) != 1) {
jas_matrix_destroy(matrix);
return 0;
}
jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x));
}
}
return matrix;
}
int jas_seq2d_output(jas_matrix_t *matrix, FILE *out)
{
#define MAXLINELEN 80
int i;
int j;
jas_seqent_t x;
char buf[MAXLINELEN + 1];
char sbuf[MAXLINELEN + 1];
int n;
fprintf(out, "%d %d\n", jas_seq2d_xstart(matrix),
jas_seq2d_ystart(matrix));
fprintf(out, "%d %d\n", jas_matrix_numcols(matrix),
jas_matrix_numrows(matrix));
buf[0] = '\0';
for (i = 0; i < jas_matrix_numrows(matrix); ++i) {
for (j = 0; j < jas_matrix_numcols(matrix); ++j) {
x = jas_matrix_get(matrix, i, j);
sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "",
JAS_CAST(long, x));
n = strlen(buf);
if (n + strlen(sbuf) > MAXLINELEN) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
strcat(buf, sbuf);
if (j == jas_matrix_numcols(matrix) - 1) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
}
}
fputs(buf, out);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5370_0 |
crossvul-cpp_data_good_576_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 1993 OpenVision Technologies, Inc., All Rights Reserved
*
* $Header$
*/
#include "k5-int.h"
#include <sys/time.h>
#include <kadm5/admin.h>
#include <kdb.h>
#include "server_internal.h"
#ifdef USE_PASSWORD_SERVER
#include <sys/wait.h>
#include <signal.h>
#endif
#include <krb5/kadm5_hook_plugin.h>
#ifdef USE_VALGRIND
#include <valgrind/memcheck.h>
#else
#define VALGRIND_CHECK_DEFINED(LVALUE) ((void)0)
#endif
extern krb5_principal master_princ;
extern krb5_principal hist_princ;
extern krb5_keyblock master_keyblock;
extern krb5_db_entry master_db;
static int decrypt_key_data(krb5_context context,
int n_key_data, krb5_key_data *key_data,
krb5_keyblock **keyblocks, int *n_keys);
/*
* XXX Functions that ought to be in libkrb5.a, but aren't.
*/
kadm5_ret_t krb5_copy_key_data_contents(context, from, to)
krb5_context context;
krb5_key_data *from, *to;
{
int i, idx;
*to = *from;
idx = (from->key_data_ver == 1 ? 1 : 2);
for (i = 0; i < idx; i++) {
if ( from->key_data_length[i] ) {
to->key_data_contents[i] = malloc(from->key_data_length[i]);
if (to->key_data_contents[i] == NULL) {
for (i = 0; i < idx; i++)
zapfree(to->key_data_contents[i], to->key_data_length[i]);
return ENOMEM;
}
memcpy(to->key_data_contents[i], from->key_data_contents[i],
from->key_data_length[i]);
}
}
return 0;
}
static krb5_tl_data *dup_tl_data(krb5_tl_data *tl)
{
krb5_tl_data *n;
n = (krb5_tl_data *) malloc(sizeof(krb5_tl_data));
if (n == NULL)
return NULL;
n->tl_data_contents = malloc(tl->tl_data_length);
if (n->tl_data_contents == NULL) {
free(n);
return NULL;
}
memcpy(n->tl_data_contents, tl->tl_data_contents, tl->tl_data_length);
n->tl_data_type = tl->tl_data_type;
n->tl_data_length = tl->tl_data_length;
n->tl_data_next = NULL;
return n;
}
/* This is in lib/kdb/kdb_cpw.c, but is static */
static void cleanup_key_data(context, count, data)
krb5_context context;
int count;
krb5_key_data * data;
{
int i;
for (i = 0; i < count; i++)
krb5_free_key_data_contents(context, &data[i]);
free(data);
}
/* Check whether a ks_tuple is present in an array of ks_tuples. */
static krb5_boolean
ks_tuple_present(int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_key_salt_tuple *looking_for)
{
int i;
for (i = 0; i < n_ks_tuple; i++) {
if (ks_tuple[i].ks_enctype == looking_for->ks_enctype &&
ks_tuple[i].ks_salttype == looking_for->ks_salttype)
return TRUE;
}
return FALSE;
}
/* Fetch a policy if it exists; set *have_pol_out appropriately. Return
* success whether or not the policy exists. */
static kadm5_ret_t
get_policy(kadm5_server_handle_t handle, const char *name,
kadm5_policy_ent_t policy_out, krb5_boolean *have_pol_out)
{
kadm5_ret_t ret;
*have_pol_out = FALSE;
if (name == NULL)
return 0;
ret = kadm5_get_policy(handle->lhandle, (char *)name, policy_out);
if (ret == 0)
*have_pol_out = TRUE;
return (ret == KADM5_UNK_POLICY) ? 0 : ret;
}
/*
* Apply the -allowedkeysalts policy (see kadmin(1)'s addpol/modpol
* commands). We use the allowed key/salt tuple list as a default if
* no ks tuples as provided by the caller. We reject lists that include
* key/salts outside the policy. We re-order the requested ks tuples
* (which may be a subset of the policy) to reflect the policy order.
*/
static kadm5_ret_t
apply_keysalt_policy(kadm5_server_handle_t handle, const char *policy,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
int *new_n_kstp, krb5_key_salt_tuple **new_kstp)
{
kadm5_ret_t ret;
kadm5_policy_ent_rec polent;
krb5_boolean have_polent;
int ak_n_ks_tuple = 0;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *ak_ks_tuple = NULL;
krb5_key_salt_tuple *new_ks_tuple = NULL;
krb5_key_salt_tuple *subset;
int i, m;
if (new_n_kstp != NULL) {
*new_n_kstp = 0;
*new_kstp = NULL;
}
memset(&polent, 0, sizeof(polent));
ret = get_policy(handle, policy, &polent, &have_polent);
if (ret)
goto cleanup;
if (polent.allowed_keysalts == NULL) {
/* Requested keysalts allowed or default to supported_enctypes. */
if (n_ks_tuple == 0) {
/* Default to supported_enctypes. */
n_ks_tuple = handle->params.num_keysalts;
ks_tuple = handle->params.keysalts;
}
/* Dup the requested or defaulted keysalt tuples. */
new_ks_tuple = malloc(n_ks_tuple * sizeof(*new_ks_tuple));
if (new_ks_tuple == NULL) {
ret = ENOMEM;
goto cleanup;
}
memcpy(new_ks_tuple, ks_tuple, n_ks_tuple * sizeof(*new_ks_tuple));
new_n_ks_tuple = n_ks_tuple;
ret = 0;
goto cleanup;
}
ret = krb5_string_to_keysalts(polent.allowed_keysalts,
",", /* Tuple separators */
NULL, /* Key/salt separators */
0, /* No duplicates */
&ak_ks_tuple,
&ak_n_ks_tuple);
/*
* Malformed policy? Shouldn't happen, but it's remotely possible
* someday, so we don't assert, just bail.
*/
if (ret)
goto cleanup;
/* Check that the requested ks_tuples are within policy, if we have one. */
for (i = 0; i < n_ks_tuple; i++) {
if (!ks_tuple_present(ak_n_ks_tuple, ak_ks_tuple, &ks_tuple[i])) {
ret = KADM5_BAD_KEYSALTS;
goto cleanup;
}
}
/* Have policy but no ks_tuple input? Output the policy. */
if (n_ks_tuple == 0) {
new_n_ks_tuple = ak_n_ks_tuple;
new_ks_tuple = ak_ks_tuple;
ak_ks_tuple = NULL;
goto cleanup;
}
/*
* Now filter the policy ks tuples by the requested ones so as to
* preserve in the requested sub-set the relative ordering from the
* policy. We could optimize this (if (n_ks_tuple == ak_n_ks_tuple)
* then skip this), but we don't bother.
*/
subset = calloc(n_ks_tuple, sizeof(*subset));
if (subset == NULL) {
ret = ENOMEM;
goto cleanup;
}
for (m = 0, i = 0; i < ak_n_ks_tuple && m < n_ks_tuple; i++) {
if (ks_tuple_present(n_ks_tuple, ks_tuple, &ak_ks_tuple[i]))
subset[m++] = ak_ks_tuple[i];
}
new_ks_tuple = subset;
new_n_ks_tuple = m;
ret = 0;
cleanup:
if (have_polent)
kadm5_free_policy_ent(handle->lhandle, &polent);
free(ak_ks_tuple);
if (new_n_kstp != NULL) {
*new_n_kstp = new_n_ks_tuple;
*new_kstp = new_ks_tuple;
} else {
free(new_ks_tuple);
}
return ret;
}
/*
* Set *passptr to NULL if the request looks like the first part of a krb5 1.6
* addprinc -randkey operation. The krb5 1.6 dummy password for these requests
* was invalid UTF-8, which runs afoul of the arcfour string-to-key.
*/
static void
check_1_6_dummy(kadm5_principal_ent_t entry, long mask,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr)
{
int i;
char *password = *passptr;
/* Old-style randkey operations disallowed tickets to start. */
if (password == NULL || !(mask & KADM5_ATTRIBUTES) ||
!(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX))
return;
/* The 1.6 dummy password was the octets 1..255. */
for (i = 0; (unsigned char) password[i] == i + 1; i++);
if (password[i] != '\0' || i != 255)
return;
/* This will make the caller use a random password instead. */
*passptr = NULL;
}
/* Return the number of keys with the newest kvno. Assumes that all key data
* with the newest kvno are at the front of the key data array. */
static int
count_new_keys(int n_key_data, krb5_key_data *key_data)
{
int n;
for (n = 1; n < n_key_data; n++) {
if (key_data[n - 1].key_data_kvno != key_data[n].key_data_kvno)
return n;
}
return n_key_data;
}
kadm5_ret_t
kadm5_create_principal(void *server_handle,
kadm5_principal_ent_t entry, long mask,
char *password)
{
return
kadm5_create_principal_3(server_handle, entry, mask,
0, NULL, password);
}
kadm5_ret_t
kadm5_create_principal_3(void *server_handle,
kadm5_principal_ent_t entry, long mask,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
char *password)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
kadm5_policy_ent_rec polent;
krb5_boolean have_polent = FALSE;
krb5_timestamp now;
krb5_tl_data *tl_data_tail;
unsigned int ret;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_kvno act_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password);
/*
* Argument sanity checking, and opening up the DB
*/
if (entry == NULL)
return EINVAL;
if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) ||
(mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) ||
(mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) ||
(mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) ||
(mask & KADM5_FAIL_AUTH_COUNT))
return KADM5_BAD_MASK;
if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0)
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && entry->policy == NULL)
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR))
return KADM5_BAD_MASK;
if((mask & ~ALL_PRINC_MASK))
return KADM5_BAD_MASK;
if (mask & KADM5_TL_DATA) {
for (tl_data_tail = entry->tl_data; tl_data_tail != NULL;
tl_data_tail = tl_data_tail->tl_data_next) {
if (tl_data_tail->tl_data_type < 256)
return KADM5_BAD_TL_TYPE;
}
}
/*
* Check to see if the principal exists
*/
ret = kdb_get_entry(handle, entry->principal, &kdb, &adb);
switch(ret) {
case KADM5_UNK_PRINC:
break;
case 0:
kdb_free_entry(handle, kdb, &adb);
return KADM5_DUP;
default:
return ret;
}
kdb = calloc(1, sizeof(*kdb));
if (kdb == NULL)
return ENOMEM;
memset(&adb, 0, sizeof(osa_princ_ent_rec));
/*
* If a policy was specified, load it.
* If we can not find the one specified return an error
*/
if ((mask & KADM5_POLICY)) {
ret = get_policy(handle, entry->policy, &polent, &have_polent);
if (ret)
goto cleanup;
}
if (password) {
ret = passwd_check(handle, password, have_polent ? &polent : NULL,
entry->principal);
if (ret)
goto cleanup;
}
/*
* Start populating the various DB fields, using the
* "defaults" for fields that were not specified by the
* mask.
*/
if ((ret = krb5_timeofday(handle->context, &now)))
goto cleanup;
kdb->magic = KRB5_KDB_MAGIC_NUMBER;
kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */
if ((mask & KADM5_ATTRIBUTES))
kdb->attributes = entry->attributes;
else
kdb->attributes = handle->params.flags;
if ((mask & KADM5_MAX_LIFE))
kdb->max_life = entry->max_life;
else
kdb->max_life = handle->params.max_life;
if (mask & KADM5_MAX_RLIFE)
kdb->max_renewable_life = entry->max_renewable_life;
else
kdb->max_renewable_life = handle->params.max_rlife;
if ((mask & KADM5_PRINC_EXPIRE_TIME))
kdb->expiration = entry->princ_expire_time;
else
kdb->expiration = handle->params.expiration;
kdb->pw_expiration = 0;
if (have_polent) {
if(polent.pw_max_life)
kdb->pw_expiration = ts_incr(now, polent.pw_max_life);
else
kdb->pw_expiration = 0;
}
if ((mask & KADM5_PW_EXPIRATION))
kdb->pw_expiration = entry->pw_expiration;
kdb->last_success = 0;
kdb->last_failed = 0;
kdb->fail_auth_count = 0;
/* this is kind of gross, but in order to free the tl data, I need
to free the entire kdb entry, and that will try to free the
principal. */
ret = krb5_copy_principal(handle->context, entry->principal, &kdb->princ);
if (ret)
goto cleanup;
if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now)))
goto cleanup;
if (mask & KADM5_TL_DATA) {
/* splice entry->tl_data onto the front of kdb->tl_data */
for (tl_data_tail = entry->tl_data; tl_data_tail;
tl_data_tail = tl_data_tail->tl_data_next)
{
ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail);
if( ret )
goto cleanup;
}
}
/*
* We need to have setup the TL data, so we have strings, so we can
* check enctype policy, which is why we check/initialize ks_tuple
* this late.
*/
ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto cleanup;
/* initialize the keys */
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto cleanup;
if (mask & KADM5_KEY_DATA) {
/* The client requested no keys for this principal. */
assert(entry->n_key_data == 0);
} else if (password) {
ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple,
new_n_ks_tuple, password,
(mask & KADM5_KVNO)?entry->kvno:1,
FALSE, kdb);
} else {
/* Null password means create with random key (new in 1.8). */
ret = krb5_dbe_crk(handle->context, &master_keyblock,
new_ks_tuple, new_n_ks_tuple, FALSE, kdb);
}
if (ret)
goto cleanup;
/* Record the master key VNO used to encrypt this entry's keys */
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto cleanup;
ret = k5_kadm5_hook_create(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, entry, mask,
new_n_ks_tuple, new_ks_tuple, password);
if (ret)
goto cleanup;
/* populate the admin-server-specific fields. In the OV server,
this used to be in a separate database. Since there's already
marshalling code for the admin fields, to keep things simple,
I'm going to keep it, and make all the admin stuff occupy a
single tl_data record, */
adb.admin_history_kvno = INITIAL_HIST_KVNO;
if (mask & KADM5_POLICY) {
adb.aux_attributes = KADM5_POLICY;
/* this does *not* need to be strdup'ed, because adb is xdr */
/* encoded in osa_adb_create_princ, and not ever freed */
adb.policy = entry->policy;
}
/* In all cases key and the principal data is set, let the database provider know */
kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ;
/* store the new db entry */
ret = kdb_put_entry(handle, kdb, &adb);
(void) k5_kadm5_hook_create(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask,
new_n_ks_tuple, new_ks_tuple, password);
cleanup:
free(new_ks_tuple);
krb5_db_free_principal(handle->context, kdb);
if (have_polent)
(void) kadm5_free_policy_ent(handle->lhandle, &polent);
return ret;
}
kadm5_ret_t
kadm5_delete_principal(void *server_handle, krb5_principal principal)
{
unsigned int ret;
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = k5_kadm5_hook_remove(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal);
if (ret) {
kdb_free_entry(handle, kdb, &adb);
return ret;
}
ret = kdb_delete_entry(handle, principal);
kdb_free_entry(handle, kdb, &adb);
if (ret == 0)
(void) k5_kadm5_hook_remove(handle->context,
handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal);
return ret;
}
kadm5_ret_t
kadm5_modify_principal(void *server_handle,
kadm5_principal_ent_t entry, long mask)
{
int ret, ret2, i;
kadm5_policy_ent_rec pol;
krb5_boolean have_pol = FALSE;
krb5_db_entry *kdb;
krb5_tl_data *tl_data_orig;
osa_princ_ent_rec adb;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if(entry == NULL)
return EINVAL;
if((mask & KADM5_PRINCIPAL) || (mask & KADM5_LAST_PWD_CHANGE) ||
(mask & KADM5_MOD_TIME) || (mask & KADM5_MOD_NAME) ||
(mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) ||
(mask & KADM5_KEY_DATA) || (mask & KADM5_LAST_SUCCESS) ||
(mask & KADM5_LAST_FAILED))
return KADM5_BAD_MASK;
if((mask & ~ALL_PRINC_MASK))
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && entry->policy == NULL)
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR))
return KADM5_BAD_MASK;
if (mask & KADM5_TL_DATA) {
tl_data_orig = entry->tl_data;
while (tl_data_orig) {
if (tl_data_orig->tl_data_type < 256)
return KADM5_BAD_TL_TYPE;
tl_data_orig = tl_data_orig->tl_data_next;
}
}
ret = kdb_get_entry(handle, entry->principal, &kdb, &adb);
if (ret)
return(ret);
/*
* This is pretty much the same as create ...
*/
if ((mask & KADM5_POLICY)) {
ret = get_policy(handle, entry->policy, &pol, &have_pol);
if (ret)
goto done;
/* set us up to use the new policy */
adb.aux_attributes |= KADM5_POLICY;
if (adb.policy)
free(adb.policy);
adb.policy = strdup(entry->policy);
}
if (have_pol) {
/* set pw_max_life based on new policy */
if (pol.pw_max_life) {
ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb,
&(kdb->pw_expiration));
if (ret)
goto done;
kdb->pw_expiration = ts_incr(kdb->pw_expiration, pol.pw_max_life);
} else {
kdb->pw_expiration = 0;
}
}
if ((mask & KADM5_POLICY_CLR) && (adb.aux_attributes & KADM5_POLICY)) {
free(adb.policy);
adb.policy = NULL;
adb.aux_attributes &= ~KADM5_POLICY;
kdb->pw_expiration = 0;
}
if ((mask & KADM5_ATTRIBUTES))
kdb->attributes = entry->attributes;
if ((mask & KADM5_MAX_LIFE))
kdb->max_life = entry->max_life;
if ((mask & KADM5_PRINC_EXPIRE_TIME))
kdb->expiration = entry->princ_expire_time;
if (mask & KADM5_PW_EXPIRATION)
kdb->pw_expiration = entry->pw_expiration;
if (mask & KADM5_MAX_RLIFE)
kdb->max_renewable_life = entry->max_renewable_life;
if((mask & KADM5_KVNO)) {
for (i = 0; i < kdb->n_key_data; i++)
kdb->key_data[i].key_data_kvno = entry->kvno;
}
if (mask & KADM5_TL_DATA) {
krb5_tl_data *tl;
/* may have to change the version number of the API. Updates the list with the given tl_data rather than over-writting */
for (tl = entry->tl_data; tl;
tl = tl->tl_data_next)
{
ret = krb5_dbe_update_tl_data(handle->context, kdb, tl);
if( ret )
{
goto done;
}
}
}
/*
* Setting entry->fail_auth_count to 0 can be used to manually unlock
* an account. It is not possible to set fail_auth_count to any other
* value using kadmin.
*/
if (mask & KADM5_FAIL_AUTH_COUNT) {
if (entry->fail_auth_count != 0) {
ret = KADM5_BAD_SERVER_PARAMS;
goto done;
}
kdb->fail_auth_count = 0;
}
/* let the mask propagate to the database provider */
kdb->mask = mask;
ret = k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, entry, mask);
if (ret)
goto done;
ret = kdb_put_entry(handle, kdb, &adb);
if (ret) goto done;
(void) k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask);
ret = KADM5_OK;
done:
if (have_pol) {
ret2 = kadm5_free_policy_ent(handle->lhandle, &pol);
ret = ret ? ret : ret2;
}
kdb_free_entry(handle, kdb, &adb);
return ret;
}
kadm5_ret_t
kadm5_rename_principal(void *server_handle,
krb5_principal source, krb5_principal target)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_error_code ret;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (source == NULL || target == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, target, &kdb, &adb)) == 0) {
kdb_free_entry(handle, kdb, &adb);
return(KADM5_DUP);
}
ret = k5_kadm5_hook_rename(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, source, target);
if (ret)
return ret;
ret = krb5_db_rename_principal(handle->context, source, target);
if (ret)
return ret;
/* Update the principal mod data. */
ret = kdb_get_entry(handle, target, &kdb, &adb);
if (ret)
return ret;
kdb->mask = 0;
ret = kdb_put_entry(handle, kdb, &adb);
kdb_free_entry(handle, kdb, &adb);
if (ret)
return ret;
(void) k5_kadm5_hook_rename(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, source, target);
return 0;
}
kadm5_ret_t
kadm5_get_principal(void *server_handle, krb5_principal principal,
kadm5_principal_ent_t entry,
long in_mask)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_error_code ret = 0;
long mask;
int i;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
/*
* In version 1, all the defined fields are always returned.
* entry is a pointer to a kadm5_principal_ent_t_v1 that should be
* filled with allocated memory.
*/
mask = in_mask;
memset(entry, 0, sizeof(*entry));
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return ret;
if ((mask & KADM5_POLICY) &&
adb.policy && (adb.aux_attributes & KADM5_POLICY)) {
if ((entry->policy = strdup(adb.policy)) == NULL) {
ret = ENOMEM;
goto done;
}
}
if (mask & KADM5_AUX_ATTRIBUTES)
entry->aux_attributes = adb.aux_attributes;
if ((mask & KADM5_PRINCIPAL) &&
(ret = krb5_copy_principal(handle->context, kdb->princ,
&entry->principal))) {
goto done;
}
if (mask & KADM5_PRINC_EXPIRE_TIME)
entry->princ_expire_time = kdb->expiration;
if ((mask & KADM5_LAST_PWD_CHANGE) &&
(ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb,
&(entry->last_pwd_change)))) {
goto done;
}
if (mask & KADM5_PW_EXPIRATION)
entry->pw_expiration = kdb->pw_expiration;
if (mask & KADM5_MAX_LIFE)
entry->max_life = kdb->max_life;
/* this is a little non-sensical because the function returns two */
/* values that must be checked separately against the mask */
if ((mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME)) {
ret = krb5_dbe_lookup_mod_princ_data(handle->context, kdb,
&(entry->mod_date),
&(entry->mod_name));
if (ret) {
goto done;
}
if (! (mask & KADM5_MOD_TIME))
entry->mod_date = 0;
if (! (mask & KADM5_MOD_NAME)) {
krb5_free_principal(handle->context, entry->mod_name);
entry->mod_name = NULL;
}
}
if (mask & KADM5_ATTRIBUTES)
entry->attributes = kdb->attributes;
if (mask & KADM5_KVNO)
for (entry->kvno = 0, i=0; i<kdb->n_key_data; i++)
if ((krb5_kvno) kdb->key_data[i].key_data_kvno > entry->kvno)
entry->kvno = kdb->key_data[i].key_data_kvno;
if (mask & KADM5_MKVNO) {
ret = krb5_dbe_get_mkvno(handle->context, kdb, &entry->mkvno);
if (ret)
goto done;
}
if (mask & KADM5_MAX_RLIFE)
entry->max_renewable_life = kdb->max_renewable_life;
if (mask & KADM5_LAST_SUCCESS)
entry->last_success = kdb->last_success;
if (mask & KADM5_LAST_FAILED)
entry->last_failed = kdb->last_failed;
if (mask & KADM5_FAIL_AUTH_COUNT)
entry->fail_auth_count = kdb->fail_auth_count;
if (mask & KADM5_TL_DATA) {
krb5_tl_data *tl, *tl2;
entry->tl_data = NULL;
tl = kdb->tl_data;
while (tl) {
if (tl->tl_data_type > 255) {
if ((tl2 = dup_tl_data(tl)) == NULL) {
ret = ENOMEM;
goto done;
}
tl2->tl_data_next = entry->tl_data;
entry->tl_data = tl2;
entry->n_tl_data++;
}
tl = tl->tl_data_next;
}
}
if (mask & KADM5_KEY_DATA) {
entry->n_key_data = kdb->n_key_data;
if(entry->n_key_data) {
entry->key_data = k5calloc(entry->n_key_data,
sizeof(krb5_key_data), &ret);
if (entry->key_data == NULL)
goto done;
} else
entry->key_data = NULL;
for (i = 0; i < entry->n_key_data; i++)
ret = krb5_copy_key_data_contents(handle->context,
&kdb->key_data[i],
&entry->key_data[i]);
if (ret)
goto done;
}
ret = KADM5_OK;
done:
if (ret && entry->principal) {
krb5_free_principal(handle->context, entry->principal);
entry->principal = NULL;
}
kdb_free_entry(handle, kdb, &adb);
return ret;
}
/*
* Function: check_pw_reuse
*
* Purpose: Check if a key appears in a list of keys, in order to
* enforce password history.
*
* Arguments:
*
* context (r) the krb5 context
* hist_keyblock (r) the key that hist_key_data is
* encrypted in
* n_new_key_data (r) length of new_key_data
* new_key_data (r) keys to check against
* pw_hist_data, encrypted in hist_keyblock
* n_pw_hist_data (r) length of pw_hist_data
* pw_hist_data (r) passwords to check new_key_data against
*
* Effects:
* For each new_key in new_key_data:
* decrypt new_key with the master_keyblock
* for each password in pw_hist_data:
* for each hist_key in password:
* decrypt hist_key with hist_keyblock
* compare the new_key and hist_key
*
* Returns krb5 errors, KADM5_PASS_RESUSE if a key in
* new_key_data is the same as a key in pw_hist_data, or 0.
*/
static kadm5_ret_t
check_pw_reuse(krb5_context context,
krb5_keyblock *hist_keyblocks,
int n_new_key_data, krb5_key_data *new_key_data,
unsigned int n_pw_hist_data, osa_pw_hist_ent *pw_hist_data)
{
unsigned int x, y, z;
krb5_keyblock newkey, histkey, *kb;
krb5_key_data *key_data;
krb5_error_code ret;
assert (n_new_key_data >= 0);
for (x = 0; x < (unsigned) n_new_key_data; x++) {
/* Check only entries with the most recent kvno. */
if (new_key_data[x].key_data_kvno != new_key_data[0].key_data_kvno)
break;
ret = krb5_dbe_decrypt_key_data(context, NULL, &(new_key_data[x]),
&newkey, NULL);
if (ret)
return(ret);
for (y = 0; y < n_pw_hist_data; y++) {
for (z = 0; z < (unsigned int) pw_hist_data[y].n_key_data; z++) {
for (kb = hist_keyblocks; kb->enctype != 0; kb++) {
key_data = &pw_hist_data[y].key_data[z];
ret = krb5_dbe_decrypt_key_data(context, kb, key_data,
&histkey, NULL);
if (ret)
continue;
if (newkey.length == histkey.length &&
newkey.enctype == histkey.enctype &&
memcmp(newkey.contents, histkey.contents,
histkey.length) == 0) {
krb5_free_keyblock_contents(context, &histkey);
krb5_free_keyblock_contents(context, &newkey);
return KADM5_PASS_REUSE;
}
krb5_free_keyblock_contents(context, &histkey);
}
}
}
krb5_free_keyblock_contents(context, &newkey);
}
return(0);
}
static void
free_history_entry(krb5_context context, osa_pw_hist_ent *hist)
{
int i;
for (i = 0; i < hist->n_key_data; i++)
krb5_free_key_data_contents(context, &hist->key_data[i]);
free(hist->key_data);
}
/*
* Function: create_history_entry
*
* Purpose: Creates a password history entry from an array of
* key_data.
*
* Arguments:
*
* context (r) krb5_context to use
* mkey (r) master keyblock to decrypt key data with
* hist_key (r) history keyblock to encrypt key data with
* n_key_data (r) number of elements in key_data
* key_data (r) keys to add to the history entry
* hist_out (w) history entry to fill in
*
* Effects:
*
* hist->key_data is allocated to store n_key_data key_datas. Each
* element of key_data is decrypted with master_keyblock, re-encrypted
* in hist_key, and added to hist->key_data. hist->n_key_data is
* set to n_key_data.
*/
static
int create_history_entry(krb5_context context,
krb5_keyblock *hist_key, int n_key_data,
krb5_key_data *key_data, osa_pw_hist_ent *hist_out)
{
int i;
krb5_error_code ret = 0;
krb5_keyblock key;
krb5_keysalt salt;
krb5_ui_2 kvno;
osa_pw_hist_ent hist;
hist_out->key_data = NULL;
hist_out->n_key_data = 0;
if (n_key_data < 0)
return EINVAL;
memset(&key, 0, sizeof(key));
memset(&hist, 0, sizeof(hist));
if (n_key_data == 0)
goto cleanup;
hist.key_data = k5calloc(n_key_data, sizeof(krb5_key_data), &ret);
if (hist.key_data == NULL)
goto cleanup;
/* We only want to store the most recent kvno, and key_data should already
* be sorted in descending order by kvno. */
kvno = key_data[0].key_data_kvno;
for (i = 0; i < n_key_data; i++) {
if (key_data[i].key_data_kvno < kvno)
break;
ret = krb5_dbe_decrypt_key_data(context, NULL,
&key_data[i], &key,
&salt);
if (ret)
goto cleanup;
ret = krb5_dbe_encrypt_key_data(context, hist_key, &key, &salt,
key_data[i].key_data_kvno,
&hist.key_data[hist.n_key_data]);
if (ret)
goto cleanup;
hist.n_key_data++;
krb5_free_keyblock_contents(context, &key);
/* krb5_free_keysalt(context, &salt); */
}
*hist_out = hist;
hist.n_key_data = 0;
hist.key_data = NULL;
cleanup:
krb5_free_keyblock_contents(context, &key);
free_history_entry(context, &hist);
return ret;
}
/*
* Function: add_to_history
*
* Purpose: Adds a password to a principal's password history.
*
* Arguments:
*
* context (r) krb5_context to use
* hist_kvno (r) kvno of current history key
* adb (r/w) admin principal entry to add keys to
* pol (r) adb's policy
* pw (r) keys for the password to add to adb's key history
*
* Effects:
*
* add_to_history adds a single password to adb's password history.
* pw contains n_key_data keys in its key_data, in storage should be
* allocated but not freed by the caller (XXX blech!).
*
* This function maintains adb->old_keys as a circular queue. It
* starts empty, and grows each time this function is called until it
* is pol->pw_history_num items long. adb->old_key_len holds the
* number of allocated entries in the array, and must therefore be [0,
* pol->pw_history_num). adb->old_key_next is the index into the
* array where the next element should be written, and must be [0,
* adb->old_key_len).
*/
static kadm5_ret_t add_to_history(krb5_context context,
krb5_kvno hist_kvno,
osa_princ_ent_t adb,
kadm5_policy_ent_t pol,
osa_pw_hist_ent *pw)
{
osa_pw_hist_ent *histp;
uint32_t nhist;
unsigned int i, knext, nkeys;
nhist = pol->pw_history_num;
/* A history of 1 means just check the current password */
if (nhist <= 1)
return 0;
if (adb->admin_history_kvno != hist_kvno) {
/* The history key has changed since the last password change, so we
* have to reset the password history. */
free(adb->old_keys);
adb->old_keys = NULL;
adb->old_key_len = 0;
adb->old_key_next = 0;
adb->admin_history_kvno = hist_kvno;
}
nkeys = adb->old_key_len;
knext = adb->old_key_next;
/* resize the adb->old_keys array if necessary */
if (nkeys + 1 < nhist) {
if (adb->old_keys == NULL) {
adb->old_keys = (osa_pw_hist_ent *)
malloc((nkeys + 1) * sizeof (osa_pw_hist_ent));
} else {
adb->old_keys = (osa_pw_hist_ent *)
realloc(adb->old_keys,
(nkeys + 1) * sizeof (osa_pw_hist_ent));
}
if (adb->old_keys == NULL)
return(ENOMEM);
memset(&adb->old_keys[nkeys], 0, sizeof(osa_pw_hist_ent));
nkeys = ++adb->old_key_len;
/*
* To avoid losing old keys, shift forward each entry after
* knext.
*/
for (i = nkeys - 1; i > knext; i--) {
adb->old_keys[i] = adb->old_keys[i - 1];
}
memset(&adb->old_keys[knext], 0, sizeof(osa_pw_hist_ent));
} else if (nkeys + 1 > nhist) {
/*
* The policy must have changed! Shrink the array.
* Can't simply realloc() down, since it might be wrapped.
* To understand the arithmetic below, note that we are
* copying into new positions 0 .. N-1 from old positions
* old_key_next-N .. old_key_next-1, modulo old_key_len,
* where N = pw_history_num - 1 is the length of the
* shortened list. Matt Crawford, FNAL
*/
/*
* M = adb->old_key_len, N = pol->pw_history_num - 1
*
* tmp[0] .. tmp[N-1] = old[(knext-N)%M] .. old[(knext-1)%M]
*/
int j;
osa_pw_hist_t tmp;
tmp = (osa_pw_hist_ent *)
malloc((nhist - 1) * sizeof (osa_pw_hist_ent));
if (tmp == NULL)
return ENOMEM;
for (i = 0; i < nhist - 1; i++) {
/*
* Add nkeys once before taking remainder to avoid
* negative values.
*/
j = (i + nkeys + knext - (nhist - 1)) % nkeys;
tmp[i] = adb->old_keys[j];
}
/* Now free the ones we don't keep (the oldest ones) */
for (i = 0; i < nkeys - (nhist - 1); i++) {
j = (i + nkeys + knext) % nkeys;
histp = &adb->old_keys[j];
for (j = 0; j < histp->n_key_data; j++) {
krb5_free_key_data_contents(context, &histp->key_data[j]);
}
free(histp->key_data);
}
free(adb->old_keys);
adb->old_keys = tmp;
nkeys = adb->old_key_len = nhist - 1;
knext = adb->old_key_next = 0;
}
/*
* If nhist decreased since the last password change, and nkeys+1
* is less than the previous nhist, it is possible for knext to
* index into unallocated space. This condition would not be
* caught by the resizing code above.
*/
if (knext + 1 > nkeys)
knext = adb->old_key_next = 0;
/* free the old pw history entry if it contains data */
histp = &adb->old_keys[knext];
for (i = 0; i < (unsigned int) histp->n_key_data; i++)
krb5_free_key_data_contents(context, &histp->key_data[i]);
free(histp->key_data);
/* store the new entry */
adb->old_keys[knext] = *pw;
/* update the next pointer */
if (++adb->old_key_next == nhist - 1)
adb->old_key_next = 0;
return(0);
}
/* FIXME: don't use global variable for this */
krb5_boolean use_password_server = 0;
#ifdef USE_PASSWORD_SERVER
static krb5_boolean
kadm5_use_password_server (void)
{
return use_password_server;
}
#endif
void kadm5_set_use_password_server (void);
void
kadm5_set_use_password_server (void)
{
use_password_server = 1;
}
#ifdef USE_PASSWORD_SERVER
/*
* kadm5_launch_task () runs a program (task_path) to synchronize the
* Apple password server with the Kerberos database. Password server
* programs can receive arguments on the command line (task_argv)
* and a block of data via stdin (data_buffer).
*
* Because a failure to communicate with the tool results in the
* password server falling out of sync with the database,
* kadm5_launch_task() always fails if it can't talk to the tool.
*/
static kadm5_ret_t
kadm5_launch_task (krb5_context context,
const char *task_path, char * const task_argv[],
const char *buffer)
{
kadm5_ret_t ret;
int data_pipe[2];
ret = pipe (data_pipe);
if (ret)
ret = errno;
if (!ret) {
pid_t pid = fork ();
if (pid == -1) {
ret = errno;
close (data_pipe[0]);
close (data_pipe[1]);
} else if (pid == 0) {
/* The child: */
if (dup2 (data_pipe[0], STDIN_FILENO) == -1)
_exit (1);
close (data_pipe[0]);
close (data_pipe[1]);
execv (task_path, task_argv);
_exit (1); /* Fail if execv fails */
} else {
/* The parent: */
int status;
ret = 0;
close (data_pipe[0]);
/* Write out the buffer to the child, add \n */
if (buffer) {
if (krb5_net_write (context, data_pipe[1], buffer, strlen (buffer)) < 0
|| krb5_net_write (context, data_pipe[1], "\n", 1) < 0)
{
/* kill the child to make sure waitpid() won't hang later */
ret = errno;
kill (pid, SIGKILL);
}
}
close (data_pipe[1]);
waitpid (pid, &status, 0);
if (!ret) {
if (WIFEXITED (status)) {
/* child read password and exited. Check the return value. */
if ((WEXITSTATUS (status) != 0) && (WEXITSTATUS (status) != 252)) {
ret = KRB5KDC_ERR_POLICY; /* password change rejected */
}
} else {
/* child read password but crashed or was killed */
ret = KRB5KRB_ERR_GENERIC; /* FIXME: better error */
}
}
}
}
return ret;
}
#endif
kadm5_ret_t
kadm5_chpass_principal(void *server_handle,
krb5_principal principal, char *password)
{
return
kadm5_chpass_principal_3(server_handle, principal, FALSE,
0, NULL, password);
}
kadm5_ret_t
kadm5_chpass_principal_3(void *server_handle,
krb5_principal principal, krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
char *password)
{
krb5_timestamp now;
kadm5_policy_ent_rec pol;
osa_princ_ent_rec adb;
krb5_db_entry *kdb;
int ret, ret2, hist_added;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
osa_pw_hist_ent hist;
krb5_keyblock *act_mkey, *hist_keyblocks = NULL;
krb5_kvno act_kvno, hist_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
hist_added = 0;
memset(&hist, 0, sizeof(hist));
if (principal == NULL || password == NULL)
return EINVAL;
if ((krb5_principal_compare(handle->context,
principal, hist_princ)) == TRUE)
return KADM5_PROTECT_PRINCIPAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
/* Create a password history entry before we change kdb's key_data. */
ret = kdb_get_hist_key(handle, &hist_keyblocks, &hist_kvno);
if (ret)
goto done;
ret = create_history_entry(handle->context, &hist_keyblocks[0],
kdb->n_key_data, kdb->key_data, &hist);
if (ret)
goto done;
}
if ((ret = passwd_check(handle, password, have_pol ? &pol : NULL,
principal)))
goto done;
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple,
password, 0 /* increment kvno */,
keepold, kdb);
if (ret)
goto done;
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto done;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
/* the policy was loaded before */
ret = check_pw_reuse(handle->context, hist_keyblocks,
kdb->n_key_data, kdb->key_data,
1, &hist);
if (ret)
goto done;
if (pol.pw_history_num > 1) {
/* If hist_kvno has changed since the last password change, we
* can't check the history. */
if (adb.admin_history_kvno == hist_kvno) {
ret = check_pw_reuse(handle->context, hist_keyblocks,
kdb->n_key_data, kdb->key_data,
adb.old_key_len, adb.old_keys);
if (ret)
goto done;
}
/* Don't save empty history. */
if (hist.n_key_data > 0) {
ret = add_to_history(handle->context, hist_kvno, &adb, &pol,
&hist);
if (ret)
goto done;
hist_added = 1;
}
}
if (pol.pw_max_life)
kdb->pw_expiration = ts_incr(now, pol.pw_max_life);
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
#ifdef USE_PASSWORD_SERVER
if (kadm5_use_password_server () &&
(krb5_princ_size (handle->context, principal) == 1)) {
krb5_data *princ = krb5_princ_component (handle->context, principal, 0);
const char *path = "/usr/sbin/mkpassdb";
char *argv[] = { "mkpassdb", "-setpassword", NULL, NULL };
char *pstring = NULL;
if (!ret) {
pstring = malloc ((princ->length + 1) * sizeof (char));
if (pstring == NULL) { ret = ENOMEM; }
}
if (!ret) {
memcpy (pstring, princ->data, princ->length);
pstring [princ->length] = '\0';
argv[2] = pstring;
ret = kadm5_launch_task (handle->context, path, argv, password);
}
if (pstring != NULL)
free (pstring);
if (ret)
goto done;
}
#endif
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
/* key data and attributes changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_ATTRIBUTES |
KADM5_FAIL_AUTH_COUNT;
/* | KADM5_CPW_FUNCTION */
if (hist_added)
kdb->mask |= KADM5_KEY_HIST;
ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold,
new_n_ks_tuple, new_ks_tuple, password);
if (ret)
goto done;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
(void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal,
keepold, new_n_ks_tuple, new_ks_tuple, password);
ret = KADM5_OK;
done:
free(new_ks_tuple);
if (!hist_added && hist.key_data)
free_history_entry(handle->context, &hist);
kdb_free_entry(handle, kdb, &adb);
kdb_free_keyblocks(handle, hist_keyblocks);
if (have_pol && (ret2 = kadm5_free_policy_ent(handle->lhandle, &pol))
&& !ret)
ret = ret2;
return ret;
}
kadm5_ret_t
kadm5_randkey_principal(void *server_handle,
krb5_principal principal,
krb5_keyblock **keyblocks,
int *n_keys)
{
return
kadm5_randkey_principal_3(server_handle, principal,
FALSE, 0, NULL,
keyblocks, n_keys);
}
kadm5_ret_t
kadm5_randkey_principal_3(void *server_handle,
krb5_principal principal,
krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_keyblock **keyblocks,
int *n_keys)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_timestamp now;
kadm5_policy_ent_rec pol;
int ret, n_new_keys;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_kvno act_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
if (keyblocks)
*keyblocks = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto done;
if (krb5_principal_compare(handle->context, principal, hist_princ)) {
/* If changing the history entry, the new entry must have exactly one
* key. */
if (keepold)
return KADM5_PROTECT_PRINCIPAL;
new_n_ks_tuple = 1;
}
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple,
keepold, kdb);
if (ret)
goto done;
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto done;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
if (pol.pw_max_life)
kdb->pw_expiration = ts_incr(now, pol.pw_max_life);
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
if (keyblocks) {
/* Return only the new keys added by krb5_dbe_crk. */
n_new_keys = count_new_keys(kdb->n_key_data, kdb->key_data);
ret = decrypt_key_data(handle->context, n_new_keys, kdb->key_data,
keyblocks, n_keys);
if (ret)
goto done;
}
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
/* | KADM5_RANDKEY_USED */;
ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold,
new_n_ks_tuple, new_ks_tuple, NULL);
if (ret)
goto done;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
(void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal,
keepold, new_n_ks_tuple, new_ks_tuple, NULL);
ret = KADM5_OK;
done:
free(new_ks_tuple);
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
/*
* kadm5_setv4key_principal:
*
* Set only ONE key of the principal, removing all others. This key
* must have the DES_CBC_CRC enctype and is entered as having the
* krb4 salttype. This is to enable things like kadmind4 to work.
*/
kadm5_ret_t
kadm5_setv4key_principal(void *server_handle,
krb5_principal principal,
krb5_keyblock *keyblock)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_timestamp now;
kadm5_policy_ent_rec pol;
krb5_keysalt keysalt;
int i, kvno, ret;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_key_data tmp_key_data;
krb5_keyblock *act_mkey;
memset( &tmp_key_data, 0, sizeof(tmp_key_data));
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL || keyblock == NULL)
return EINVAL;
if (hist_princ && /* this will be NULL when initializing the databse */
((krb5_principal_compare(handle->context,
principal, hist_princ)) == TRUE))
return KADM5_PROTECT_PRINCIPAL;
if (keyblock->enctype != ENCTYPE_DES_CBC_CRC)
return KADM5_SETV4KEY_INVAL_ENCTYPE;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
for (kvno = 0, i=0; i<kdb->n_key_data; i++)
if (kdb->key_data[i].key_data_kvno > kvno)
kvno = kdb->key_data[i].key_data_kvno;
if (kdb->key_data != NULL)
cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data);
kdb->key_data = calloc(1, sizeof(krb5_key_data));
if (kdb->key_data == NULL)
return ENOMEM;
kdb->n_key_data = 1;
keysalt.type = KRB5_KDB_SALTTYPE_V4;
/* XXX data.magic? */
keysalt.data.length = 0;
keysalt.data.data = NULL;
ret = kdb_get_active_mkey(handle, NULL, &act_mkey);
if (ret)
goto done;
/* use tmp_key_data as temporary location and reallocate later */
ret = krb5_dbe_encrypt_key_data(handle->context, act_mkey, keyblock,
&keysalt, kvno + 1, kdb->key_data);
if (ret) {
goto done;
}
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
if (pol.pw_max_life)
kdb->pw_expiration = ts_incr(now, pol.pw_max_life);
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
ret = KADM5_OK;
done:
for (i = 0; i < tmp_key_data.key_data_ver; i++) {
if (tmp_key_data.key_data_contents[i]) {
memset (tmp_key_data.key_data_contents[i], 0, tmp_key_data.key_data_length[i]);
free (tmp_key_data.key_data_contents[i]);
}
}
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
kadm5_ret_t
kadm5_setkey_principal(void *server_handle,
krb5_principal principal,
krb5_keyblock *keyblocks,
int n_keys)
{
return
kadm5_setkey_principal_3(server_handle, principal,
FALSE, 0, NULL,
keyblocks, n_keys);
}
kadm5_ret_t
kadm5_setkey_principal_3(void *server_handle,
krb5_principal principal,
krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_keyblock *keyblocks,
int n_keys)
{
kadm5_key_data *key_data;
kadm5_ret_t ret;
int i;
if (keyblocks == NULL)
return EINVAL;
if (n_ks_tuple) {
if (n_ks_tuple != n_keys)
return KADM5_SETKEY3_ETYPE_MISMATCH;
for (i = 0; i < n_ks_tuple; i++) {
if (ks_tuple[i].ks_enctype != keyblocks[i].enctype)
return KADM5_SETKEY3_ETYPE_MISMATCH;
}
}
key_data = calloc(n_keys, sizeof(kadm5_key_data));
if (key_data == NULL)
return ENOMEM;
for (i = 0; i < n_keys; i++) {
key_data[i].key = keyblocks[i];
key_data[i].salt.type =
n_ks_tuple ? ks_tuple[i].ks_salttype : KRB5_KDB_SALTTYPE_NORMAL;
}
ret = kadm5_setkey_principal_4(server_handle, principal, keepold,
key_data, n_keys);
free(key_data);
return ret;
}
/* Create a key/salt list from a key_data array. */
static kadm5_ret_t
make_ks_from_key_data(krb5_context context, kadm5_key_data *key_data,
int n_key_data, krb5_key_salt_tuple **out)
{
int i;
krb5_key_salt_tuple *ks;
*out = NULL;
ks = calloc(n_key_data, sizeof(*ks));
if (ks == NULL)
return ENOMEM;
for (i = 0; i < n_key_data; i++) {
ks[i].ks_enctype = key_data[i].key.enctype;
ks[i].ks_salttype = key_data[i].salt.type;
}
*out = ks;
return 0;
}
kadm5_ret_t
kadm5_setkey_principal_4(void *server_handle, krb5_principal principal,
krb5_boolean keepold, kadm5_key_data *key_data,
int n_key_data)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_timestamp now;
kadm5_policy_ent_rec pol;
krb5_key_data *new_key_data = NULL;
int i, j, ret, n_new_key_data = 0;
krb5_kvno kvno;
krb5_boolean similar, have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_key_salt_tuple *ks_from_keys = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL || key_data == NULL || n_key_data == 0)
return EINVAL;
/* hist_princ will be NULL when initializing the database. */
if (hist_princ != NULL &&
krb5_principal_compare(handle->context, principal, hist_princ))
return KADM5_PROTECT_PRINCIPAL;
/* For now, all keys must have the same kvno. */
kvno = key_data[0].kvno;
for (i = 1; i < n_key_data; i++) {
if (key_data[i].kvno != kvno)
return KADM5_SETKEY_BAD_KVNO;
}
ret = kdb_get_entry(handle, principal, &kdb, &adb);
if (ret)
return ret;
if (kvno == 0) {
/* Pick the next kvno. */
for (i = 0; i < kdb->n_key_data; i++) {
if (kdb->key_data[i].key_data_kvno > kvno)
kvno = kdb->key_data[i].key_data_kvno;
}
kvno++;
} else if (keepold) {
/* Check that the kvno does collide with existing keys. */
for (i = 0; i < kdb->n_key_data; i++) {
if (kdb->key_data[i].key_data_kvno == kvno) {
ret = KADM5_SETKEY_BAD_KVNO;
goto done;
}
}
}
ret = make_ks_from_key_data(handle->context, key_data, n_key_data,
&ks_from_keys);
if (ret)
goto done;
ret = apply_keysalt_policy(handle, adb.policy, n_key_data, ks_from_keys,
NULL, NULL);
free(ks_from_keys);
if (ret)
goto done;
for (i = 0; i < n_key_data; i++) {
for (j = i + 1; j < n_key_data; j++) {
ret = krb5_c_enctype_compare(handle->context,
key_data[i].key.enctype,
key_data[j].key.enctype,
&similar);
if (ret)
goto done;
if (similar) {
if (key_data[i].salt.type == key_data[j].salt.type) {
ret = KADM5_SETKEY_DUP_ENCTYPES;
goto done;
}
}
}
}
n_new_key_data = n_key_data + (keepold ? kdb->n_key_data : 0);
new_key_data = calloc(n_new_key_data, sizeof(krb5_key_data));
if (new_key_data == NULL) {
n_new_key_data = 0;
ret = ENOMEM;
goto done;
}
n_new_key_data = 0;
for (i = 0; i < n_key_data; i++) {
ret = kdb_get_active_mkey(handle, NULL, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_encrypt_key_data(handle->context, act_mkey,
&key_data[i].key, &key_data[i].salt,
kvno, &new_key_data[i]);
if (ret)
goto done;
n_new_key_data++;
}
/* Copy old key data if necessary. */
if (keepold) {
memcpy(new_key_data + n_new_key_data, kdb->key_data,
kdb->n_key_data * sizeof(krb5_key_data));
memset(kdb->key_data, 0, kdb->n_key_data * sizeof(krb5_key_data));
/*
* Sort the keys to maintain the defined kvno order. We only need to
* sort if we keep old keys, as otherwise we allow only a single kvno
* to be specified.
*/
krb5_dbe_sort_key_data(new_key_data, n_new_key_data);
}
/* Replace kdb->key_data with the new keys. */
cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data);
kdb->key_data = new_key_data;
kdb->n_key_data = n_new_key_data;
new_key_data = NULL;
n_new_key_data = 0;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if (adb.aux_attributes & KADM5_POLICY) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
if (pol.pw_max_life)
kdb->pw_expiration = ts_incr(now, pol.pw_max_life);
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* Unlock principal on this KDC. */
kdb->fail_auth_count = 0;
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
ret = kdb_put_entry(handle, kdb, &adb);
if (ret)
goto done;
ret = KADM5_OK;
done:
cleanup_key_data(handle->context, n_new_key_data, new_key_data);
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
/*
* Return the list of keys like kadm5_randkey_principal,
* but don't modify the principal.
*/
kadm5_ret_t
kadm5_get_principal_keys(void *server_handle /* IN */,
krb5_principal principal /* IN */,
krb5_kvno kvno /* IN */,
kadm5_key_data **key_data_out /* OUT */,
int *n_key_data_out /* OUT */)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
kadm5_ret_t ret;
kadm5_server_handle_t handle = server_handle;
kadm5_key_data *key_data = NULL;
int i, nkeys = 0;
if (principal == NULL || key_data_out == NULL || n_key_data_out == NULL)
return EINVAL;
CHECK_HANDLE(server_handle);
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
key_data = calloc(kdb->n_key_data, sizeof(kadm5_key_data));
if (key_data == NULL) {
ret = ENOMEM;
goto done;
}
for (i = 0, nkeys = 0; i < kdb->n_key_data; i++) {
if (kvno != 0 && kvno != kdb->key_data[i].key_data_kvno)
continue;
key_data[nkeys].kvno = kdb->key_data[i].key_data_kvno;
ret = krb5_dbe_decrypt_key_data(handle->context, NULL,
&kdb->key_data[i],
&key_data[nkeys].key,
&key_data[nkeys].salt);
if (ret)
goto done;
nkeys++;
}
*n_key_data_out = nkeys;
*key_data_out = key_data;
key_data = NULL;
nkeys = 0;
ret = KADM5_OK;
done:
kdb_free_entry(handle, kdb, &adb);
kadm5_free_kadm5_key_data(handle->context, nkeys, key_data);
return ret;
}
/*
* Allocate an array of n_key_data krb5_keyblocks, fill in each
* element with the results of decrypting the nth key in key_data,
* and if n_keys is not NULL fill it in with the
* number of keys decrypted.
*/
static int decrypt_key_data(krb5_context context,
int n_key_data, krb5_key_data *key_data,
krb5_keyblock **keyblocks, int *n_keys)
{
krb5_keyblock *keys;
int ret, i;
keys = (krb5_keyblock *) malloc(n_key_data*sizeof(krb5_keyblock));
if (keys == NULL)
return ENOMEM;
memset(keys, 0, n_key_data*sizeof(krb5_keyblock));
for (i = 0; i < n_key_data; i++) {
ret = krb5_dbe_decrypt_key_data(context, NULL, &key_data[i], &keys[i],
NULL);
if (ret) {
for (; i >= 0; i--) {
if (keys[i].contents) {
memset (keys[i].contents, 0, keys[i].length);
free( keys[i].contents );
}
}
memset(keys, 0, n_key_data*sizeof(krb5_keyblock));
free(keys);
return ret;
}
}
*keyblocks = keys;
if (n_keys)
*n_keys = n_key_data;
return 0;
}
/*
* Function: kadm5_decrypt_key
*
* Purpose: Retrieves and decrypts a principal key.
*
* Arguments:
*
* server_handle (r) kadm5 handle
* entry (r) principal retrieved with kadm5_get_principal
* ktype (r) enctype to search for, or -1 to ignore
* stype (r) salt type to search for, or -1 to ignore
* kvno (r) kvno to search for, -1 for max, 0 for max
* only if it also matches ktype and stype
* keyblock (w) keyblock to fill in
* keysalt (w) keysalt to fill in, or NULL
* kvnop (w) kvno to fill in, or NULL
*
* Effects: Searches the key_data array of entry, which must have been
* retrived with kadm5_get_principal with the KADM5_KEY_DATA mask, to
* find a key with a specified enctype, salt type, and kvno in a
* principal entry. If not found, return ENOENT. Otherwise, decrypt
* it with the master key, and return the key in keyblock, the salt
* in salttype, and the key version number in kvno.
*
* If ktype or stype is -1, it is ignored for the search. If kvno is
* -1, ktype and stype are ignored and the key with the max kvno is
* returned. If kvno is 0, only the key with the max kvno is returned
* and only if it matches the ktype and stype; otherwise, ENOENT is
* returned.
*/
kadm5_ret_t kadm5_decrypt_key(void *server_handle,
kadm5_principal_ent_t entry, krb5_int32
ktype, krb5_int32 stype, krb5_int32
kvno, krb5_keyblock *keyblock,
krb5_keysalt *keysalt, int *kvnop)
{
kadm5_server_handle_t handle = server_handle;
krb5_db_entry dbent;
krb5_key_data *key_data;
krb5_keyblock *mkey_ptr;
int ret;
CHECK_HANDLE(server_handle);
if (entry->n_key_data == 0 || entry->key_data == NULL)
return EINVAL;
/* find_enctype only uses these two fields */
dbent.n_key_data = entry->n_key_data;
dbent.key_data = entry->key_data;
if ((ret = krb5_dbe_find_enctype(handle->context, &dbent, ktype,
stype, kvno, &key_data)))
return ret;
/* find_mkey only uses this field */
dbent.tl_data = entry->tl_data;
if ((ret = krb5_dbe_find_mkey(handle->context, &dbent, &mkey_ptr))) {
/* try refreshing master key list */
/* XXX it would nice if we had the mkvno here for optimization */
if (krb5_db_fetch_mkey_list(handle->context, master_princ,
&master_keyblock) == 0) {
if ((ret = krb5_dbe_find_mkey(handle->context, &dbent,
&mkey_ptr))) {
return ret;
}
} else {
return ret;
}
}
if ((ret = krb5_dbe_decrypt_key_data(handle->context, NULL, key_data,
keyblock, keysalt)))
return ret;
/*
* Coerce the enctype of the output keyblock in case we got an
* inexact match on the enctype; this behavior will go away when
* the key storage architecture gets redesigned for 1.3.
*/
if (ktype != -1)
keyblock->enctype = ktype;
if (kvnop)
*kvnop = key_data->key_data_kvno;
return KADM5_OK;
}
kadm5_ret_t
kadm5_purgekeys(void *server_handle,
krb5_principal principal,
int keepkvno)
{
kadm5_server_handle_t handle = server_handle;
kadm5_ret_t ret;
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_key_data *old_keydata;
int n_old_keydata;
int i, j, k;
CHECK_HANDLE(server_handle);
if (principal == NULL)
return EINVAL;
ret = kdb_get_entry(handle, principal, &kdb, &adb);
if (ret)
return(ret);
if (keepkvno <= 0) {
keepkvno = krb5_db_get_key_data_kvno(handle->context, kdb->n_key_data,
kdb->key_data);
}
old_keydata = kdb->key_data;
n_old_keydata = kdb->n_key_data;
kdb->n_key_data = 0;
/* Allocate one extra key_data to avoid allocating 0 bytes. */
kdb->key_data = calloc(n_old_keydata, sizeof(krb5_key_data));
if (kdb->key_data == NULL) {
ret = ENOMEM;
goto done;
}
memset(kdb->key_data, 0, n_old_keydata * sizeof(krb5_key_data));
for (i = 0, j = 0; i < n_old_keydata; i++) {
if (old_keydata[i].key_data_kvno < keepkvno)
continue;
/* Alias the key_data_contents pointers; we null them out in the
* source array immediately after. */
kdb->key_data[j] = old_keydata[i];
for (k = 0; k < old_keydata[i].key_data_ver; k++) {
old_keydata[i].key_data_contents[k] = NULL;
}
j++;
}
kdb->n_key_data = j;
cleanup_key_data(handle->context, n_old_keydata, old_keydata);
kdb->mask = KADM5_KEY_DATA;
ret = kdb_put_entry(handle, kdb, &adb);
if (ret)
goto done;
done:
kdb_free_entry(handle, kdb, &adb);
return ret;
}
kadm5_ret_t
kadm5_get_strings(void *server_handle, krb5_principal principal,
krb5_string_attr **strings_out, int *count_out)
{
kadm5_server_handle_t handle = server_handle;
kadm5_ret_t ret;
krb5_db_entry *kdb = NULL;
*strings_out = NULL;
*count_out = 0;
CHECK_HANDLE(server_handle);
if (principal == NULL)
return EINVAL;
ret = kdb_get_entry(handle, principal, &kdb, NULL);
if (ret)
return ret;
ret = krb5_dbe_get_strings(handle->context, kdb, strings_out, count_out);
kdb_free_entry(handle, kdb, NULL);
return ret;
}
kadm5_ret_t
kadm5_set_string(void *server_handle, krb5_principal principal,
const char *key, const char *value)
{
kadm5_server_handle_t handle = server_handle;
kadm5_ret_t ret;
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
CHECK_HANDLE(server_handle);
if (principal == NULL || key == NULL)
return EINVAL;
ret = kdb_get_entry(handle, principal, &kdb, &adb);
if (ret)
return ret;
ret = krb5_dbe_set_string(handle->context, kdb, key, value);
if (ret)
goto done;
kdb->mask = KADM5_TL_DATA;
ret = kdb_put_entry(handle, kdb, &adb);
done:
kdb_free_entry(handle, kdb, &adb);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_576_0 |
crossvul-cpp_data_bad_3402_0 | /*
* DNxHD/VC-3 parser
* Copyright (c) 2008 Baptiste Coudurier <baptiste.coudurier@free.fr>
*
* 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
* DNxHD/VC-3 parser
*/
#include "parser.h"
#include "dnxhddata.h"
typedef struct {
ParseContext pc;
int cur_byte;
int remaining;
int w, h;
} DNXHDParserContext;
static int dnxhd_get_hr_frame_size(int cid, int w, int h)
{
int result, i = ff_dnxhd_get_cid_table(cid);
if (i < 0)
return i;
result = ((h + 15) / 16) * ((w + 15) / 16) * ff_dnxhd_cid_table[i].packet_scale.num / ff_dnxhd_cid_table[i].packet_scale.den;
result = (result + 2048) / 4096 * 4096;
return FFMAX(result, 8192);
}
static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
if (cid <= 0)
continue;
dctx->remaining = avpriv_dnxhd_get_frame_size(cid);
if (dctx->remaining <= 0) {
dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (dctx->remaining <= 0)
return dctx->remaining;
}
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
static int dnxhd_parse(AVCodecParserContext *s,
AVCodecContext *avctx,
const uint8_t **poutbuf, int *poutbuf_size,
const uint8_t *buf, int buf_size)
{
DNXHDParserContext *dctx = s->priv_data;
ParseContext *pc = &dctx->pc;
int next;
if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
next = buf_size;
} else {
next = dnxhd_find_frame_end(dctx, buf, buf_size);
if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
*poutbuf = NULL;
*poutbuf_size = 0;
return buf_size;
}
}
*poutbuf = buf;
*poutbuf_size = buf_size;
return next;
}
AVCodecParser ff_dnxhd_parser = {
.codec_ids = { AV_CODEC_ID_DNXHD },
.priv_data_size = sizeof(DNXHDParserContext),
.parser_parse = dnxhd_parse,
.parser_close = ff_parse_close,
};
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_3402_0 |
crossvul-cpp_data_bad_862_0 | /* $Id: upnpsoap.c,v 1.151 2018/03/13 10:32:53 nanard Exp $ */
/* vim: tabstop=4 shiftwidth=4 noexpandtab
* MiniUPnP project
* http://miniupnp.free.fr/ or https://miniupnp.tuxfamily.org/
* (c) 2006-2018 Thomas Bernard
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <unistd.h>
#include <syslog.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <ctype.h>
#include "macros.h"
#include "config.h"
#include "upnpglobalvars.h"
#include "upnphttp.h"
#include "upnpsoap.h"
#include "upnpreplyparse.h"
#include "upnpredirect.h"
#include "upnppinhole.h"
#include "getifaddr.h"
#include "getifstats.h"
#include "getconnstatus.h"
#include "upnpurns.h"
#include "upnputils.h"
/* utility function */
static int is_numeric(const char * s)
{
while(*s) {
if(*s < '0' || *s > '9') return 0;
s++;
}
return 1;
}
static void
BuildSendAndCloseSoapResp(struct upnphttp * h,
const char * body, int bodylen)
{
static const char beforebody[] =
"<?xml version=\"1.0\"?>\r\n"
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body>";
static const char afterbody[] =
"</s:Body>"
"</s:Envelope>\r\n";
int r = BuildHeader_upnphttp(h, 200, "OK", sizeof(beforebody) - 1
+ sizeof(afterbody) - 1 + bodylen );
if(r >= 0) {
memcpy(h->res_buf + h->res_buflen, beforebody, sizeof(beforebody) - 1);
h->res_buflen += sizeof(beforebody) - 1;
memcpy(h->res_buf + h->res_buflen, body, bodylen);
h->res_buflen += bodylen;
memcpy(h->res_buf + h->res_buflen, afterbody, sizeof(afterbody) - 1);
h->res_buflen += sizeof(afterbody) - 1;
} else {
BuildResp2_upnphttp(h, 500, "Internal Server Error", NULL, 0);
}
SendRespAndClose_upnphttp(h);
}
static void
GetConnectionTypeInfo(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:GetConnectionTypeInfoResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"<NewConnectionType>IP_Routed</NewConnectionType>"
"<NewPossibleConnectionTypes>IP_Routed</NewPossibleConnectionTypes>"
"</u:GetConnectionTypeInfoResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewConnectionType>IP_Routed</NewConnectionType>"
"<NewPossibleConnectionTypes>IP_Routed</NewPossibleConnectionTypes>"
"</u:%sResponse>";
char body[512];
int bodylen;
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
/* maximum value for a UPNP ui4 type variable */
#define UPNP_UI4_MAX (4294967295ul)
static void
GetTotalBytesSent(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalBytesSent>%lu</NewTotalBytesSent>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.obytes & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.obytes, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalBytesReceived(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalBytesReceived>%lu</NewTotalBytesReceived>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
/* TotalBytesReceived
* This variable represents the cumulative counter for total number of
* bytes received downstream across all connection service instances on
* WANDevice. The count rolls over to 0 after it reaching the maximum
* value (2^32)-1. */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.ibytes & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.ibytes, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalPacketsSent(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalPacketsSent>%lu</NewTotalPacketsSent>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1",*/
#ifdef UPNP_STRICT
r<0?0:(data.opackets & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.opackets, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalPacketsReceived(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalPacketsReceived>%lu</NewTotalPacketsReceived>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.ipackets & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.ipackets, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetCommonLinkProperties(struct upnphttp * h, const char * action, const char * ns)
{
/* WANAccessType : set depending on the hardware :
* DSL, POTS (plain old Telephone service), Cable, Ethernet */
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewWANAccessType>%s</NewWANAccessType>"
"<NewLayer1UpstreamMaxBitRate>%lu</NewLayer1UpstreamMaxBitRate>"
"<NewLayer1DownstreamMaxBitRate>%lu</NewLayer1DownstreamMaxBitRate>"
"<NewPhysicalLinkStatus>%s</NewPhysicalLinkStatus>"
"</u:%sResponse>";
char body[2048];
int bodylen;
struct ifdata data;
const char * status = "Up"; /* Up, Down (Required),
* Initializing, Unavailable (Optional) */
const char * wan_access_type = "Cable"; /* DSL, POTS, Cable, Ethernet */
char ext_ip_addr[INET_ADDRSTRLEN];
if((downstream_bitrate == 0) || (upstream_bitrate == 0))
{
if(getifstats(ext_if_name, &data) >= 0)
{
if(downstream_bitrate == 0) downstream_bitrate = data.baudrate;
if(upstream_bitrate == 0) upstream_bitrate = data.baudrate;
}
}
if(getifaddr(ext_if_name, ext_ip_addr, INET_ADDRSTRLEN, NULL, NULL) < 0) {
status = "Down";
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
wan_access_type,
upstream_bitrate, downstream_bitrate,
status, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetStatusInfo(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewConnectionStatus>%s</NewConnectionStatus>"
"<NewLastConnectionError>ERROR_NONE</NewLastConnectionError>"
"<NewUptime>%ld</NewUptime>"
"</u:%sResponse>";
char body[512];
int bodylen;
time_t uptime;
const char * status;
/* ConnectionStatus possible values :
* Unconfigured, Connecting, Connected, PendingDisconnect,
* Disconnecting, Disconnected */
status = get_wan_connection_status_str(ext_if_name);
uptime = upnp_get_uptime();
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
status, (long)uptime, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetNATRSIPStatus(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:GetNATRSIPStatusResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"<NewRSIPAvailable>0</NewRSIPAvailable>"
"<NewNATEnabled>1</NewNATEnabled>"
"</u:GetNATRSIPStatusResponse>";
UNUSED(action);
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewRSIPAvailable>0</NewRSIPAvailable>"
"<NewNATEnabled>1</NewNATEnabled>"
"</u:%sResponse>";
char body[512];
int bodylen;
/* 2.2.9. RSIPAvailable
* This variable indicates if Realm-specific IP (RSIP) is available
* as a feature on the InternetGatewayDevice. RSIP is being defined
* in the NAT working group in the IETF to allow host-NATing using
* a standard set of message exchanges. It also allows end-to-end
* applications that otherwise break if NAT is introduced
* (e.g. IPsec-based VPNs).
* A gateway that does not support RSIP should set this variable to 0. */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetExternalIPAddress(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewExternalIPAddress>%s</NewExternalIPAddress>"
"</u:%sResponse>";
char body[512];
int bodylen;
char ext_ip_addr[INET_ADDRSTRLEN];
/* Does that method need to work with IPv6 ?
* There is usually no NAT with IPv6 */
#ifndef MULTIPLE_EXTERNAL_IP
struct in_addr addr;
if(use_ext_ip_addr)
{
strncpy(ext_ip_addr, use_ext_ip_addr, INET_ADDRSTRLEN);
ext_ip_addr[INET_ADDRSTRLEN - 1] = '\0';
}
else if(getifaddr(ext_if_name, ext_ip_addr, INET_ADDRSTRLEN, &addr, NULL) < 0)
{
syslog(LOG_ERR, "Failed to get ip address for interface %s",
ext_if_name);
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
}
if (addr_is_reserved(&addr))
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
#else
struct lan_addr_s * lan_addr;
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
for(lan_addr = lan_addrs.lh_first; lan_addr != NULL; lan_addr = lan_addr->list.le_next)
{
if( (h->clientaddr.s_addr & lan_addr->mask.s_addr)
== (lan_addr->addr.s_addr & lan_addr->mask.s_addr))
{
strncpy(ext_ip_addr, lan_addr->ext_ip_str, INET_ADDRSTRLEN);
break;
}
}
#endif
if (strcmp(ext_ip_addr, "0.0.0.0") == 0)
{
SoapError(h, 501, "Action Failed");
return;
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
ext_ip_addr, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
/* AddPortMapping method of WANIPConnection Service
* Ignored argument : NewEnabled */
static void
AddPortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
/*static const char resp[] =
"<u:AddPortMappingResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\"/>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\"/>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * ext_port, * protocol, * desc;
char * leaseduration_str;
unsigned int leaseduration;
char * r_host;
unsigned short iport, eport;
struct hostent *hp; /* getbyhostname() */
char ** ptr; /* getbyhostname() */
struct in_addr result_ip;/*unsigned char result_ip[16];*/ /* inet_pton() */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "NewInternalClient");
if (int_ip) {
/* trim */
while(int_ip[0] == ' ')
int_ip++;
}
#ifdef UPNP_STRICT
if (!int_ip || int_ip[0] == '\0')
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#endif
/* IGD 2 MUST support both wildcard and specific IP address values
* for RemoteHost (only the wildcard value was REQUIRED in release 1.0) */
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
#ifndef UPNP_STRICT
/* if <NewInternalClient> arg is empty, use client address
* see https://github.com/miniupnp/miniupnp/issues/236 */
if (!int_ip || int_ip[0] == '\0')
{
int_ip = h->clientaddr_str;
memcpy(&result_ip, &(h->clientaddr), sizeof(struct in_addr));
}
else
#endif
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET, int_ip, &result_ip) <= 0)
{
hp = gethostbyname(int_ip);
if(hp && hp->h_addrtype == AF_INET)
{
for(ptr = hp->h_addr_list; ptr && *ptr; ptr++)
{
int_ip = inet_ntoa(*((struct in_addr *) *ptr));
result_ip = *((struct in_addr *) *ptr);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
}
/* check if NewInternalAddress is the client address */
if(GETFLAG(SECUREMODEMASK))
{
if(h->clientaddr.s_addr != result_ip.s_addr)
{
syslog(LOG_INFO, "Client %s tried to redirect port to %s",
inet_ntoa(h->clientaddr), int_ip);
ClearNameValueList(&data);
SoapError(h, 718, "ConflictInMappingEntry");
return;
}
}
int_port = GetValueFromNameValueList(&data, "NewInternalPort");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
desc = GetValueFromNameValueList(&data, "NewPortMappingDescription");
leaseduration_str = GetValueFromNameValueList(&data, "NewLeaseDuration");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
eport = (unsigned short)atoi(ext_port);
iport = (unsigned short)atoi(int_port);
if (strcmp(ext_port, "*") == 0 || eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 716, "Wildcard not permited in ExtPort");
return;
}
leaseduration = leaseduration_str ? atoi(leaseduration_str) : 0;
#ifdef IGD_V2
/* PortMappingLeaseDuration can be either a value between 1 and
* 604800 seconds or the zero value (for infinite lease time).
* Note that an infinite lease time can be only set by out-of-band
* mechanisms like WWW-administration, remote management or local
* management.
* If a control point uses the value 0 to indicate an infinite lease
* time mapping, it is REQUIRED that gateway uses the maximum value
* instead (e.g. 604800 seconds) */
if(leaseduration == 0 || leaseduration > 604800)
leaseduration = 604800;
#endif
syslog(LOG_INFO, "%s: ext port %hu to %s:%hu protocol %s for: %s leaseduration=%u rhost=%s",
action, eport, int_ip, iport, protocol, desc, leaseduration,
r_host ? r_host : "NULL");
r = upnp_redirect(r_host, eport, int_ip, iport, protocol, desc, leaseduration);
ClearNameValueList(&data);
/* possible error codes for AddPortMapping :
* 402 - Invalid Args
* 501 - Action Failed
* 715 - Wildcard not permited in SrcAddr
* 716 - Wildcard not permited in ExtPort
* 718 - ConflictInMappingEntry
* 724 - SamePortValuesRequired (deprecated in IGD v2)
* 725 - OnlyPermanentLeasesSupported
The NAT implementation only supports permanent lease times on
port mappings (deprecated in IGD v2)
* 726 - RemoteHostOnlySupportsWildcard
RemoteHost must be a wildcard and cannot be a specific IP
address or DNS name (deprecated in IGD v2)
* 727 - ExternalPortOnlySupportsWildcard
ExternalPort must be a wildcard and cannot be a specific port
value (deprecated in IGD v2)
* 728 - NoPortMapsAvailable
There are not enough free ports available to complete the mapping
(added in IGD v2)
* 729 - ConflictWithOtherMechanisms (added in IGD v2) */
switch(r)
{
case 0: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*SERVICE_TYPE_WANIPC*/);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -4:
#ifdef IGD_V2
SoapError(h, 729, "ConflictWithOtherMechanisms");
break;
#endif /* IGD_V2 */
case -2: /* already redirected */
case -3: /* not permitted */
SoapError(h, 718, "ConflictInMappingEntry");
break;
default:
SoapError(h, 501, "ActionFailed");
}
}
/* AddAnyPortMapping was added in WANIPConnection v2 */
static void
AddAnyPortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewReservedPort>%hu</NewReservedPort>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * int_ip, * int_port, * ext_port, * protocol, * desc;
const char * r_host;
unsigned short iport, eport;
const char * leaseduration_str;
unsigned int leaseduration;
struct hostent *hp; /* getbyhostname() */
char ** ptr; /* getbyhostname() */
struct in_addr result_ip;/*unsigned char result_ip[16];*/ /* inet_pton() */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
int_port = GetValueFromNameValueList(&data, "NewInternalPort");
int_ip = GetValueFromNameValueList(&data, "NewInternalClient");
/* NewEnabled */
desc = GetValueFromNameValueList(&data, "NewPortMappingDescription");
leaseduration_str = GetValueFromNameValueList(&data, "NewLeaseDuration");
leaseduration = leaseduration_str ? atoi(leaseduration_str) : 0;
if(leaseduration == 0)
leaseduration = 604800;
if (!int_ip || !ext_port || !int_port)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
eport = (unsigned short)atoi(ext_port);
iport = (unsigned short)atoi(int_port);
if(iport == 0 || !is_numeric(ext_port)) {
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET, int_ip, &result_ip) <= 0)
{
hp = gethostbyname(int_ip);
if(hp && hp->h_addrtype == AF_INET)
{
for(ptr = hp->h_addr_list; ptr && *ptr; ptr++)
{
int_ip = inet_ntoa(*((struct in_addr *) *ptr));
result_ip = *((struct in_addr *) *ptr);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
}
/* check if NewInternalAddress is the client address */
if(GETFLAG(SECUREMODEMASK))
{
if(h->clientaddr.s_addr != result_ip.s_addr)
{
syslog(LOG_INFO, "Client %s tried to redirect port to %s",
inet_ntoa(h->clientaddr), int_ip);
ClearNameValueList(&data);
SoapError(h, 606, "Action not authorized");
return;
}
}
/* TODO : accept a different external port
* have some smart strategy to choose the port */
for(;;) {
r = upnp_redirect(r_host, eport, int_ip, iport, protocol, desc, leaseduration);
if(r==-2 && eport < 65535) {
eport++;
} else {
break;
}
}
ClearNameValueList(&data);
switch(r)
{
case 0: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
eport, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -2: /* already redirected */
SoapError(h, 718, "ConflictInMappingEntry");
break;
case -3: /* not permitted */
SoapError(h, 606, "Action not authorized");
break;
default:
SoapError(h, 501, "ActionFailed");
}
}
static void
GetSpecificPortMappingEntry(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewInternalPort>%u</NewInternalPort>"
"<NewInternalClient>%s</NewInternalClient>"
"<NewEnabled>1</NewEnabled>"
"<NewPortMappingDescription>%s</NewPortMappingDescription>"
"<NewLeaseDuration>%u</NewLeaseDuration>"
"</u:%sResponse>";
char body[1024];
int bodylen;
struct NameValueParserData data;
const char * r_host, * ext_port, * protocol;
unsigned short eport, iport;
char int_ip[32];
char desc[64];
unsigned int leaseduration = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
#ifdef UPNP_STRICT
if(!ext_port || !protocol || !r_host)
#else
if(!ext_port || !protocol)
#endif
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
eport = (unsigned short)atoi(ext_port);
if(eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
/* TODO : add r_host as an input parameter ...
* We prevent several Port Mapping with same external port
* but different remoteHost to be set up, so that is not
* a priority. */
r = upnp_get_redirection_infos(eport, protocol, &iport,
int_ip, sizeof(int_ip),
desc, sizeof(desc),
NULL, 0,
&leaseduration);
if(r < 0)
{
SoapError(h, 714, "NoSuchEntryInArray");
}
else
{
syslog(LOG_INFO, "%s: rhost='%s' %s %s found => %s:%u desc='%s'",
action,
r_host ? r_host : "NULL", ext_port, protocol, int_ip,
(unsigned int)iport, desc);
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*SERVICE_TYPE_WANIPC*/,
(unsigned int)iport, int_ip, desc, leaseduration,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
static void
DeletePortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
/*static const char resp[] =
"<u:DeletePortMappingResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"</u:DeletePortMappingResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * ext_port, * protocol;
unsigned short eport;
#ifdef UPNP_STRICT
const char * r_host;
#endif /* UPNP_STRICT */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
#ifdef UPNP_STRICT
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
#endif /* UPNP_STRICT */
#ifdef UPNP_STRICT
if(!ext_port || !protocol || !r_host)
#else
if(!ext_port || !protocol)
#endif /* UPNP_STRICT */
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif /* UPNP_STRICT */
#endif /* SUPPORT_REMOTEHOST */
eport = (unsigned short)atoi(ext_port);
if(eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
syslog(LOG_INFO, "%s: external port: %hu, protocol: %s",
action, eport, protocol);
/* if in secure mode, check the IP
* Removing a redirection is not a security threat,
* just an annoyance for the user using it. So this is not
* a priority. */
if(GETFLAG(SECUREMODEMASK))
{
char int_ip[32];
struct in_addr int_ip_addr;
unsigned short iport;
unsigned int leaseduration = 0;
r = upnp_get_redirection_infos(eport, protocol, &iport,
int_ip, sizeof(int_ip),
NULL, 0, NULL, 0,
&leaseduration);
if(r >= 0)
{
if(inet_pton(AF_INET, int_ip, &int_ip_addr) > 0)
{
if(h->clientaddr.s_addr != int_ip_addr.s_addr)
{
SoapError(h, 606, "Action not authorized");
/*SoapError(h, 714, "NoSuchEntryInArray");*/
ClearNameValueList(&data);
return;
}
}
}
}
r = upnp_delete_redirection(eport, protocol);
if(r < 0)
{
SoapError(h, 714, "NoSuchEntryInArray");
}
else
{
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
/* DeletePortMappingRange was added in IGD spec v2 */
static void
DeletePortMappingRange(struct upnphttp * h, const char * action, const char * ns)
{
int r = -1;
/*static const char resp[] =
"<u:DeletePortMappingRangeResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"</u:DeletePortMappingRangeResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * protocol;
const char * startport_s, * endport_s;
unsigned short startport, endport;
/*int manage;*/
unsigned short * port_list;
unsigned int i, number = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
startport_s = GetValueFromNameValueList(&data, "NewStartPort");
endport_s = GetValueFromNameValueList(&data, "NewEndPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
/*manage = atoi(GetValueFromNameValueList(&data, "NewManage"));*/
if(startport_s == NULL || endport_s == NULL || protocol == NULL ||
!is_numeric(startport_s) || !is_numeric(endport_s)) {
SoapError(h, 402, "Invalid Args");
ClearNameValueList(&data);
return;
}
startport = (unsigned short)atoi(startport_s);
endport = (unsigned short)atoi(endport_s);
/* possible errors :
606 - Action not authorized
730 - PortMappingNotFound
733 - InconsistentParameter
*/
if(startport > endport)
{
SoapError(h, 733, "InconsistentParameter");
ClearNameValueList(&data);
return;
}
syslog(LOG_INFO, "%s: deleting external ports: %hu-%hu, protocol: %s",
action, startport, endport, protocol);
port_list = upnp_get_portmappings_in_range(startport, endport,
protocol, &number);
if(number == 0)
{
SoapError(h, 730, "PortMappingNotFound");
ClearNameValueList(&data);
free(port_list);
return;
}
for(i = 0; i < number; i++)
{
r = upnp_delete_redirection(port_list[i], protocol);
syslog(LOG_INFO, "%s: deleting external port: %hu, protocol: %s: %s",
action, port_list[i], protocol, r < 0 ? "failed" : "ok");
}
free(port_list);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
ClearNameValueList(&data);
}
static void
GetGenericPortMappingEntry(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewRemoteHost>%s</NewRemoteHost>"
"<NewExternalPort>%u</NewExternalPort>"
"<NewProtocol>%s</NewProtocol>"
"<NewInternalPort>%u</NewInternalPort>"
"<NewInternalClient>%s</NewInternalClient>"
"<NewEnabled>1</NewEnabled>"
"<NewPortMappingDescription>%s</NewPortMappingDescription>"
"<NewLeaseDuration>%u</NewLeaseDuration>"
"</u:%sResponse>";
long int index = 0;
unsigned short eport, iport;
const char * m_index;
char * endptr;
char protocol[8], iaddr[32];
char desc[64];
char rhost[40];
unsigned int leaseduration = 0;
struct NameValueParserData data;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
m_index = GetValueFromNameValueList(&data, "NewPortMappingIndex");
if(!m_index)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
errno = 0; /* To distinguish success/failure after call */
index = strtol(m_index, &endptr, 10);
if((errno == ERANGE && (index == LONG_MAX || index == LONG_MIN))
|| (errno != 0 && index == 0) || (m_index == endptr))
{
/* should condition (*endptr != '\0') be also an error ? */
if(m_index == endptr)
syslog(LOG_WARNING, "%s: no digits were found in <%s>",
"GetGenericPortMappingEntry", "NewPortMappingIndex");
else
syslog(LOG_WARNING, "%s: strtol('%s'): %m",
"GetGenericPortMappingEntry", m_index);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
syslog(LOG_INFO, "%s: index=%d", action, (int)index);
rhost[0] = '\0';
r = upnp_get_redirection_infos_by_index((int)index, &eport, protocol, &iport,
iaddr, sizeof(iaddr),
desc, sizeof(desc),
rhost, sizeof(rhost),
&leaseduration);
if(r < 0)
{
SoapError(h, 713, "SpecifiedArrayIndexInvalid");
}
else
{
int bodylen;
char body[2048];
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/ rhost,
(unsigned int)eport, protocol, (unsigned int)iport, iaddr, desc,
leaseduration, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
/* GetListOfPortMappings was added in the IGD v2 specification */
static void
GetListOfPortMappings(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp_start[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewPortListing><![CDATA[";
static const char resp_end[] =
"]]></NewPortListing>"
"</u:%sResponse>";
static const char list_start[] =
"<p:PortMappingList xmlns:p=\"urn:schemas-upnp-org:gw:WANIPConnection\""
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
" xsi:schemaLocation=\"urn:schemas-upnp-org:gw:WANIPConnection"
" http://www.upnp.org/schemas/gw/WANIPConnection-v2.xsd\">";
static const char list_end[] =
"</p:PortMappingList>";
static const char entry[] =
"<p:PortMappingEntry>"
"<p:NewRemoteHost>%s</p:NewRemoteHost>"
"<p:NewExternalPort>%hu</p:NewExternalPort>"
"<p:NewProtocol>%s</p:NewProtocol>"
"<p:NewInternalPort>%hu</p:NewInternalPort>"
"<p:NewInternalClient>%s</p:NewInternalClient>"
"<p:NewEnabled>1</p:NewEnabled>"
"<p:NewDescription>%s</p:NewDescription>"
"<p:NewLeaseTime>%u</p:NewLeaseTime>"
"</p:PortMappingEntry>";
char * body;
size_t bodyalloc;
int bodylen;
int r = -1;
unsigned short iport;
char int_ip[32];
char desc[64];
char rhost[64];
unsigned int leaseduration = 0;
struct NameValueParserData data;
const char * startport_s, * endport_s;
unsigned short startport, endport;
const char * protocol;
/*int manage;*/
const char * number_s;
int number;
unsigned short * port_list;
unsigned int i, list_size = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
startport_s = GetValueFromNameValueList(&data, "NewStartPort");
endport_s = GetValueFromNameValueList(&data, "NewEndPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
/*manage_s = GetValueFromNameValueList(&data, "NewManage");*/
number_s = GetValueFromNameValueList(&data, "NewNumberOfPorts");
if(startport_s == NULL || endport_s == NULL || protocol == NULL ||
number_s == NULL || !is_numeric(number_s) ||
!is_numeric(startport_s) || !is_numeric(endport_s)) {
SoapError(h, 402, "Invalid Args");
ClearNameValueList(&data);
return;
}
startport = (unsigned short)atoi(startport_s);
endport = (unsigned short)atoi(endport_s);
/*manage = atoi(manage_s);*/
number = atoi(number_s);
if(number == 0) number = 1000; /* return up to 1000 mappings by default */
if(startport > endport)
{
SoapError(h, 733, "InconsistentParameter");
ClearNameValueList(&data);
return;
}
/*
build the PortMappingList xml document :
<p:PortMappingList xmlns:p="urn:schemas-upnp-org:gw:WANIPConnection"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:schemas-upnp-org:gw:WANIPConnection
http://www.upnp.org/schemas/gw/WANIPConnection-v2.xsd">
<p:PortMappingEntry>
<p:NewRemoteHost>202.233.2.1</p:NewRemoteHost>
<p:NewExternalPort>2345</p:NewExternalPort>
<p:NewProtocol>TCP</p:NewProtocol>
<p:NewInternalPort>2345</p:NewInternalPort>
<p:NewInternalClient>192.168.1.137</p:NewInternalClient>
<p:NewEnabled>1</p:NewEnabled>
<p:NewDescription>dooom</p:NewDescription>
<p:NewLeaseTime>345</p:NewLeaseTime>
</p:PortMappingEntry>
</p:PortMappingList>
*/
bodyalloc = 4096;
body = malloc(bodyalloc);
if(!body)
{
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
return;
}
bodylen = snprintf(body, bodyalloc, resp_start,
action, ns/*SERVICE_TYPE_WANIPC*/);
if(bodylen < 0)
{
SoapError(h, 501, "ActionFailed");
free(body);
return;
}
memcpy(body+bodylen, list_start, sizeof(list_start));
bodylen += (sizeof(list_start) - 1);
port_list = upnp_get_portmappings_in_range(startport, endport,
protocol, &list_size);
/* loop through port mappings */
for(i = 0; number > 0 && i < list_size; i++)
{
/* have a margin of 1024 bytes to store the new entry */
if((unsigned int)bodylen + 1024 > bodyalloc)
{
char * body_sav = body;
bodyalloc += 4096;
body = realloc(body, bodyalloc);
if(!body)
{
syslog(LOG_CRIT, "realloc(%p, %u) FAILED", body_sav, (unsigned)bodyalloc);
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
free(body_sav);
free(port_list);
return;
}
}
rhost[0] = '\0';
r = upnp_get_redirection_infos(port_list[i], protocol, &iport,
int_ip, sizeof(int_ip),
desc, sizeof(desc),
rhost, sizeof(rhost),
&leaseduration);
if(r == 0)
{
bodylen += snprintf(body+bodylen, bodyalloc-bodylen, entry,
rhost, port_list[i], protocol,
iport, int_ip, desc, leaseduration);
number--;
}
}
free(port_list);
port_list = NULL;
if((bodylen + sizeof(list_end) + 1024) > bodyalloc)
{
char * body_sav = body;
bodyalloc += (sizeof(list_end) + 1024);
body = realloc(body, bodyalloc);
if(!body)
{
syslog(LOG_CRIT, "realloc(%p, %u) FAILED", body_sav, (unsigned)bodyalloc);
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
free(body_sav);
return;
}
}
memcpy(body+bodylen, list_end, sizeof(list_end));
bodylen += (sizeof(list_end) - 1);
bodylen += snprintf(body+bodylen, bodyalloc-bodylen, resp_end,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
free(body);
ClearNameValueList(&data);
}
#ifdef ENABLE_L3F_SERVICE
static void
SetDefaultConnectionService(struct upnphttp * h, const char * action, const char * ns)
{
/*static const char resp[] =
"<u:SetDefaultConnectionServiceResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:Layer3Forwarding:1\">"
"</u:SetDefaultConnectionServiceResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * p;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
p = GetValueFromNameValueList(&data, "NewDefaultConnectionService");
if(p) {
/* 720 InvalidDeviceUUID
* 721 InvalidServiceID
* 723 InvalidConnServiceSelection */
#ifdef UPNP_STRICT
char * service;
service = strchr(p, ',');
if(0 != memcmp(uuidvalue_wcd, p, sizeof("uuid:00000000-0000-0000-0000-000000000000") - 1)) {
SoapError(h, 720, "InvalidDeviceUUID");
} else if(service == NULL || 0 != strcmp(service+1, SERVICE_ID_WANIPC)) {
SoapError(h, 721, "InvalidServiceID");
} else
#endif
{
syslog(LOG_INFO, "%s(%s) : Ignored", action, p);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
} else {
/* missing argument */
SoapError(h, 402, "Invalid Args");
}
ClearNameValueList(&data);
}
static void
GetDefaultConnectionService(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
#ifdef IGD_V2
"<NewDefaultConnectionService>%s:WANConnectionDevice:2,"
#else
"<NewDefaultConnectionService>%s:WANConnectionDevice:1,"
#endif
SERVICE_ID_WANIPC "</NewDefaultConnectionService>"
"</u:%sResponse>";
/* example from UPnP_IGD_Layer3Forwarding 1.0.pdf :
* uuid:44f5824f-c57d-418c-a131-f22b34e14111:WANConnectionDevice:1,
* urn:upnp-org:serviceId:WANPPPConn1 */
char body[1024];
int bodylen;
/* namespace : urn:schemas-upnp-org:service:Layer3Forwarding:1 */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, uuidvalue_wcd, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
/* Added for compliance with WANIPConnection v2 */
static void
SetConnectionType(struct upnphttp * h, const char * action, const char * ns)
{
#ifdef UPNP_STRICT
const char * connection_type;
#endif /* UPNP_STRICT */
struct NameValueParserData data;
UNUSED(action);
UNUSED(ns);
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
#ifdef UPNP_STRICT
connection_type = GetValueFromNameValueList(&data, "NewConnectionType");
if(!connection_type) {
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#endif /* UPNP_STRICT */
/* Unconfigured, IP_Routed, IP_Bridged */
ClearNameValueList(&data);
/* always return a ReadOnly error */
SoapError(h, 731, "ReadOnly");
}
/* Added for compliance with WANIPConnection v2 */
static void
RequestConnection(struct upnphttp * h, const char * action, const char * ns)
{
UNUSED(action);
UNUSED(ns);
SoapError(h, 606, "Action not authorized");
}
/* Added for compliance with WANIPConnection v2 */
static void
ForceTermination(struct upnphttp * h, const char * action, const char * ns)
{
UNUSED(action);
UNUSED(ns);
SoapError(h, 606, "Action not authorized");
}
/*
If a control point calls QueryStateVariable on a state variable that is not
buffered in memory within (or otherwise available from) the service,
the service must return a SOAP fault with an errorCode of 404 Invalid Var.
QueryStateVariable remains useful as a limited test tool but may not be
part of some future versions of UPnP.
*/
static void
QueryStateVariable(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<return>%s</return>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * var_name;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
/*var_name = GetValueFromNameValueList(&data, "QueryStateVariable"); */
/*var_name = GetValueFromNameValueListIgnoreNS(&data, "varName");*/
var_name = GetValueFromNameValueList(&data, "varName");
/*syslog(LOG_INFO, "QueryStateVariable(%.40s)", var_name); */
if(!var_name)
{
SoapError(h, 402, "Invalid Args");
}
else if(strcmp(var_name, "ConnectionStatus") == 0)
{
const char * status;
status = get_wan_connection_status_str(ext_if_name);
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:control-1-0",*/
status, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#if 0
/* not useful */
else if(strcmp(var_name, "ConnectionType") == 0)
{
bodylen = snprintf(body, sizeof(body), resp, "IP_Routed");
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else if(strcmp(var_name, "LastConnectionError") == 0)
{
bodylen = snprintf(body, sizeof(body), resp, "ERROR_NONE");
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
else if(strcmp(var_name, "PortMappingNumberOfEntries") == 0)
{
char strn[10];
snprintf(strn, sizeof(strn), "%i",
upnp_get_portmapping_number_of_entries());
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:control-1-0",*/
strn, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else
{
syslog(LOG_NOTICE, "%s: Unknown: %s", action, var_name?var_name:"");
SoapError(h, 404, "Invalid Var");
}
ClearNameValueList(&data);
}
#ifdef ENABLE_6FC_SERVICE
#ifndef ENABLE_IPV6
#error "ENABLE_6FC_SERVICE needs ENABLE_IPV6"
#endif
/* WANIPv6FirewallControl actions */
static void
GetFirewallStatus(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<FirewallEnabled>%d</FirewallEnabled>"
"<InboundPinholeAllowed>%d</InboundPinholeAllowed>"
"</u:%sResponse>";
char body[512];
int bodylen;
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1",*/
GETFLAG(IPV6FCFWDISABLEDMASK) ? 0 : 1,
GETFLAG(IPV6FCINBOUNDDISALLOWEDMASK) ? 0 : 1,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static int
CheckStatus(struct upnphttp * h)
{
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return 0;
}
else if(GETFLAG(IPV6FCINBOUNDDISALLOWEDMASK))
{
SoapError(h, 703, "InboundPinholeNotAllowed");
return 0;
}
else
return 1;
}
#if 0
static int connecthostport(const char * host, unsigned short port, char * result)
{
int s, n;
char hostname[INET6_ADDRSTRLEN];
char port_str[8], ifname[8], tmp[4];
struct addrinfo *ai, *p;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
/* hints.ai_flags = AI_ADDRCONFIG; */
#ifdef AI_NUMERICSERV
hints.ai_flags = AI_NUMERICSERV;
#endif
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC; /* AF_INET, AF_INET6 or AF_UNSPEC */
/* hints.ai_protocol = IPPROTO_TCP; */
snprintf(port_str, sizeof(port_str), "%hu", port);
strcpy(hostname, host);
if(!strncmp(host, "fe80", 4))
{
printf("Using an linklocal address\n");
strcpy(ifname, "%");
snprintf(tmp, sizeof(tmp), "%d", linklocal_index);
strcat(ifname, tmp);
strcat(hostname, ifname);
printf("host: %s\n", hostname);
}
n = getaddrinfo(hostname, port_str, &hints, &ai);
if(n != 0)
{
fprintf(stderr, "getaddrinfo() error : %s\n", gai_strerror(n));
return -1;
}
s = -1;
for(p = ai; p; p = p->ai_next)
{
#ifdef DEBUG
char tmp_host[256];
char tmp_service[256];
printf("ai_family=%d ai_socktype=%d ai_protocol=%d ai_addrlen=%d\n ",
p->ai_family, p->ai_socktype, p->ai_protocol, p->ai_addrlen);
getnameinfo(p->ai_addr, p->ai_addrlen, tmp_host, sizeof(tmp_host),
tmp_service, sizeof(tmp_service),
NI_NUMERICHOST | NI_NUMERICSERV);
printf(" host=%s service=%s\n", tmp_host, tmp_service);
#endif
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr), result, INET6_ADDRSTRLEN);
return 0;
}
freeaddrinfo(ai);
}
#endif
/* Check the security policy right */
static int
PinholeVerification(struct upnphttp * h, char * int_ip, unsigned short int_port)
{
int n;
char senderAddr[INET6_ADDRSTRLEN]="";
struct addrinfo hints, *ai, *p;
struct in6_addr result_ip;
/* Pinhole InternalClient address must correspond to the action sender */
syslog(LOG_INFO, "Checking internal IP@ and port (Security policy purpose)");
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET6, int_ip, &result_ip) <= 0)
{
n = getaddrinfo(int_ip, NULL, &hints, &ai);
if(!n && ai->ai_family == AF_INET6)
{
for(p = ai; p; p = p->ai_next)
{
inet_ntop(AF_INET6, (struct in6_addr *) p, int_ip, sizeof(struct in6_addr));
result_ip = *((struct in6_addr *) p);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
SoapError(h, 402, "Invalid Args");
return -1;
}
freeaddrinfo(p);
}
if(inet_ntop(AF_INET6, &(h->clientaddr_v6), senderAddr, INET6_ADDRSTRLEN) == NULL)
{
syslog(LOG_ERR, "inet_ntop: %m");
}
#ifdef DEBUG
printf("\tPinholeVerification:\n\t\tCompare sender @: %s\n\t\t to intClient @: %s\n", senderAddr, int_ip);
#endif
if(strcmp(senderAddr, int_ip) != 0)
if(h->clientaddr_v6.s6_addr != result_ip.s6_addr)
{
syslog(LOG_INFO, "Client %s tried to access pinhole for internal %s and is not authorized to do it",
senderAddr, int_ip);
SoapError(h, 606, "Action not authorized");
return 0;
}
/* Pinhole InternalPort must be greater than or equal to 1024 */
if (int_port < 1024)
{
syslog(LOG_INFO, "Client %s tried to access pinhole with port < 1024 and is not authorized to do it",
senderAddr);
SoapError(h, 606, "Action not authorized");
return 0;
}
return 1;
}
static void
AddPinhole(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<UniqueID>%d</UniqueID>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * rem_host, * rem_port, * int_ip, * int_port, * protocol, * leaseTime;
int uid = 0;
unsigned short iport, rport;
int ltime;
long proto;
char rem_ip[INET6_ADDRSTRLEN];
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
protocol = GetValueFromNameValueList(&data, "Protocol");
leaseTime = GetValueFromNameValueList(&data, "LeaseTime");
rport = (unsigned short)(rem_port ? atoi(rem_port) : 0);
iport = (unsigned short)(int_port ? atoi(int_port) : 0);
ltime = leaseTime ? atoi(leaseTime) : -1;
errno = 0;
proto = protocol ? strtol(protocol, NULL, 0) : -1;
if(errno != 0 || proto > 65535 || proto < 0)
{
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
}
if(iport == 0)
{
SoapError(h, 706, "InternalPortWilcardingNotAllowed");
goto clear_and_exit;
}
/* In particular, [IGD2] RECOMMENDS that unauthenticated and
* unauthorized control points are only allowed to invoke
* this action with:
* - InternalPort value greater than or equal to 1024,
* - InternalClient value equals to the control point's IP address.
* It is REQUIRED that InternalClient cannot be one of IPv6
* addresses used by the gateway. */
if(!int_ip || int_ip[0] == '\0' || 0 == strcmp(int_ip, "*"))
{
SoapError(h, 708, "WildCardNotPermittedInSrcIP");
goto clear_and_exit;
}
/* I guess it is useless to convert int_ip to literal ipv6 address */
if(rem_host)
{
/* trim */
while(isspace(rem_host[0]))
rem_host++;
}
/* rem_host should be converted to literal ipv6 : */
if(rem_host && (rem_host[0] != '\0') && (rem_host[0] != '*'))
{
struct addrinfo *ai, *p;
struct addrinfo hints;
int err;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET6;
/*hints.ai_flags = */
/* hints.ai_protocol = proto; */
err = getaddrinfo(rem_host, rem_port, &hints, &ai);
if(err == 0)
{
/* take the 1st IPv6 address */
for(p = ai; p; p = p->ai_next)
{
if(p->ai_family == AF_INET6)
{
inet_ntop(AF_INET6,
&(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr),
rem_ip, sizeof(rem_ip));
syslog(LOG_INFO, "resolved '%s' to '%s'", rem_host, rem_ip);
rem_host = rem_ip;
break;
}
}
freeaddrinfo(ai);
}
else
{
syslog(LOG_WARNING, "AddPinhole : getaddrinfo(%s) : %s",
rem_host, gai_strerror(err));
#if 0
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
#endif
}
}
if(proto == 65535)
{
SoapError(h, 707, "ProtocolWilcardingNotAllowed");
goto clear_and_exit;
}
if(proto != IPPROTO_UDP && proto != IPPROTO_TCP
#ifdef IPPROTO_UDPITE
&& atoi(protocol) != IPPROTO_UDPLITE
#endif
)
{
SoapError(h, 705, "ProtocolNotSupported");
goto clear_and_exit;
}
if(ltime < 1 || ltime > 86400)
{
syslog(LOG_WARNING, "%s: LeaseTime=%d not supported, (ip=%s)",
action, ltime, int_ip);
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
}
if(PinholeVerification(h, int_ip, iport) <= 0)
goto clear_and_exit;
syslog(LOG_INFO, "%s: (inbound) from [%s]:%hu to [%s]:%hu with proto %ld during %d sec",
action, rem_host?rem_host:"any",
rport, int_ip, iport,
proto, ltime);
/* In cases where the RemoteHost, RemotePort, InternalPort,
* InternalClient and Protocol are the same than an existing pinhole,
* but LeaseTime is different, the device MUST extend the existing
* pinhole's lease time and return the UniqueID of the existing pinhole. */
r = upnp_add_inboundpinhole(rem_host, rport, int_ip, iport, proto, "IGD2 pinhole", ltime, &uid);
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body),
resp, action,
ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
uid, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -1: /* not permitted */
SoapError(h, 701, "PinholeSpaceExhausted");
break;
default:
SoapError(h, 501, "ActionFailed");
break;
}
/* 606 Action not authorized
* 701 PinholeSpaceExhausted
* 702 FirewallDisabled
* 703 InboundPinholeNotAllowed
* 705 ProtocolNotSupported
* 706 InternalPortWildcardingNotAllowed
* 707 ProtocolWildcardingNotAllowed
* 708 WildCardNotPermittedInSrcIP */
clear_and_exit:
ClearNameValueList(&data);
}
static void
UpdatePinhole(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:UpdatePinholeResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\">"
"</u:UpdatePinholeResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str, * leaseTime;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
int ltime;
int uid;
int n;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
leaseTime = GetValueFromNameValueList(&data, "NewLeaseTime");
uid = uid_str ? atoi(uid_str) : -1;
ltime = leaseTime ? atoi(leaseTime) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535 || ltime <= 0 || ltime > 86400)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not updating an pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
NULL, /* proto */
NULL, 0, /* desc, desclen */
NULL, NULL);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return;
}
else if(n == -2)
{
SoapError(h, 704, "NoSuchEntry");
return;
}
else
{
SoapError(h, 501, "ActionFailed");
return;
}
syslog(LOG_INFO, "%s: (inbound) updating lease duration to %d for pinhole with ID: %d",
action, ltime, uid);
n = upnp_update_inboundpinhole(uid, ltime);
if(n == -1)
SoapError(h, 704, "NoSuchEntry");
else if(n < 0)
SoapError(h, 501, "ActionFailed");
else {
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
}
static void
GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
static void
DeletePinhole(struct upnphttp * h, const char * action, const char * ns)
{
int n;
#if 0
static const char resp[] =
"<u:DeletePinholeResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\">"
"</u:DeletePinholeResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str;
char iaddr[INET6_ADDRSTRLEN];
int proto;
unsigned short iport;
unsigned int leasetime;
int uid;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not deleting an pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
&proto,
NULL, 0, /* desc, desclen */
&leasetime, NULL);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return;
}
else if(n == -2)
{
SoapError(h, 704, "NoSuchEntry");
return;
}
else
{
SoapError(h, 501, "ActionFailed");
return;
}
n = upnp_delete_inboundpinhole(uid);
if(n < 0)
{
syslog(LOG_INFO, "%s: (inbound) failed to remove pinhole with ID: %d",
action, uid);
SoapError(h, 501, "ActionFailed");
return;
}
syslog(LOG_INFO, "%s: (inbound) pinhole with ID %d successfully removed",
action, uid);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
CheckPinholeWorking(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<IsWorking>%d</IsWorking>"
"</u:%sResponse>";
char body[512];
int bodylen;
int r;
struct NameValueParserData data;
const char * uid_str;
int uid;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
unsigned int packets;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not checking a pinhole
* it doesn't have access to, because of its public access */
r = upnp_get_pinhole_info(uid,
NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
NULL, /* proto */
NULL, 0, /* desc, desclen */
NULL, &packets);
if (r >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return ;
if(packets == 0)
{
SoapError(h, 709, "NoPacketSent");
return;
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
1, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else if(r == -2)
SoapError(h, 704, "NoSuchEntry");
else
SoapError(h, 501, "ActionFailed");
}
static void
GetPinholePackets(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<PinholePackets>%u</PinholePackets>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str;
int n;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
unsigned int packets = 0;
int uid;
int proto;
unsigned int leasetime;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not getting infos of a pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
&proto,
NULL, 0, /* desc, desclen */
&leasetime, &packets);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport)<=0)
return ;
}
#if 0
else if(r == -4 || r == -1)
{
SoapError(h, 704, "NoSuchEntry");
}
#endif
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
packets, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
#ifdef ENABLE_DP_SERVICE
static void
SendSetupMessage(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutMessage>%s</OutMessage>"
"</u:%sResponse>";
char body[1024];
int bodylen;
struct NameValueParserData data;
const char * ProtocolType; /* string */
const char * InMessage; /* base64 */
const char * OutMessage = ""; /* base64 */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
ProtocolType = GetValueFromNameValueList(&data, "ProtocolType"); /* string */
InMessage = GetValueFromNameValueList(&data, "InMessage"); /* base64 */
if(ProtocolType == NULL || InMessage == NULL)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
/*if(strcmp(ProtocolType, "DeviceProtection:1") != 0)*/
if(strcmp(ProtocolType, "WPS") != 0)
{
ClearNameValueList(&data);
SoapError(h, 600, "Argument Value Invalid"); /* 703 ? */
return;
}
/* TODO : put here code for WPS */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
OutMessage, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
ClearNameValueList(&data);
}
static void
GetSupportedProtocols(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<ProtocolList><![CDATA[%s]]></ProtocolList>"
"</u:%sResponse>";
char body[1024];
int bodylen;
const char * ProtocolList =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<SupportedProtocols xmlns=\"urn:schemas-upnp-org:gw:DeviceProtection\""
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
" xsi:schemaLocation=\"urn:schemas-upnp-org:gw:DeviceProtection"
" http://www.upnp.org/schemas/gw/DeviceProtection-v1.xsd\">"
"<Introduction><Name>WPS</Name></Introduction>"
"<Login><Name>PKCS5</Name></Login>"
"</SupportedProtocols>";
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
ProtocolList, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetAssignedRoles(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<RoleList>%s</RoleList>"
"</u:%sResponse>";
char body[1024];
int bodylen;
const char * RoleList = "Public"; /* list of roles separated by spaces */
#ifdef ENABLE_HTTPS
if(h->ssl != NULL) {
/* we should get the Roles of the session (based on client certificate) */
X509 * peercert;
peercert = SSL_get_peer_certificate(h->ssl);
if(peercert != NULL) {
RoleList = "Admin Basic";
X509_free(peercert);
}
}
#endif
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
RoleList, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
/* Windows XP as client send the following requests :
* GetConnectionTypeInfo
* GetNATRSIPStatus
* ? GetTotalBytesSent - WANCommonInterfaceConfig
* ? GetTotalBytesReceived - idem
* ? GetTotalPacketsSent - idem
* ? GetTotalPacketsReceived - idem
* GetCommonLinkProperties - idem
* GetStatusInfo - WANIPConnection
* GetExternalIPAddress
* QueryStateVariable / ConnectionStatus!
*/
static const struct
{
const char * methodName;
void (*methodImpl)(struct upnphttp *, const char *, const char *);
}
soapMethods[] =
{
/* WANCommonInterfaceConfig */
{ "QueryStateVariable", QueryStateVariable},
{ "GetTotalBytesSent", GetTotalBytesSent},
{ "GetTotalBytesReceived", GetTotalBytesReceived},
{ "GetTotalPacketsSent", GetTotalPacketsSent},
{ "GetTotalPacketsReceived", GetTotalPacketsReceived},
{ "GetCommonLinkProperties", GetCommonLinkProperties},
{ "GetStatusInfo", GetStatusInfo},
/* WANIPConnection */
{ "GetConnectionTypeInfo", GetConnectionTypeInfo },
{ "GetNATRSIPStatus", GetNATRSIPStatus},
{ "GetExternalIPAddress", GetExternalIPAddress},
{ "AddPortMapping", AddPortMapping},
{ "DeletePortMapping", DeletePortMapping},
{ "GetGenericPortMappingEntry", GetGenericPortMappingEntry},
{ "GetSpecificPortMappingEntry", GetSpecificPortMappingEntry},
/* Required in WANIPConnection:2 */
{ "SetConnectionType", SetConnectionType},
{ "RequestConnection", RequestConnection},
{ "ForceTermination", ForceTermination},
{ "AddAnyPortMapping", AddAnyPortMapping},
{ "DeletePortMappingRange", DeletePortMappingRange},
{ "GetListOfPortMappings", GetListOfPortMappings},
#ifdef ENABLE_L3F_SERVICE
/* Layer3Forwarding */
{ "SetDefaultConnectionService", SetDefaultConnectionService},
{ "GetDefaultConnectionService", GetDefaultConnectionService},
#endif
#ifdef ENABLE_6FC_SERVICE
/* WANIPv6FirewallControl */
{ "GetFirewallStatus", GetFirewallStatus}, /* Required */
{ "AddPinhole", AddPinhole}, /* Required */
{ "UpdatePinhole", UpdatePinhole}, /* Required */
{ "GetOutboundPinholeTimeout", GetOutboundPinholeTimeout}, /* Optional */
{ "DeletePinhole", DeletePinhole}, /* Required */
{ "CheckPinholeWorking", CheckPinholeWorking}, /* Optional */
{ "GetPinholePackets", GetPinholePackets}, /* Required */
#endif
#ifdef ENABLE_DP_SERVICE
/* DeviceProtection */
{ "SendSetupMessage", SendSetupMessage}, /* Required */
{ "GetSupportedProtocols", GetSupportedProtocols}, /* Required */
{ "GetAssignedRoles", GetAssignedRoles}, /* Required */
#endif
{ 0, 0 }
};
void
ExecuteSoapAction(struct upnphttp * h, const char * action, int n)
{
char * p;
char * p2;
int i, len, methodlen;
char namespace[256];
/* SoapAction example :
* urn:schemas-upnp-org:service:WANIPConnection:1#GetStatusInfo */
p = strchr(action, '#');
if(p && (p - action) < n) {
for(i = 0; i < ((int)sizeof(namespace) - 1) && (action + i) < p; i++)
namespace[i] = action[i];
namespace[i] = '\0';
p++;
p2 = strchr(p, '"');
if(p2 && (p2 - action) <= n)
methodlen = p2 - p;
else
methodlen = n - (p - action);
/*syslog(LOG_DEBUG, "SoapMethod: %.*s %d %d %p %p %d",
methodlen, p, methodlen, n, action, p, (int)(p - action));*/
for(i = 0; soapMethods[i].methodName; i++) {
len = strlen(soapMethods[i].methodName);
if((len == methodlen) && memcmp(p, soapMethods[i].methodName, len) == 0) {
#ifdef DEBUG
syslog(LOG_DEBUG, "Remote Call of SoapMethod '%s' %s",
soapMethods[i].methodName, namespace);
#endif /* DEBUG */
soapMethods[i].methodImpl(h, soapMethods[i].methodName, namespace);
return;
}
}
syslog(LOG_NOTICE, "SoapMethod: Unknown: %.*s %s", methodlen, p, namespace);
} else {
syslog(LOG_NOTICE, "cannot parse SoapAction");
}
SoapError(h, 401, "Invalid Action");
}
/* Standard Errors:
*
* errorCode errorDescription Description
* -------- ---------------- -----------
* 401 Invalid Action No action by that name at this service.
* 402 Invalid Args Could be any of the following: not enough in args,
* too many in args, no in arg by that name,
* one or more in args are of the wrong data type.
* 403 Out of Sync Out of synchronization.
* 501 Action Failed May be returned in current state of service
* prevents invoking that action.
* 600-699 TBD Common action errors. Defined by UPnP Forum
* Technical Committee.
* 700-799 TBD Action-specific errors for standard actions.
* Defined by UPnP Forum working committee.
* 800-899 TBD Action-specific errors for non-standard actions.
* Defined by UPnP vendor.
*/
void
SoapError(struct upnphttp * h, int errCode, const char * errDesc)
{
static const char resp[] =
"<s:Envelope "
"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body>"
"<s:Fault>"
"<faultcode>s:Client</faultcode>"
"<faultstring>UPnPError</faultstring>"
"<detail>"
"<UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">"
"<errorCode>%d</errorCode>"
"<errorDescription>%s</errorDescription>"
"</UPnPError>"
"</detail>"
"</s:Fault>"
"</s:Body>"
"</s:Envelope>";
char body[2048];
int bodylen;
syslog(LOG_INFO, "Returning UPnPError %d: %s", errCode, errDesc);
bodylen = snprintf(body, sizeof(body), resp, errCode, errDesc);
BuildResp2_upnphttp(h, 500, "Internal Server Error", body, bodylen);
SendRespAndClose_upnphttp(h);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_862_0 |
crossvul-cpp_data_good_3198_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X X CCCC FFFFF %
% X X C F %
% X C FFF %
% X X C F %
% X X CCCC F %
% %
% %
% Read GIMP XCF Image Format %
% %
% Software Design %
% Leonard Rosenthol %
% November 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 %
% %
% 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/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/composite.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.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Typedef declarations.
*/
typedef enum
{
GIMP_RGB,
GIMP_GRAY,
GIMP_INDEXED
} GimpImageBaseType;
typedef enum
{
PROP_END = 0,
PROP_COLORMAP = 1,
PROP_ACTIVE_LAYER = 2,
PROP_ACTIVE_CHANNEL = 3,
PROP_SELECTION = 4,
PROP_FLOATING_SELECTION = 5,
PROP_OPACITY = 6,
PROP_MODE = 7,
PROP_VISIBLE = 8,
PROP_LINKED = 9,
PROP_PRESERVE_TRANSPARENCY = 10,
PROP_APPLY_MASK = 11,
PROP_EDIT_MASK = 12,
PROP_SHOW_MASK = 13,
PROP_SHOW_MASKED = 14,
PROP_OFFSETS = 15,
PROP_COLOR = 16,
PROP_COMPRESSION = 17,
PROP_GUIDES = 18,
PROP_RESOLUTION = 19,
PROP_TATTOO = 20,
PROP_PARASITES = 21,
PROP_UNIT = 22,
PROP_PATHS = 23,
PROP_USER_UNIT = 24
} PropType;
typedef enum
{
COMPRESS_NONE = 0,
COMPRESS_RLE = 1,
COMPRESS_ZLIB = 2, /* unused */
COMPRESS_FRACTAL = 3 /* unused */
} XcfCompressionType;
typedef struct
{
size_t
width,
height,
image_type,
bytes_per_pixel;
int
compression;
size_t
file_size;
size_t
number_layers;
ExceptionInfo
*exception;
} XCFDocInfo;
typedef struct
{
char
name[1024];
unsigned int
active;
size_t
width,
height,
type,
alpha,
visible,
linked,
preserve_trans,
apply_mask,
show_mask,
edit_mask,
floating_offset;
ssize_t
offset_x,
offset_y;
size_t
mode,
tattoo;
Image
*image;
} XCFLayerInfo;
#define TILE_WIDTH 64
#define TILE_HEIGHT 64
typedef struct
{
unsigned char
red,
green,
blue,
alpha;
} XCFPixelPacket;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s X C F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsXCF() returns MagickTrue if the image format type, identified by the
% magick string, is XCF (GIMP native format).
%
% The format of the IsXCF method is:
%
% MagickBooleanType IsXCF(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 IsXCF(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"gimp xcf",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
typedef enum
{
GIMP_NORMAL_MODE,
GIMP_DISSOLVE_MODE,
GIMP_BEHIND_MODE,
GIMP_MULTIPLY_MODE,
GIMP_SCREEN_MODE,
GIMP_OVERLAY_MODE,
GIMP_DIFFERENCE_MODE,
GIMP_ADDITION_MODE,
GIMP_SUBTRACT_MODE,
GIMP_DARKEN_ONLY_MODE,
GIMP_LIGHTEN_ONLY_MODE,
GIMP_HUE_MODE,
GIMP_SATURATION_MODE,
GIMP_COLOR_MODE,
GIMP_VALUE_MODE,
GIMP_DIVIDE_MODE,
GIMP_DODGE_MODE,
GIMP_BURN_MODE,
GIMP_HARDLIGHT_MODE
} GimpLayerModeEffects;
/*
Simple utility routine to convert between PSD blending modes and
ImageMagick compositing operators
*/
static CompositeOperator GIMPBlendModeToCompositeOperator(
size_t blendMode)
{
switch ( blendMode )
{
case GIMP_NORMAL_MODE: return(OverCompositeOp);
case GIMP_DISSOLVE_MODE: return(DissolveCompositeOp);
case GIMP_MULTIPLY_MODE: return(MultiplyCompositeOp);
case GIMP_SCREEN_MODE: return(ScreenCompositeOp);
case GIMP_OVERLAY_MODE: return(OverlayCompositeOp);
case GIMP_DIFFERENCE_MODE: return(DifferenceCompositeOp);
case GIMP_ADDITION_MODE: return(AddCompositeOp);
case GIMP_SUBTRACT_MODE: return(SubtractCompositeOp);
case GIMP_DARKEN_ONLY_MODE: return(DarkenCompositeOp);
case GIMP_LIGHTEN_ONLY_MODE: return(LightenCompositeOp);
case GIMP_HUE_MODE: return(HueCompositeOp);
case GIMP_SATURATION_MODE: return(SaturateCompositeOp);
case GIMP_COLOR_MODE: return(ColorizeCompositeOp);
case GIMP_DODGE_MODE: return(ColorDodgeCompositeOp);
case GIMP_BURN_MODE: return(ColorBurnCompositeOp);
case GIMP_HARDLIGHT_MODE: return(HardLightCompositeOp);
case GIMP_DIVIDE_MODE: return(DivideCompositeOp);
/* these are the ones we don't support...yet */
case GIMP_BEHIND_MODE: return(OverCompositeOp);
case GIMP_VALUE_MODE: return(OverCompositeOp);
default: return(OverCompositeOp);
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e a d B l o b S t r i n g W i t h L o n g S i z e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadBlobStringWithLongSize reads characters from a blob or file
% starting with a ssize_t length byte and then characters to that length
%
% The format of the ReadBlobStringWithLongSize method is:
%
% char *ReadBlobStringWithLongSize(Image *image,char *string)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o string: the address of a character buffer.
%
*/
static char *ReadBlobStringWithLongSize(Image *image,char *string,size_t max)
{
int
c;
MagickOffsetType
offset;
register ssize_t
i;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
assert(max != 0);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=ReadBlobMSBLong(image);
for (i=0; i < (ssize_t) MagickMin(length,max-1); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
return((char *) NULL);
string[i]=(char) c;
}
string[i]='\0';
offset=SeekBlob(image,(MagickOffsetType) (length-i),SEEK_CUR);
if (offset < 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,"ImproperImageHeader","`%s'",image->filename);
return(string);
}
static MagickBooleanType load_tile(Image *image,Image *tile_image,
XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length)
{
ExceptionInfo
*exception;
ssize_t
y;
register ssize_t
x;
register PixelPacket
*q;
size_t
extent;
ssize_t
count;
unsigned char
*graydata;
XCFPixelPacket
*xcfdata,
*xcfodata;
extent=0;
if (inDocInfo->image_type == GIMP_GRAY)
extent=tile_image->columns*tile_image->rows*sizeof(*graydata);
else
if (inDocInfo->image_type == GIMP_RGB)
extent=tile_image->columns*tile_image->rows*sizeof(*xcfdata);
if (extent > data_length)
ThrowBinaryException(CorruptImageError,"NotEnoughPixelData",
image->filename);
xcfdata=(XCFPixelPacket *) AcquireQuantumMemory(MagickMax(data_length,
tile_image->columns*tile_image->rows),sizeof(*xcfdata));
if (xcfdata == (XCFPixelPacket *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
xcfodata=xcfdata;
graydata=(unsigned char *) xcfdata; /* used by gray and indexed */
count=ReadBlob(image,data_length,(unsigned char *) xcfdata);
if (count != (ssize_t) data_length)
ThrowBinaryException(CorruptImageError,"NotEnoughPixelData",
image->filename);
exception=(&image->exception);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (inDocInfo->image_type == GIMP_GRAY)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*graydata));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
inLayerInfo->alpha));
graydata++;
q++;
}
}
else
if (inDocInfo->image_type == GIMP_RGB)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(xcfdata->red));
SetPixelGreen(q,ScaleCharToQuantum(xcfdata->green));
SetPixelBlue(q,ScaleCharToQuantum(xcfdata->blue));
SetPixelAlpha(q,xcfdata->alpha == 255U ? TransparentOpacity :
ScaleCharToQuantum((unsigned char) inLayerInfo->alpha));
xcfdata++;
q++;
}
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
}
xcfodata=(XCFPixelPacket *) RelinquishMagickMemory(xcfodata);
return MagickTrue;
}
static MagickBooleanType load_tile_rle(Image *image,Image *tile_image,
XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length)
{
ExceptionInfo
*exception;
MagickOffsetType
size;
Quantum
alpha;
register PixelPacket
*q;
size_t
length;
ssize_t
bytes_per_pixel,
count,
i,
j;
unsigned char
data,
pixel,
*xcfdata,
*xcfodata,
*xcfdatalimit;
bytes_per_pixel=(ssize_t) inDocInfo->bytes_per_pixel;
xcfdata=(unsigned char *) AcquireQuantumMemory(data_length,sizeof(*xcfdata));
if (xcfdata == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
xcfodata=xcfdata;
count=ReadBlob(image, (size_t) data_length, xcfdata);
xcfdatalimit = xcfodata+count-1;
exception=(&image->exception);
alpha=ScaleCharToQuantum((unsigned char) inLayerInfo->alpha);
for (i=0; i < (ssize_t) bytes_per_pixel; i++)
{
q=GetAuthenticPixels(tile_image,0,0,tile_image->columns,tile_image->rows,
exception);
if (q == (PixelPacket *) NULL)
continue;
size=(MagickOffsetType) tile_image->rows*tile_image->columns;
while (size > 0)
{
if (xcfdata > xcfdatalimit)
goto bogus_rle;
pixel=(*xcfdata++);
length=(size_t) pixel;
if (length >= 128)
{
length=255-(length-1);
if (length == 128)
{
if (xcfdata >= xcfdatalimit)
goto bogus_rle;
length=(size_t) ((*xcfdata << 8) + xcfdata[1]);
xcfdata+=2;
}
size-=length;
if (size < 0)
goto bogus_rle;
if (&xcfdata[length-1] > xcfdatalimit)
goto bogus_rle;
while (length-- > 0)
{
data=(*xcfdata++);
switch (i)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum(data));
if (inDocInfo->image_type == GIMP_GRAY)
{
SetPixelGreen(q,ScaleCharToQuantum(data));
SetPixelBlue(q,ScaleCharToQuantum(data));
}
else
{
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
}
SetPixelAlpha(q,alpha);
break;
}
case 1:
{
if (inDocInfo->image_type == GIMP_GRAY)
SetPixelAlpha(q,ScaleCharToQuantum(data));
else
SetPixelGreen(q,ScaleCharToQuantum(data));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum(data));
break;
}
case 3:
{
SetPixelAlpha(q,ScaleCharToQuantum(data));
break;
}
}
q++;
}
}
else
{
length+=1;
if (length == 128)
{
if (xcfdata >= xcfdatalimit)
goto bogus_rle;
length=(size_t) ((*xcfdata << 8) + xcfdata[1]);
xcfdata+=2;
}
size-=length;
if (size < 0)
goto bogus_rle;
if (xcfdata > xcfdatalimit)
goto bogus_rle;
pixel=(*xcfdata++);
for (j=0; j < (ssize_t) length; j++)
{
data=pixel;
switch (i)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum(data));
if (inDocInfo->image_type == GIMP_GRAY)
{
SetPixelGreen(q,ScaleCharToQuantum(data));
SetPixelBlue(q,ScaleCharToQuantum(data));
}
else
{
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
}
SetPixelAlpha(q,alpha);
break;
}
case 1:
{
if (inDocInfo->image_type == GIMP_GRAY)
SetPixelAlpha(q,ScaleCharToQuantum(data));
else
SetPixelGreen(q,ScaleCharToQuantum(data));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum(data));
break;
}
case 3:
{
SetPixelAlpha(q,ScaleCharToQuantum(data));
break;
}
}
q++;
}
}
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
}
xcfodata=(unsigned char *) RelinquishMagickMemory(xcfodata);
return(MagickTrue);
bogus_rle:
if (xcfodata != (unsigned char *) NULL)
xcfodata=(unsigned char *) RelinquishMagickMemory(xcfodata);
return(MagickFalse);
}
static MagickBooleanType load_level(Image *image,XCFDocInfo *inDocInfo,
XCFLayerInfo *inLayerInfo)
{
ExceptionInfo
*exception;
int
destLeft = 0,
destTop = 0;
Image*
tile_image;
MagickBooleanType
status;
MagickOffsetType
saved_pos,
offset,
offset2;
register ssize_t
i;
size_t
width,
height,
ntiles,
ntile_rows,
ntile_cols,
tile_image_width,
tile_image_height;
/* start reading the data */
exception=inDocInfo->exception;
width=ReadBlobMSBLong(image);
height=ReadBlobMSBLong(image);
/*
Read in the first tile offset. If it is '0', then this tile level is empty
and we can simply return.
*/
offset=(MagickOffsetType) ReadBlobMSBLong(image);
if (offset == 0)
return(MagickTrue);
/*
Initialize the reference for the in-memory tile-compression.
*/
ntile_rows=(height+TILE_HEIGHT-1)/TILE_HEIGHT;
ntile_cols=(width+TILE_WIDTH-1)/TILE_WIDTH;
ntiles=ntile_rows*ntile_cols;
for (i = 0; i < (ssize_t) ntiles; i++)
{
status=MagickFalse;
if (offset == 0)
ThrowBinaryException(CorruptImageError,"NotEnoughTiles",image->filename);
/* save the current position as it is where the
* next tile offset is stored.
*/
saved_pos=TellBlob(image);
/* read in the offset of the next tile so we can calculate the amount
of data needed for this tile*/
offset2=(MagickOffsetType)ReadBlobMSBLong(image);
/* if the offset is 0 then we need to read in the maximum possible
allowing for negative compression */
if (offset2 == 0)
offset2=(MagickOffsetType) (offset + TILE_WIDTH * TILE_WIDTH * 4* 1.5);
/* seek to the tile offset */
if (SeekBlob(image, offset, SEEK_SET) != offset)
ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile",
image->filename);
/* allocate the image for the tile
NOTE: the last tile in a row or column may not be a full tile!
*/
tile_image_width=(size_t) (destLeft == (int) ntile_cols-1 ?
(int) width % TILE_WIDTH : TILE_WIDTH);
if (tile_image_width == 0)
tile_image_width=TILE_WIDTH;
tile_image_height = (size_t) (destTop == (int) ntile_rows-1 ?
(int) height % TILE_HEIGHT : TILE_HEIGHT);
if (tile_image_height == 0)
tile_image_height=TILE_HEIGHT;
tile_image=CloneImage(inLayerInfo->image,tile_image_width,
tile_image_height,MagickTrue,exception);
/* read in the tile */
switch (inDocInfo->compression)
{
case COMPRESS_NONE:
if (load_tile(image,tile_image,inDocInfo,inLayerInfo,(size_t) (offset2-offset)) == 0)
status=MagickTrue;
break;
case COMPRESS_RLE:
if (load_tile_rle (image,tile_image,inDocInfo,inLayerInfo,
(int) (offset2-offset)) == 0)
status=MagickTrue;
break;
case COMPRESS_ZLIB:
ThrowBinaryException(CoderError,"ZipCompressNotSupported",
image->filename)
case COMPRESS_FRACTAL:
ThrowBinaryException(CoderError,"FractalCompressNotSupported",
image->filename)
}
/* composite the tile onto the layer's image, and then destroy it */
(void) CompositeImage(inLayerInfo->image,CopyCompositeOp,tile_image,
destLeft * TILE_WIDTH,destTop*TILE_HEIGHT);
tile_image=DestroyImage(tile_image);
/* adjust tile position */
destLeft++;
if (destLeft >= (int) ntile_cols)
{
destLeft = 0;
destTop++;
}
if (status != MagickFalse)
return(MagickFalse);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
/* read in the offset of the next tile */
offset=(MagickOffsetType) ReadBlobMSBLong(image);
}
if (offset != 0)
ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename)
return(MagickTrue);
}
static MagickBooleanType load_hierarchy(Image *image,XCFDocInfo *inDocInfo,
XCFLayerInfo *inLayer)
{
MagickOffsetType
saved_pos,
offset,
junk;
size_t
width,
height,
bytes_per_pixel;
width=ReadBlobMSBLong(image);
(void) width;
height=ReadBlobMSBLong(image);
(void) height;
bytes_per_pixel=inDocInfo->bytes_per_pixel=ReadBlobMSBLong(image);
(void) bytes_per_pixel;
/* load in the levels...we make sure that the number of levels
* calculated when the TileManager was created is the same
* as the number of levels found in the file.
*/
offset=(MagickOffsetType) ReadBlobMSBLong(image); /* top level */
/* discard offsets for layers below first, if any.
*/
do
{
junk=(MagickOffsetType) ReadBlobMSBLong(image);
}
while (junk != 0);
/* save the current position as it is where the
* next level offset is stored.
*/
saved_pos=TellBlob(image);
/* seek to the level offset */
if (SeekBlob(image, offset, SEEK_SET) != offset)
ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile",
image->filename);
/* read in the level */
if (load_level (image, inDocInfo, inLayer) == 0)
return(MagickFalse);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
return(MagickTrue);
}
static void InitXCFImage(XCFLayerInfo *outLayer)
{
outLayer->image->page.x=outLayer->offset_x;
outLayer->image->page.y=outLayer->offset_y;
outLayer->image->page.width=outLayer->width;
outLayer->image->page.height=outLayer->height;
(void) SetImageProperty(outLayer->image,"label",(char *)outLayer->name);
}
static MagickBooleanType ReadOneLayer(const ImageInfo *image_info,Image* image,
XCFDocInfo* inDocInfo,XCFLayerInfo *outLayer,const ssize_t layer)
{
MagickOffsetType
offset;
unsigned int
foundPropEnd = 0;
size_t
hierarchy_offset,
layer_mask_offset;
/* clear the block! */
(void) ResetMagickMemory( outLayer, 0, sizeof( XCFLayerInfo ) );
/* read in the layer width, height, type and name */
outLayer->width = ReadBlobMSBLong(image);
outLayer->height = ReadBlobMSBLong(image);
outLayer->type = ReadBlobMSBLong(image);
(void) ReadBlobStringWithLongSize(image, outLayer->name,
sizeof(outLayer->name));
if (EOFBlob(image) != MagickFalse)
ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile",
image->filename);
/* read the layer properties! */
foundPropEnd = 0;
while ( (foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse) ) {
PropType prop_type = (PropType) ReadBlobMSBLong(image);
size_t prop_size = ReadBlobMSBLong(image);
switch (prop_type)
{
case PROP_END:
foundPropEnd = 1;
break;
case PROP_ACTIVE_LAYER:
outLayer->active = 1;
break;
case PROP_FLOATING_SELECTION:
outLayer->floating_offset = ReadBlobMSBLong(image);
break;
case PROP_OPACITY:
outLayer->alpha = ReadBlobMSBLong(image);
break;
case PROP_VISIBLE:
outLayer->visible = ReadBlobMSBLong(image);
break;
case PROP_LINKED:
outLayer->linked = ReadBlobMSBLong(image);
break;
case PROP_PRESERVE_TRANSPARENCY:
outLayer->preserve_trans = ReadBlobMSBLong(image);
break;
case PROP_APPLY_MASK:
outLayer->apply_mask = ReadBlobMSBLong(image);
break;
case PROP_EDIT_MASK:
outLayer->edit_mask = ReadBlobMSBLong(image);
break;
case PROP_SHOW_MASK:
outLayer->show_mask = ReadBlobMSBLong(image);
break;
case PROP_OFFSETS:
outLayer->offset_x = ReadBlobMSBSignedLong(image);
outLayer->offset_y = ReadBlobMSBSignedLong(image);
break;
case PROP_MODE:
outLayer->mode = ReadBlobMSBLong(image);
break;
case PROP_TATTOO:
outLayer->preserve_trans = ReadBlobMSBLong(image);
break;
case PROP_PARASITES:
{
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
ssize_t base = info->cp;
GimpParasite *p;
while (info->cp - base < prop_size)
{
p = xcf_load_parasite(info);
gimp_drawable_parasite_attach(GIMP_DRAWABLE(layer), p);
gimp_parasite_free(p);
}
if (info->cp - base != prop_size)
g_message ("Error detected while loading a layer's parasites");
*/
}
break;
default:
/* g_message ("unexpected/unknown layer property: %d (skipping)",
prop_type); */
{
int buf[16];
ssize_t amount;
/* read over it... */
while ((prop_size > 0) && (EOFBlob(image) == MagickFalse))
{
amount = (ssize_t) MagickMin(16, prop_size);
amount = ReadBlob(image, (size_t) amount, (unsigned char *) &buf);
if (!amount)
ThrowBinaryException(CorruptImageError,"CorruptImage",
image->filename);
prop_size -= (size_t) MagickMin(16, (size_t) amount);
}
}
break;
}
}
if (foundPropEnd == MagickFalse)
return(MagickFalse);
/* allocate the image for this layer */
if (image_info->number_scenes != 0)
{
ssize_t
scene;
scene=inDocInfo->number_layers-layer-1;
if (scene > (ssize_t) (image_info->scene+image_info->number_scenes-1))
{
outLayer->image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (outLayer->image == (Image *) NULL)
return(MagickFalse);
InitXCFImage(outLayer);
return(MagickTrue);
}
}
/* allocate the image for this layer */
outLayer->image=CloneImage(image,outLayer->width, outLayer->height,MagickTrue,
&image->exception);
if (outLayer->image == (Image *) NULL)
return(MagickFalse);
/* clear the image based on the layer opacity */
outLayer->image->background_color.opacity=
ScaleCharToQuantum((unsigned char) (255-outLayer->alpha));
(void) SetImageBackgroundColor(outLayer->image);
InitXCFImage(outLayer);
/* set the compositing mode */
outLayer->image->compose = GIMPBlendModeToCompositeOperator( outLayer->mode );
if ( outLayer->visible == MagickFalse )
{
/* BOGUS: should really be separate member var! */
outLayer->image->compose = NoCompositeOp;
}
/* read the hierarchy and layer mask offsets */
hierarchy_offset = ReadBlobMSBLong(image);
layer_mask_offset = ReadBlobMSBLong(image);
/* read in the hierarchy */
offset=SeekBlob(image, (MagickOffsetType) hierarchy_offset, SEEK_SET);
if (offset != (MagickOffsetType) hierarchy_offset)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,"InvalidImageHeader","`%s'",image->filename);
if (load_hierarchy (image, inDocInfo, outLayer) == 0)
return(MagickFalse);
/* read in the layer mask */
if (layer_mask_offset != 0)
{
offset=SeekBlob(image, (MagickOffsetType) layer_mask_offset, SEEK_SET);
#if 0 /* BOGUS: support layer masks! */
layer_mask = xcf_load_layer_mask (info, gimage);
if (layer_mask == 0)
goto error;
/* set the offsets of the layer_mask */
GIMP_DRAWABLE (layer_mask)->offset_x = GIMP_DRAWABLE (layer)->offset_x;
GIMP_DRAWABLE (layer_mask)->offset_y = GIMP_DRAWABLE (layer)->offset_y;
gimp_layer_add_mask (layer, layer_mask, MagickFalse);
layer->mask->apply_mask = apply_mask;
layer->mask->edit_mask = edit_mask;
layer->mask->show_mask = show_mask;
#endif
}
/* attach the floating selection... */
#if 0 /* BOGUS: we may need to read this, even if we don't support it! */
if (add_floating_sel)
{
GimpLayer *floating_sel;
floating_sel = info->floating_sel;
floating_sel_attach (floating_sel, GIMP_DRAWABLE (layer));
}
#endif
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d X C F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadXCFImage() reads a GIMP (GNU Image Manipulation Program) 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 ReadXCFImage method is:
%
% image=ReadXCFImage(image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadXCFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[14];
Image
*image;
int
foundPropEnd = 0;
MagickBooleanType
status;
MagickOffsetType
offset;
register ssize_t
i;
size_t
image_type,
length;
ssize_t
count;
XCFDocInfo
doc_info;
/*
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);
}
count=ReadBlob(image,14,(unsigned char *) magick);
if ((count != 14) ||
(LocaleNCompare((char *) magick,"gimp xcf",8) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ResetMagickMemory(&doc_info,0,sizeof(XCFDocInfo));
doc_info.exception=exception;
doc_info.width=ReadBlobMSBLong(image);
doc_info.height=ReadBlobMSBLong(image);
if ((doc_info.width > 262144) || (doc_info.height > 262144))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
doc_info.image_type=ReadBlobMSBLong(image);
/*
Initialize image attributes.
*/
image->columns=doc_info.width;
image->rows=doc_info.height;
image_type=doc_info.image_type;
doc_info.file_size=GetBlobSize(image);
image->compression=NoCompression;
image->depth=8;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image_type == GIMP_RGB)
;
else
if (image_type == GIMP_GRAY)
image->colorspace=GRAYColorspace;
else
if (image_type == GIMP_INDEXED)
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
(void) SetImageOpacity(image,OpaqueOpacity);
(void) SetImageBackgroundColor(image);
/*
Read properties.
*/
while ((foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse))
{
PropType prop_type = (PropType) ReadBlobMSBLong(image);
size_t prop_size = ReadBlobMSBLong(image);
switch (prop_type)
{
case PROP_END:
foundPropEnd=1;
break;
case PROP_COLORMAP:
{
/* Cannot rely on prop_size here--the value is set incorrectly
by some Gimp versions.
*/
size_t num_colours = ReadBlobMSBLong(image);
if (DiscardBlobBytes(image,3*num_colours) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
if (info->file_version == 0)
{
gint i;
g_message (_("XCF warning: version 0 of XCF file format\n"
"did not save indexed colormaps correctly.\n"
"Substituting grayscale map."));
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
xcf_seek_pos (info, info->cp + gimage->num_cols);
for (i = 0; i<gimage->num_cols; i++)
{
gimage->cmap[i*3+0] = i;
gimage->cmap[i*3+1] = i;
gimage->cmap[i*3+2] = i;
}
}
else
{
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
info->cp +=
xcf_read_int8 (info->fp,
(guint8*) gimage->cmap, gimage->num_cols*3);
}
*/
break;
}
case PROP_COMPRESSION:
{
doc_info.compression = ReadBlobByte(image);
if ((doc_info.compression != COMPRESS_NONE) &&
(doc_info.compression != COMPRESS_RLE) &&
(doc_info.compression != COMPRESS_ZLIB) &&
(doc_info.compression != COMPRESS_FRACTAL))
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
}
break;
case PROP_GUIDES:
{
/* just skip it - we don't care about guides */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
break;
case PROP_RESOLUTION:
{
/* float xres = (float) */ (void) ReadBlobMSBLong(image);
/* float yres = (float) */ (void) ReadBlobMSBLong(image);
/*
if (xres < GIMP_MIN_RESOLUTION || xres > GIMP_MAX_RESOLUTION ||
yres < GIMP_MIN_RESOLUTION || yres > GIMP_MAX_RESOLUTION)
{
g_message ("Warning, resolution out of range in XCF file");
xres = gimage->gimp->config->default_xresolution;
yres = gimage->gimp->config->default_yresolution;
}
*/
/* BOGUS: we don't write these yet because we aren't
reading them properly yet :(
image->x_resolution = xres;
image->y_resolution = yres;
*/
}
break;
case PROP_TATTOO:
{
/* we need to read it, even if we ignore it */
/*size_t tattoo_state = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PARASITES:
{
/* BOGUS: we may need these for IPTC stuff */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
gssize_t base = info->cp;
GimpParasite *p;
while (info->cp - base < prop_size)
{
p = xcf_load_parasite (info);
gimp_image_parasite_attach (gimage, p);
gimp_parasite_free (p);
}
if (info->cp - base != prop_size)
g_message ("Error detected while loading an image's parasites");
*/
}
break;
case PROP_UNIT:
{
/* BOGUS: ignore for now... */
/*size_t unit = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PATHS:
{
/* BOGUS: just skip it for now */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
PathList *paths = xcf_load_bzpaths (gimage, info);
gimp_image_set_paths (gimage, paths);
*/
}
break;
case PROP_USER_UNIT:
{
char unit_string[1000];
/*BOGUS: ignored for now */
/*float factor = (float) */ (void) ReadBlobMSBLong(image);
/* size_t digits = */ (void) ReadBlobMSBLong(image);
for (i=0; i<5; i++)
(void) ReadBlobStringWithLongSize(image, unit_string,
sizeof(unit_string));
}
break;
default:
{
int buf[16];
ssize_t amount;
/* read over it... */
while ((prop_size > 0) && (EOFBlob(image) == MagickFalse))
{
amount=(ssize_t) MagickMin(16, prop_size);
amount=(ssize_t) ReadBlob(image,(size_t) amount,(unsigned char *) &buf);
if (!amount)
ThrowReaderException(CorruptImageError,"CorruptImage");
prop_size -= (size_t) MagickMin(16,(size_t) amount);
}
}
break;
}
}
if (foundPropEnd == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
{
; /* do nothing, were just pinging! */
}
else
{
int
current_layer = 0,
foundAllLayers = MagickFalse,
number_layers = 0;
MagickOffsetType
oldPos=TellBlob(image);
XCFLayerInfo
*layer_info;
/*
The read pointer.
*/
do
{
ssize_t offset = ReadBlobMSBSignedLong(image);
if (offset == 0)
foundAllLayers=MagickTrue;
else
number_layers++;
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
} while (foundAllLayers == MagickFalse);
doc_info.number_layers=number_layers;
offset=SeekBlob(image,oldPos,SEEK_SET); /* restore the position! */
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* allocate our array of layer info blocks */
length=(size_t) number_layers;
layer_info=(XCFLayerInfo *) AcquireQuantumMemory(length,
sizeof(*layer_info));
if (layer_info == (XCFLayerInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(layer_info,0,number_layers*sizeof(XCFLayerInfo));
for ( ; ; )
{
MagickBooleanType
layer_ok;
MagickOffsetType
offset,
saved_pos;
/* read in the offset of the next layer */
offset=(MagickOffsetType) ReadBlobMSBLong(image);
/* if the offset is 0 then we are at the end
* of the layer list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next layer offset is stored.
*/
saved_pos=TellBlob(image);
/* seek to the layer offset */
if (SeekBlob(image,offset,SEEK_SET) != offset)
ThrowReaderException(ResourceLimitError,"NotEnoughPixelData");
/* read in the layer */
layer_ok=ReadOneLayer(image_info,image,&doc_info,
&layer_info[current_layer],current_layer);
if (layer_ok == MagickFalse)
{
int j;
for (j=0; j < current_layer; j++)
layer_info[j].image=DestroyImage(layer_info[j].image);
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
current_layer++;
}
#if 0
{
/* NOTE: XCF layers are REVERSED from composite order! */
signed int j;
for (j=number_layers-1; j>=0; j--) {
/* BOGUS: need to consider layer blending modes!! */
if ( layer_info[j].visible ) { /* only visible ones, please! */
CompositeImage(image, OverCompositeOp, layer_info[j].image,
layer_info[j].offset_x, layer_info[j].offset_y );
layer_info[j].image =DestroyImage( layer_info[j].image );
/* If we do this, we'll get REAL gray images! */
if ( image_type == GIMP_GRAY ) {
QuantizeInfo qi;
GetQuantizeInfo(&qi);
qi.colorspace = GRAYColorspace;
QuantizeImage( &qi, layer_info[j].image );
}
}
}
}
#else
{
/* NOTE: XCF layers are REVERSED from composite order! */
ssize_t j;
/* now reverse the order of the layers as they are put
into subimages
*/
for (j=(long) number_layers-1; j >= 0; j--)
AppendImageToList(&image,layer_info[j].image);
}
#endif
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
#if 0 /* BOGUS: do we need the channels?? */
while (MagickTrue)
{
/* read in the offset of the next channel */
info->cp += xcf_read_int32 (info->fp, &offset, 1);
/* if the offset is 0 then we are at the end
* of the channel list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next channel offset is stored.
*/
saved_pos = info->cp;
/* seek to the channel offset */
xcf_seek_pos (info, offset);
/* read in the layer */
channel = xcf_load_channel (info, gimage);
if (channel == 0)
goto error;
num_successful_elements++;
/* add the channel to the image if its not the selection */
if (channel != gimage->selection_mask)
gimp_image_add_channel (gimage, channel, -1);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
xcf_seek_pos (info, saved_pos);
}
#endif
}
(void) CloseBlob(image);
if (GetNextImageInList(image) != (Image *) NULL)
DestroyImage(RemoveFirstImageFromList(&image));
if (image_type == GIMP_GRAY)
image->type=GrayscaleType;
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r X C F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterXCFImage() adds attributes for the XCF 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 RegisterXCFImage method is:
%
% size_t RegisterXCFImage(void)
%
*/
ModuleExport size_t RegisterXCFImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("XCF");
entry->decoder=(DecodeImageHandler *) ReadXCFImage;
entry->magick=(IsImageFormatHandler *) IsXCF;
entry->description=ConstantString("GIMP image");
entry->module=ConstantString("XCF");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r X C F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterXCFImage() removes format registrations made by the
% XCF module from the list of supported formats.
%
% The format of the UnregisterXCFImage method is:
%
% UnregisterXCFImage(void)
%
*/
ModuleExport void UnregisterXCFImage(void)
{
(void) UnregisterMagickInfo("XCF");
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3198_0 |
crossvul-cpp_data_bad_2583_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N GGGG %
% P P NN N G %
% PPPP N N N G GG %
% P N NN G G %
% P N N GGG %
% %
% %
% Read/Write Portable Network Graphics Image Format %
% %
% Software Design %
% Cristy %
% Glenn Randers-Pehrson %
% November 1997 %
% %
% %
% 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
#define IM
/*
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/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/layer.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/MagickCore.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"
#if defined(MAGICKCORE_PNG_DELEGATE)
/* Suppress libpng pedantic warnings that were added in
* libpng-1.2.41 and libpng-1.4.0. If you are working on
* migration to libpng-1.5, remove these defines and then
* fix any code that generates warnings.
*/
/* #define PNG_DEPRECATED Use of this function is deprecated */
/* #define PNG_USE_RESULT The result of this function must be checked */
/* #define PNG_NORETURN This function does not return */
/* #define PNG_ALLOCATED The result of the function is new memory */
/* #define PNG_DEPSTRUCT Access to this struct member is deprecated */
/* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */
#define PNG_PTR_NORETURN
#include "png.h"
#include "zlib.h"
/* ImageMagick differences */
#define first_scene scene
#if PNG_LIBPNG_VER > 10011
/*
Optional declarations. Define or undefine them as you like.
*/
/* #define PNG_DEBUG -- turning this on breaks VisualC compiling */
/*
Features under construction. Define these to work on them.
*/
#undef MNG_OBJECT_BUFFERS
#undef MNG_BASI_SUPPORTED
#define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */
#define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */
#if defined(MAGICKCORE_JPEG_DELEGATE)
# define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */
#endif
#if !defined(RGBColorMatchExact)
#define IsPNGColorEqual(color,target) \
(((color).red == (target).red) && \
((color).green == (target).green) && \
((color).blue == (target).blue))
#endif
/* Table of recognized sRGB ICC profiles */
struct sRGB_info_struct
{
png_uint_32 len;
png_uint_32 crc;
png_byte intent;
};
const struct sRGB_info_struct sRGB_info[] =
{
/* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */
{ 3048, 0x3b8772b9UL, 0},
/* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */
{ 3052, 0x427ebb21UL, 1},
/* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */
{60988, 0x306fd8aeUL, 0},
/* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */
{60960, 0xbbef7812UL, 0},
/* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */
{ 3024, 0x5d5129ceUL, 1},
/* HP-Microsoft sRGB v2 perceptual */
{ 3144, 0x182ea552UL, 0},
/* HP-Microsoft sRGB v2 media-relative */
{ 3144, 0xf29e526dUL, 1},
/* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */
{ 524, 0xd4938c39UL, 0},
/* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */
{ 3212, 0x034af5a1UL, 0},
/* Not recognized */
{ 0, 0x00000000UL, 0},
};
/* Macros for left-bit-replication to ensure that pixels
* and PixelInfos all have the same image->depth, and for use
* in PNG8 quantization.
*/
/* LBR01: Replicate top bit */
#define LBR01PacketRed(pixelpacket) \
(pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketGreen(pixelpacket) \
(pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketBlue(pixelpacket) \
(pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketAlpha(pixelpacket) \
(pixelpacket).alpha=(ScaleQuantumToChar((pixelpacket).alpha) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketRGB(pixelpacket) \
{ \
LBR01PacketRed((pixelpacket)); \
LBR01PacketGreen((pixelpacket)); \
LBR01PacketBlue((pixelpacket)); \
}
#define LBR01PacketRGBO(pixelpacket) \
{ \
LBR01PacketRGB((pixelpacket)); \
LBR01PacketAlpha((pixelpacket)); \
}
#define LBR01PixelRed(pixel) \
(SetPixelRed(image, \
ScaleQuantumToChar(GetPixelRed(image,(pixel))) < 0x10 ? \
0 : QuantumRange,(pixel)));
#define LBR01PixelGreen(pixel) \
(SetPixelGreen(image, \
ScaleQuantumToChar(GetPixelGreen(image,(pixel))) < 0x10 ? \
0 : QuantumRange,(pixel)));
#define LBR01PixelBlue(pixel) \
(SetPixelBlue(image, \
ScaleQuantumToChar(GetPixelBlue(image,(pixel))) < 0x10 ? \
0 : QuantumRange,(pixel)));
#define LBR01PixelAlpha(pixel) \
(SetPixelAlpha(image, \
ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) < 0x10 ? \
0 : QuantumRange,(pixel)));
#define LBR01PixelRGB(pixel) \
{ \
LBR01PixelRed((pixel)); \
LBR01PixelGreen((pixel)); \
LBR01PixelBlue((pixel)); \
}
#define LBR01PixelRGBA(pixel) \
{ \
LBR01PixelRGB((pixel)); \
LBR01PixelAlpha((pixel)); \
}
/* LBR02: Replicate top 2 bits */
#define LBR02PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \
(pixelpacket).red=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \
(pixelpacket).green=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \
(pixelpacket).blue=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketAlpha(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xc0; \
(pixelpacket).alpha=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketRGB(pixelpacket) \
{ \
LBR02PacketRed((pixelpacket)); \
LBR02PacketGreen((pixelpacket)); \
LBR02PacketBlue((pixelpacket)); \
}
#define LBR02PacketRGBO(pixelpacket) \
{ \
LBR02PacketRGB((pixelpacket)); \
LBR02PacketAlpha((pixelpacket)); \
}
#define LBR02PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \
& 0xc0; \
SetPixelRed(image, ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \
(pixel)); \
}
#define LBR02PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\
& 0xc0; \
SetPixelGreen(image, ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \
(pixel)); \
}
#define LBR02PixelBlue(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xc0; \
SetPixelBlue(image, ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \
(pixel)); \
}
#define LBR02PixelAlpha(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xc0; \
SetPixelAlpha(image, ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \
(pixel) ); \
}
#define LBR02PixelRGB(pixel) \
{ \
LBR02PixelRed((pixel)); \
LBR02PixelGreen((pixel)); \
LBR02PixelBlue((pixel)); \
}
#define LBR02PixelRGBA(pixel) \
{ \
LBR02PixelRGB((pixel)); \
LBR02PixelAlpha((pixel)); \
}
/* LBR03: Replicate top 3 bits (only used with opaque pixels during
PNG8 quantization) */
#define LBR03PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \
(pixelpacket).red=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \
(pixelpacket).green=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \
(pixelpacket).blue=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketRGB(pixelpacket) \
{ \
LBR03PacketRed((pixelpacket)); \
LBR03PacketGreen((pixelpacket)); \
LBR03PacketBlue((pixelpacket)); \
}
#define LBR03PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \
& 0xe0; \
SetPixelRed(image, ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \
}
#define LBR03Green(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\
& 0xe0; \
SetPixelGreen(image, ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \
}
#define LBR03Blue(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue(image,(pixel))) \
& 0xe0; \
SetPixelBlue(image, ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \
}
#define LBR03RGB(pixel) \
{ \
LBR03PixelRed((pixel)); \
LBR03Green((pixel)); \
LBR03Blue((pixel)); \
}
/* LBR04: Replicate top 4 bits */
#define LBR04PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \
(pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \
(pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \
(pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketAlpha(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xf0; \
(pixelpacket).alpha=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketRGB(pixelpacket) \
{ \
LBR04PacketRed((pixelpacket)); \
LBR04PacketGreen((pixelpacket)); \
LBR04PacketBlue((pixelpacket)); \
}
#define LBR04PacketRGBO(pixelpacket) \
{ \
LBR04PacketRGB((pixelpacket)); \
LBR04PacketAlpha((pixelpacket)); \
}
#define LBR04PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \
& 0xf0; \
SetPixelRed(image,\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \
}
#define LBR04PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\
& 0xf0; \
SetPixelGreen(image,\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \
}
#define LBR04PixelBlue(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xf0; \
SetPixelBlue(image,\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \
}
#define LBR04PixelAlpha(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xf0; \
SetPixelAlpha(image,\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \
}
#define LBR04PixelRGB(pixel) \
{ \
LBR04PixelRed((pixel)); \
LBR04PixelGreen((pixel)); \
LBR04PixelBlue((pixel)); \
}
#define LBR04PixelRGBA(pixel) \
{ \
LBR04PixelRGB((pixel)); \
LBR04PixelAlpha((pixel)); \
}
/*
Establish thread safety.
setjmp/longjmp is claimed to be safe on these platforms:
setjmp/longjmp is alleged to be unsafe on these platforms:
*/
#ifdef PNG_SETJMP_SUPPORTED
# ifndef IMPNG_SETJMP_IS_THREAD_SAFE
# define IMPNG_SETJMP_NOT_THREAD_SAFE
# endif
# ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
static SemaphoreInfo
*ping_semaphore = (SemaphoreInfo *) NULL;
# endif
#endif
/*
This temporary until I set up malloc'ed object attributes array.
Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but
waste more memory.
*/
#define MNG_MAX_OBJECTS 256
/*
If this not defined, spec is interpreted strictly. If it is
defined, an attempt will be made to recover from some errors,
including
o global PLTE too short
*/
#undef MNG_LOOSE
/*
Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure
it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work
with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8,
PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in
libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here.
PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and
will be enabled by default in libpng-1.2.0.
*/
#ifdef PNG_MNG_FEATURES_SUPPORTED
# ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
# define PNG_READ_EMPTY_PLTE_SUPPORTED
# endif
# ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED
# define PNG_WRITE_EMPTY_PLTE_SUPPORTED
# endif
#endif
/*
Maximum valid size_t in PNG/MNG chunks is (2^31)-1
This macro is only defined in libpng-1.0.3 and later.
Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6
*/
#ifndef PNG_UINT_31_MAX
#define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL
#endif
/*
Constant strings for known chunk types. If you need to add a chunk,
add a string holding the name here. To make the code more
portable, we use ASCII numbers like this, not characters.
*/
static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'};
static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'};
static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'};
static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'};
static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'};
static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'};
static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'};
static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'};
static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'};
static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'};
static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'};
static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'};
static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'};
static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'};
static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'};
static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'};
static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'};
static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'};
static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'};
static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'};
static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'};
static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'};
static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'};
static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'};
static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'};
static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'};
static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'};
static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'};
static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'};
static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'};
static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'};
static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'};
#if defined(JNG_SUPPORTED)
static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'};
static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'};
static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'};
static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'};
static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'};
static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'};
#endif
#if 0
/* Other known chunks that are not yet supported by ImageMagick: */
static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'};
static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'};
static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'};
static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'};
static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'};
static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'};
static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'};
#endif
typedef struct _MngBox
{
long
left,
right,
top,
bottom;
} MngBox;
typedef struct _MngPair
{
volatile long
a,
b;
} MngPair;
#ifdef MNG_OBJECT_BUFFERS
typedef struct _MngBuffer
{
size_t
height,
width;
Image
*image;
png_color
plte[256];
int
reference_count;
unsigned char
alpha_sample_depth,
compression_method,
color_type,
concrete,
filter_method,
frozen,
image_type,
interlace_method,
pixel_sample_depth,
plte_length,
sample_depth,
viewable;
} MngBuffer;
#endif
typedef struct _MngInfo
{
#ifdef MNG_OBJECT_BUFFERS
MngBuffer
*ob[MNG_MAX_OBJECTS];
#endif
Image *
image;
RectangleInfo
page;
int
adjoin,
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
bytes_in_read_buffer,
found_empty_plte,
#endif
equal_backgrounds,
equal_chrms,
equal_gammas,
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
equal_palettes,
#endif
equal_physs,
equal_srgbs,
framing_mode,
have_global_bkgd,
have_global_chrm,
have_global_gama,
have_global_phys,
have_global_sbit,
have_global_srgb,
have_saved_bkgd_index,
have_write_global_chrm,
have_write_global_gama,
have_write_global_plte,
have_write_global_srgb,
need_fram,
object_id,
old_framing_mode,
saved_bkgd_index;
int
new_number_colors;
ssize_t
image_found,
loop_count[256],
loop_iteration[256],
scenes_found,
x_off[MNG_MAX_OBJECTS],
y_off[MNG_MAX_OBJECTS];
MngBox
clip,
frame,
image_box,
object_clip[MNG_MAX_OBJECTS];
unsigned char
/* These flags could be combined into one byte */
exists[MNG_MAX_OBJECTS],
frozen[MNG_MAX_OBJECTS],
loop_active[256],
invisible[MNG_MAX_OBJECTS],
viewable[MNG_MAX_OBJECTS];
MagickOffsetType
loop_jump[256];
png_colorp
global_plte;
png_color_8
global_sbit;
png_byte
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
read_buffer[8],
#endif
global_trns[256];
float
global_gamma;
ChromaticityInfo
global_chrm;
RenderingIntent
global_srgb_intent;
unsigned long
delay,
global_plte_length,
global_trns_length,
global_x_pixels_per_unit,
global_y_pixels_per_unit,
mng_width,
mng_height,
ticks_per_second;
MagickBooleanType
need_blob;
unsigned int
IsPalette,
global_phys_unit_type,
basi_warning,
clon_warning,
dhdr_warning,
jhdr_warning,
magn_warning,
past_warning,
phyg_warning,
phys_warning,
sbit_warning,
show_warning,
mng_type,
write_mng,
write_png_colortype,
write_png_depth,
write_png_compression_level,
write_png_compression_strategy,
write_png_compression_filter,
write_png8,
write_png24,
write_png32,
write_png48,
write_png64;
#ifdef MNG_BASI_SUPPORTED
unsigned long
basi_width,
basi_height;
unsigned int
basi_depth,
basi_color_type,
basi_compression_method,
basi_filter_type,
basi_interlace_method,
basi_red,
basi_green,
basi_blue,
basi_alpha,
basi_viewable;
#endif
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
PixelInfo
mng_global_bkgd;
/* Added at version 6.6.6-7 */
MagickBooleanType
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
ping_exclude_eXIf,
ping_exclude_EXIF,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tRNS,
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
/* Added at version 6.8.5-7 */
ping_preserve_iCCP,
/* Added at version 6.8.9-9 */
ping_exclude_tIME;
} MngInfo;
#endif /* VER */
/*
Forward declarations.
*/
static MagickBooleanType
WritePNGImage(const ImageInfo *,Image *,ExceptionInfo *);
static MagickBooleanType
WriteMNGImage(const ImageInfo *,Image *,ExceptionInfo *);
#if defined(JNG_SUPPORTED)
static MagickBooleanType
WriteJNGImage(const ImageInfo *,Image *,ExceptionInfo *);
#endif
#if PNG_LIBPNG_VER > 10011
#if (MAGICKCORE_QUANTUM_DEPTH >= 16)
static MagickBooleanType
LosslessReduceDepthOK(Image *image,ExceptionInfo *exception)
{
/* Reduce bit depth if it can be reduced losslessly from 16+ to 8.
*
* This is true if the high byte and the next highest byte of
* each sample of the image, the colormap, and the background color
* are equal to each other. We check this by seeing if the samples
* are unchanged when we scale them down to 8 and back up to Quantum.
*
* We don't use the method GetImageDepth() because it doesn't check
* background and doesn't handle PseudoClass specially.
*/
#define QuantumToCharToQuantumEqQuantum(quantum) \
((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum)
MagickBooleanType
ok_to_reduce=MagickFalse;
if (image->depth >= 16)
{
const Quantum
*p;
ok_to_reduce=
QuantumToCharToQuantumEqQuantum(image->background_color.red) &&
QuantumToCharToQuantumEqQuantum(image->background_color.green) &&
QuantumToCharToQuantumEqQuantum(image->background_color.blue) ?
MagickTrue : MagickFalse;
if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass)
{
int indx;
for (indx=0; indx < (ssize_t) image->colors; indx++)
{
ok_to_reduce=(
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].red) &&
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].green) &&
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].blue)) ?
MagickTrue : MagickFalse;
if (ok_to_reduce == MagickFalse)
break;
}
}
if ((ok_to_reduce != MagickFalse) &&
(image->storage_class != PseudoClass))
{
ssize_t
y;
register ssize_t
x;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
ok_to_reduce = MagickFalse;
break;
}
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
ok_to_reduce=
QuantumToCharToQuantumEqQuantum(GetPixelRed(image,p)) &&
QuantumToCharToQuantumEqQuantum(GetPixelGreen(image,p)) &&
QuantumToCharToQuantumEqQuantum(GetPixelBlue(image,p)) ?
MagickTrue : MagickFalse;
if (ok_to_reduce == MagickFalse)
break;
p+=GetPixelChannels(image);
}
if (x >= 0)
break;
}
}
if (ok_to_reduce != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" OK to reduce PNG bit depth to 8 without loss of info");
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Not OK to reduce PNG bit depth to 8 without losing info");
}
}
return ok_to_reduce;
}
#endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */
static const char* PngColorTypeToString(const unsigned int color_type)
{
const char
*result = "Unknown";
switch (color_type)
{
case PNG_COLOR_TYPE_GRAY:
result = "Gray";
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
result = "Gray+Alpha";
break;
case PNG_COLOR_TYPE_PALETTE:
result = "Palette";
break;
case PNG_COLOR_TYPE_RGB:
result = "RGB";
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
result = "RGB+Alpha";
break;
}
return result;
}
static int
Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent)
{
switch (intent)
{
case PerceptualIntent:
return 0;
case RelativeIntent:
return 1;
case SaturationIntent:
return 2;
case AbsoluteIntent:
return 3;
default:
return -1;
}
}
static RenderingIntent
Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent)
{
switch (ping_intent)
{
case 0:
return PerceptualIntent;
case 1:
return RelativeIntent;
case 2:
return SaturationIntent;
case 3:
return AbsoluteIntent;
default:
return UndefinedIntent;
}
}
static const char *
Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent)
{
switch (ping_intent)
{
case 0:
return "Perceptual Intent";
case 1:
return "Relative Intent";
case 2:
return "Saturation Intent";
case 3:
return "Absolute Intent";
default:
return "Undefined Intent";
}
}
static const char *
Magick_ColorType_from_PNG_ColorType(const int ping_colortype)
{
switch (ping_colortype)
{
case 0:
return "Grayscale";
case 2:
return "Truecolor";
case 3:
return "Indexed";
case 4:
return "GrayAlpha";
case 6:
return "RGBA";
default:
return "UndefinedColorType";
}
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif /* MAGICKCORE_PNG_DELEGATE */
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s M N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsMNG() returns MagickTrue if the image format type, identified by the
% magick string, is MNG.
%
% The format of the IsMNG method is:
%
% MagickBooleanType IsMNG(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 IsMNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJNG() returns MagickTrue if the image format type, identified by the
% magick string, is JNG.
%
% The format of the IsJNG method is:
%
% MagickBooleanType IsJNG(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 IsJNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNG() returns MagickTrue if the image format type, identified by the
% magick string, is PNG.
%
% The format of the IsPNG method is:
%
% MagickBooleanType IsPNG(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 IsPNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
#if defined(MAGICKCORE_PNG_DELEGATE)
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#if (PNG_LIBPNG_VER > 10011)
static size_t WriteBlobMSBULong(Image *image,const size_t value)
{
unsigned char
buffer[4];
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
buffer[0]=(unsigned char) (value >> 24);
buffer[1]=(unsigned char) (value >> 16);
buffer[2]=(unsigned char) (value >> 8);
buffer[3]=(unsigned char) value;
return((size_t) WriteBlob(image,4,buffer));
}
static void PNGLong(png_bytep p,png_uint_32 value)
{
*p++=(png_byte) ((value >> 24) & 0xff);
*p++=(png_byte) ((value >> 16) & 0xff);
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGsLong(png_bytep p,png_int_32 value)
{
*p++=(png_byte) ((value >> 24) & 0xff);
*p++=(png_byte) ((value >> 16) & 0xff);
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGShort(png_bytep p,png_uint_16 value)
{
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGType(png_bytep p,const png_byte *type)
{
(void) CopyMagickMemory(p,type,4*sizeof(png_byte));
}
static void LogPNGChunk(MagickBooleanType logging, const png_byte *type,
size_t length)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing %c%c%c%c chunk, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
}
#endif /* PNG_LIBPNG_VER > 10011 */
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#if PNG_LIBPNG_VER > 10011
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNGImage() reads a Portable Network Graphics (PNG) or
% Multiple-image Network Graphics (MNG) 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.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadPNGImage method is:
%
% Image *ReadPNGImage(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.
%
% To do, more or less in chronological order (as of version 5.5.2,
% November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage):
%
% Get 16-bit cheap transparency working.
%
% (At this point, PNG decoding is supposed to be in full MNG-LC compliance)
%
% Preserve all unknown and not-yet-handled known chunks found in input
% PNG file and copy them into output PNG files according to the PNG
% copying rules.
%
% (At this point, PNG encoding should be in full MNG compliance)
%
% Provide options for choice of background to use when the MNG BACK
% chunk is not present or is not mandatory (i.e., leave transparent,
% user specified, MNG BACK, PNG bKGD)
%
% Implement LOOP/ENDL [done, but could do discretionary loops more
% efficiently by linking in the duplicate frames.].
%
% Decode and act on the MHDR simplicity profile (offer option to reject
% files or attempt to process them anyway when the profile isn't LC or VLC).
%
% Upgrade to full MNG without Delta-PNG.
%
% o BACK [done a while ago except for background image ID]
% o MOVE [done 15 May 1999]
% o CLIP [done 15 May 1999]
% o DISC [done 19 May 1999]
% o SAVE [partially done 19 May 1999 (marks objects frozen)]
% o SEEK [partially done 19 May 1999 (discard function only)]
% o SHOW
% o PAST
% o BASI
% o MNG-level tEXt/iTXt/zTXt
% o pHYg
% o pHYs
% o sBIT
% o bKGD
% o iTXt (wait for libpng implementation).
%
% Use the scene signature to discover when an identical scene is
% being reused, and just point to the original image->exception instead
% of storing another set of pixels. This not specific to MNG
% but could be applied generally.
%
% Upgrade to full MNG with Delta-PNG.
%
% JNG tEXt/iTXt/zTXt
%
% We will not attempt to read files containing the CgBI chunk.
% They are really Xcode files meant for display on the iPhone.
% These are not valid PNG files and it is impossible to recover
% the original PNG from files that have been converted to Xcode-PNG,
% since irretrievable loss of color data has occurred due to the
% use of premultiplied alpha.
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
/*
This the function that does the actual reading of data. It is
the same as the one supplied in libpng, except that it receives the
datastream from the ReadBlob() function instead of standard input.
*/
static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
Image
*image;
image=(Image *) png_get_io_ptr(png_ptr);
if (length != 0)
{
png_size_t
check;
check=(png_size_t) ReadBlob(image,(size_t) length,data);
if (check != length)
{
char
msg[MagickPathExtent];
(void) FormatLocaleString(msg,MagickPathExtent,
"Expected %.20g bytes; found %.20g bytes",(double) length,
(double) check);
png_warning(png_ptr,msg);
png_error(png_ptr,"Read Exception");
}
}
}
#if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \
!defined(PNG_MNG_FEATURES_SUPPORTED)
/* We use mng_get_data() instead of png_get_data() if we have a libpng
* older than libpng-1.0.3a, which was the first to allow the empty
* PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was
* ifdef'ed out. Earlier versions would crash if the bKGD chunk was
* encountered after an empty PLTE, so we have to look ahead for bKGD
* chunks and remove them from the datastream that is passed to libpng,
* and store their contents for later use.
*/
static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
MngInfo
*mng_info;
Image
*image;
png_size_t
check;
register ssize_t
i;
i=0;
mng_info=(MngInfo *) png_get_io_ptr(png_ptr);
image=(Image *) mng_info->image;
while (mng_info->bytes_in_read_buffer && length)
{
data[i]=mng_info->read_buffer[i];
mng_info->bytes_in_read_buffer--;
length--;
i++;
}
if (length != 0)
{
check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data);
if (check != length)
png_error(png_ptr,"Read Exception");
if (length == 4)
{
if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) &&
(data[3] == 0))
{
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->read_buffer[4]=0;
mng_info->bytes_in_read_buffer=4;
if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0)
mng_info->found_empty_plte=MagickTrue;
if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0)
{
mng_info->found_empty_plte=MagickFalse;
mng_info->have_saved_bkgd_index=MagickFalse;
}
}
if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) &&
(data[3] == 1))
{
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->read_buffer[4]=0;
mng_info->bytes_in_read_buffer=4;
if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0)
if (mng_info->found_empty_plte)
{
/*
Skip the bKGD data byte and CRC.
*/
check=(png_size_t)
ReadBlob(image,5,(char *) mng_info->read_buffer);
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->saved_bkgd_index=mng_info->read_buffer[0];
mng_info->have_saved_bkgd_index=MagickTrue;
mng_info->bytes_in_read_buffer=0;
}
}
}
}
}
#endif
static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
Image
*image;
image=(Image *) png_get_io_ptr(png_ptr);
if (length != 0)
{
png_size_t
check;
check=(png_size_t) WriteBlob(image,(size_t) length,data);
if (check != length)
png_error(png_ptr,"WriteBlob Failed");
}
}
static void png_flush_data(png_structp png_ptr)
{
(void) png_ptr;
}
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
static int PalettesAreEqual(Image *a,Image *b)
{
ssize_t
i;
if ((a == (Image *) NULL) || (b == (Image *) NULL))
return((int) MagickFalse);
if (a->storage_class != PseudoClass || b->storage_class != PseudoClass)
return((int) MagickFalse);
if (a->colors != b->colors)
return((int) MagickFalse);
for (i=0; i < (ssize_t) a->colors; i++)
{
if ((a->colormap[i].red != b->colormap[i].red) ||
(a->colormap[i].green != b->colormap[i].green) ||
(a->colormap[i].blue != b->colormap[i].blue))
return((int) MagickFalse);
}
return((int) MagickTrue);
}
#endif
static void MngInfoDiscardObject(MngInfo *mng_info,int i)
{
if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) &&
mng_info->exists[i] && !mng_info->frozen[i])
{
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
{
if (mng_info->ob[i]->reference_count > 0)
mng_info->ob[i]->reference_count--;
if (mng_info->ob[i]->reference_count == 0)
{
if (mng_info->ob[i]->image != (Image *) NULL)
mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image);
mng_info->ob[i]=DestroyString(mng_info->ob[i]);
}
}
mng_info->ob[i]=(MngBuffer *) NULL;
#endif
mng_info->exists[i]=MagickFalse;
mng_info->invisible[i]=MagickFalse;
mng_info->viewable[i]=MagickFalse;
mng_info->frozen[i]=MagickFalse;
mng_info->x_off[i]=0;
mng_info->y_off[i]=0;
mng_info->object_clip[i].left=0;
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].top=0;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
}
static MngInfo *MngInfoFreeStruct(MngInfo *mng_info)
{
register ssize_t
i;
if (mng_info == (MngInfo *) NULL)
return((MngInfo *) NULL);
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
if (mng_info->global_plte != (png_colorp) NULL)
mng_info->global_plte=(png_colorp)
RelinquishMagickMemory(mng_info->global_plte);
return((MngInfo *) RelinquishMagickMemory(mng_info));
}
static MngBox mng_minimum_box(MngBox box1,MngBox box2)
{
MngBox
box;
box=box1;
if (box.left < box2.left)
box.left=box2.left;
if (box.top < box2.top)
box.top=box2.top;
if (box.right > box2.right)
box.right=box2.right;
if (box.bottom > box2.bottom)
box.bottom=box2.bottom;
return box;
}
static MngBox mng_read_box(MngBox previous_box,char delta_type,
unsigned char *p)
{
MngBox
box;
/*
Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk.
*/
box.left=(long) (((png_uint_32) p[0] << 24) | ((png_uint_32) p[1] << 16) |
((png_uint_32) p[2] << 8) | (png_uint_32) p[3]);
box.right=(long) (((png_uint_32) p[4] << 24) | ((png_uint_32) p[5] << 16) |
((png_uint_32) p[6] << 8) | (png_uint_32) p[7]);
box.top=(long) (((png_uint_32) p[8] << 24) | ((png_uint_32) p[9] << 16) |
((png_uint_32) p[10] << 8) | (png_uint_32) p[11]);
box.bottom=(long) (((png_uint_32) p[12] << 24) | ((png_uint_32) p[13] << 16) |
((png_uint_32) p[14] << 8) | (png_uint_32) p[15]);
if (delta_type != 0)
{
box.left+=previous_box.left;
box.right+=previous_box.right;
box.top+=previous_box.top;
box.bottom+=previous_box.bottom;
}
return(box);
}
static MngPair mng_read_pair(MngPair previous_pair,int delta_type,
unsigned char *p)
{
MngPair
pair;
/*
Read two ssize_t's from CLON, MOVE or PAST chunk
*/
pair.a=(long) (((png_uint_32) p[0] << 24) | ((png_uint_32) p[1] << 16) |
((png_uint_32) p[2] << 8) | (png_uint_32) p[3]);
pair.b=(long) (((png_uint_32) p[4] << 24) | ((png_uint_32) p[5] << 16) |
((png_uint_32) p[6] << 8) | (png_uint_32) p[7]);
if (delta_type != 0)
{
pair.a+=previous_pair.a;
pair.b+=previous_pair.b;
}
return(pair);
}
static long mng_get_long(unsigned char *p)
{
return ((long) (((png_uint_32) p[0] << 24) | ((png_uint_32) p[1] << 16) |
((png_uint_32) p[2] << 8) | (png_uint_32) p[3]));
}
typedef struct _PNGErrorInfo
{
Image
*image;
ExceptionInfo
*exception;
} PNGErrorInfo;
static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message)
{
ExceptionInfo
*exception;
Image
*image;
PNGErrorInfo
*error_info;
error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
image=error_info->image;
exception=error_info->exception;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" libpng-%s error: %s", png_get_libpng_ver(NULL),message);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
"`%s'",image->filename);
#if (PNG_LIBPNG_VER < 10500)
/* A warning about deprecated use of jmpbuf here is unavoidable if you
* are building with libpng-1.4.x and can be ignored.
*/
longjmp(ping->jmpbuf,1);
#else
png_longjmp(ping,1);
#endif
}
static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message)
{
ExceptionInfo
*exception;
Image
*image;
PNGErrorInfo
*error_info;
if (LocaleCompare(message, "Missing PLTE before tRNS") == 0)
png_error(ping, message);
error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
image=error_info->image;
exception=error_info->exception;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" libpng-%s warning: %s", png_get_libpng_ver(NULL),message);
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'",image->filename);
}
#ifdef PNG_USER_MEM_SUPPORTED
#if PNG_LIBPNG_VER >= 10400
static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size)
#else
static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size)
#endif
{
(void) png_ptr;
return((png_voidp) AcquireMagickMemory((size_t) size));
}
/*
Free a pointer. It is removed from the list at the same time.
*/
static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr)
{
(void) png_ptr;
ptr=RelinquishMagickMemory(ptr);
return((png_free_ptr) NULL);
}
#endif
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static int
Magick_png_read_raw_profile(png_struct *ping,Image *image,
const ImageInfo *image_info, png_textp text,int ii,ExceptionInfo *exception)
{
register ssize_t
i;
register unsigned char
*dp;
register png_charp
sp;
png_uint_32
length,
nibbles;
StringInfo
*profile;
const unsigned char
unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12,
13,14,15};
sp=text[ii].text+1;
/* look for newline */
while (*sp != '\n')
sp++;
/* look for length */
while (*sp == '\0' || *sp == ' ' || *sp == '\n')
sp++;
length=(png_uint_32) StringToLong(sp);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" length: %lu",(unsigned long) length);
while (*sp != ' ' && *sp != '\n')
sp++;
/* allocate space */
if (length == 0)
{
png_warning(ping,"invalid profile length");
return(MagickFalse);
}
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
png_warning(ping, "unable to copy profile");
return(MagickFalse);
}
/* copy profile, skipping white space and column 1 "=" signs */
dp=GetStringInfoDatum(profile);
nibbles=length*2;
for (i=0; i < (ssize_t) nibbles; i++)
{
while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f')
{
if (*sp == '\0')
{
png_warning(ping, "ran out of profile data");
profile=DestroyStringInfo(profile);
return(MagickFalse);
}
sp++;
}
if (i%2 == 0)
*dp=(unsigned char) (16*unhex[(int) *sp++]);
else
(*dp++)+=unhex[(int) *sp++];
}
/*
We have already read "Raw profile type.
*/
(void) SetImageProfile(image,&text[ii].key[17],profile,exception);
profile=DestroyStringInfo(profile);
if (image_info->verbose)
(void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]);
return MagickTrue;
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk)
{
Image
*image;
/* The unknown chunk structure contains the chunk data:
png_byte name[5];
png_byte *data;
png_size_t size;
Note that libpng has already taken care of the CRC handling.
Returns one of the following:
return(-n); chunk had an error
return(0); did not recognize
return(n); success
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read_user_chunk: found %c%c%c%c chunk",
chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]);
if (chunk->name[0] == 101 &&
(chunk->name[1] == 88 || chunk->name[1] == 120 ) &&
chunk->name[2] == 73 &&
chunk-> name[3] == 102)
{
/* process eXIf or exIf chunk */
PNGErrorInfo
*error_info;
StringInfo
*profile;
unsigned char
*p;
png_byte
*s;
size_t
i;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" recognized eXIf chunk");
image=(Image *) png_get_user_chunk_ptr(ping);
error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
profile=BlobToStringInfo((const void *) NULL,chunk->size+6);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(error_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
return(-1);
}
p=GetStringInfoDatum(profile);
if (*p != 'E')
{
/* Initialize profile with "Exif\0\0" if it is not
already present by accident
*/
*p++ ='E';
*p++ ='x';
*p++ ='i';
*p++ ='f';
*p++ ='\0';
*p++ ='\0';
}
else
{
if (p[1] != 'x' || p[2] != 'i' || p[3] != 'f' ||
p[4] != '\0' || p[5] != '\0')
{
/* Chunk is malformed */
profile=DestroyStringInfo(profile);
return(-1);
}
}
/* copy chunk->data to profile */
s=chunk->data;
for (i=0; i<chunk->size; i++)
*p++ = *s++;
error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
(void) SetImageProfile(image,"exif",profile,
error_info->exception);
profile=DestroyStringInfo(profile);
return(1);
}
/* vpAg (deprecated, replaced by caNv) */
if (chunk->name[0] == 118 &&
chunk->name[1] == 112 &&
chunk->name[2] == 65 &&
chunk->name[3] == 103)
{
/* recognized vpAg */
if (chunk->size != 9)
return(-1); /* Error return */
if (chunk->data[8] != 0)
return(0); /* ImageMagick requires pixel units */
image=(Image *) png_get_user_chunk_ptr(ping);
image->page.width=(size_t) (((png_uint_32) chunk->data[0] << 24) |
((png_uint_32) chunk->data[1] << 16) |
((png_uint_32) chunk->data[2] << 8) |
(png_uint_32) chunk->data[3]);
image->page.height=(size_t) (((png_uint_32) chunk->data[4] << 24) |
((png_uint_32) chunk->data[5] << 16) |
((png_uint_32) chunk->data[6] << 8) |
(png_uint_32) chunk->data[7]);
return(1);
}
/* caNv */
if (chunk->name[0] == 99 &&
chunk->name[1] == 97 &&
chunk->name[2] == 78 &&
chunk->name[3] == 118)
{
/* recognized caNv */
if (chunk->size != 16)
return(-1); /* Error return */
image=(Image *) png_get_user_chunk_ptr(ping);
image->page.width=(size_t) (((png_uint_32) chunk->data[0] << 24) |
((png_uint_32) chunk->data[1] << 16) |
((png_uint_32) chunk->data[2] << 8) | (png_uint_32) chunk->data[3]);
image->page.height=(size_t) (((png_uint_32) chunk->data[4] << 24) |
((png_uint_32) chunk->data[5] << 16) |
((png_uint_32) chunk->data[6] << 8) | (png_uint_32) chunk->data[7]);
image->page.x=(ssize_t) (((png_uint_32) chunk->data[8] << 24) |
((png_uint_32) chunk->data[9] << 16) |
((png_uint_32) chunk->data[10] << 8) | (png_uint_32) chunk->data[11]);
image->page.y=(ssize_t) (((png_uint_32) chunk->data[12] << 24) |
((png_uint_32) chunk->data[13] << 16) |
((png_uint_32) chunk->data[14] << 8) | (png_uint_32) chunk->data[15]);
return(1);
}
return(0); /* Did not recognize */
}
#endif /* PNG_UNKNOWN_CHUNKS_SUPPORTED */
#if defined(PNG_tIME_SUPPORTED)
static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info,
ExceptionInfo *exception)
{
png_timep
time;
if (png_get_tIME(ping,info,&time))
{
char
timestamp[21];
FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ",
time->year,time->month,time->day,time->hour,time->minute,time->second);
SetImageProperty(image,"png:tIME",timestamp,exception);
}
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d O n e P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file
% (minus the 8-byte signature) 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 ReadOnePNGImage method is:
%
% Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o mng_info: Specifies a pointer to a MngInfo structure.
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadOnePNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
/* Read one PNG image */
/* To do: Read the tEXt/Creation Time chunk into the date:create property */
Image
*image;
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
int
intent, /* "PNG Rendering intent", which is ICC intent + 1 */
num_raw_profiles,
num_text,
num_text_total,
num_passes,
number_colors,
pass,
ping_bit_depth,
ping_color_type,
ping_file_depth,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans,
unit_type;
double
file_gamma;
MagickBooleanType
logging,
ping_found_cHRM,
ping_found_gAMA,
ping_found_iCCP,
ping_found_sRGB,
ping_found_sRGB_cHRM,
ping_preserve_iCCP,
status;
MemoryInfo
*volatile pixel_info;
PixelInfo
transparent_color;
PNGErrorInfo
error_info;
png_bytep
ping_trans_alpha;
png_color_16p
ping_background,
ping_trans_color;
png_info
*end_info,
*ping_info;
png_struct
*ping;
png_textp
text;
png_uint_32
ping_height,
ping_width,
x_resolution,
y_resolution;
QuantumInfo
*volatile quantum_info;
ssize_t
ping_rowbytes,
y;
register unsigned char
*p;
register ssize_t
i,
x;
register Quantum
*q;
size_t
length,
row_offset;
ssize_t
j;
unsigned char
*ping_pixels;
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
png_byte unused_chunks[]=
{
104, 73, 83, 84, (png_byte) '\0', /* hIST */
105, 84, 88, 116, (png_byte) '\0', /* iTXt */
112, 67, 65, 76, (png_byte) '\0', /* pCAL */
115, 67, 65, 76, (png_byte) '\0', /* sCAL */
115, 80, 76, 84, (png_byte) '\0', /* sPLT */
#if !defined(PNG_tIME_SUPPORTED)
116, 73, 77, 69, (png_byte) '\0', /* tIME */
#endif
#ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */
/* ignore the APNG chunks */
97, 99, 84, 76, (png_byte) '\0', /* acTL */
102, 99, 84, 76, (png_byte) '\0', /* fcTL */
102, 100, 65, 84, (png_byte) '\0', /* fdAT */
#endif
};
#endif
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,32);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,32);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOnePNGImage()\n"
" IM version = %s\n"
" Libpng version = %s",
im_vers, libpng_vers);
if (logging != MagickFalse)
{
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
#if (PNG_LIBPNG_VER < 10200)
if (image_info->verbose)
printf("Your PNG library (libpng-%s) is rather old.\n",
PNG_LIBPNG_VER_STRING);
#endif
#if (PNG_LIBPNG_VER >= 10400)
# ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */
if (image_info->verbose)
{
printf("Your PNG library (libpng-%s) is an old beta version.\n",
PNG_LIBPNG_VER_STRING);
printf("Please update it.\n");
}
# endif
#endif
quantum_info = (QuantumInfo *) NULL;
image=mng_info->image;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before reading:\n"
" image->alpha_trait=%d"
" image->rendering_intent=%d\n"
" image->colorspace=%d\n"
" image->gamma=%f",
(int) image->alpha_trait, (int) image->rendering_intent,
(int) image->colorspace, image->gamma);
}
intent=
Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent);
/* Set to an out-of-range color unless tRNS chunk is present */
transparent_color.red=65537;
transparent_color.green=65537;
transparent_color.blue=65537;
transparent_color.alpha=65537;
number_colors=0;
num_text = 0;
num_text_total = 0;
num_raw_profiles = 0;
ping_found_cHRM = MagickFalse;
ping_found_gAMA = MagickFalse;
ping_found_iCCP = MagickFalse;
ping_found_sRGB = MagickFalse;
ping_found_sRGB_cHRM = MagickFalse;
ping_preserve_iCCP = MagickFalse;
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
error_info.image=image;
error_info.exception=exception;
ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler, NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
end_info=png_create_info_struct(ping);
if (end_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG image is corrupt.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() with error.");
return(GetFirstImageInList(image));
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for reading.
*/
mng_info->image_found++;
png_set_sig_bytes(ping,8);
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED)
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
png_set_read_fn(ping,image,png_get_data);
#else
#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED)
png_permit_empty_plte(ping,MagickTrue);
png_set_read_fn(ping,image,png_get_data);
#else
mng_info->image=image;
mng_info->bytes_in_read_buffer=0;
mng_info->found_empty_plte=MagickFalse;
mng_info->have_saved_bkgd_index=MagickFalse;
png_set_read_fn(ping,mng_info,mng_get_data);
#endif
#endif
}
else
png_set_read_fn(ping,image,png_get_data);
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",value) == MagickFalse)
{
value=GetImageOption(image_info,"png:preserve-iCCP");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-iCCP");
if (value != NULL)
ping_preserve_iCCP=MagickTrue;
#if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED)
/* Don't let libpng check for ICC/sRGB profile because we're going
* to do that anyway. This feature was added at libpng-1.6.12.
* If logging, go ahead and check and issue a warning as appropriate.
*/
if (logging == MagickFalse)
png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
else
{
png_set_keep_unknown_chunks(ping, 1, (png_bytep) mng_iCCP, 1);
}
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
/* Ignore unused chunks and all unknown chunks except for eXIf,
caNv, and vpAg */
# if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */
png_set_keep_unknown_chunks(ping, 2, NULL, 0);
# else
png_set_keep_unknown_chunks(ping, 1, NULL, 0);
# endif
png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_eXIf, 1);
png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_caNv, 1);
png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_vpAg, 1);
png_set_keep_unknown_chunks(ping, 1, unused_chunks,
(int)sizeof(unused_chunks)/5);
/* Callback for other unknown chunks */
png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
# if (PNG_LIBPNG_VER >= 10400)
/* Limit the size of the chunk storage cache used for sPLT, text,
* and unknown chunks.
*/
png_set_chunk_cache_max(ping, 32767);
# endif
#endif
#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature */
png_set_check_for_invalid_index (ping, 0);
#endif
#if (PNG_LIBPNG_VER < 10400)
# if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \
(PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__)
/* Disable thread-unsafe features of pnggccrd */
if (png_access_version_number() >= 10200)
{
png_uint_32 mmx_disable_mask=0;
png_uint_32 asm_flags;
mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
| PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
| PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
| PNG_ASM_FLAG_MMX_READ_FILTER_PAETH );
asm_flags=png_get_asm_flags(ping);
png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask);
}
# endif
#endif
png_read_info(ping,ping_info);
png_get_IHDR(ping,ping_info,&ping_width,&ping_height,
&ping_bit_depth,&ping_color_type,
&ping_interlace_method,&ping_compression_method,
&ping_filter_method);
ping_file_depth = ping_bit_depth;
/* Swap bytes if requested */
if (ping_file_depth == 16)
{
const char
*value;
value=GetImageOption(image_info,"png:swap-bytes");
if (value == NULL)
value=GetImageArtifact(image,"png:swap-bytes");
if (value != NULL)
png_set_swap(ping);
}
/* Save bit-depth and color-type in case we later want to write a PNG00 */
{
char
msg[MagickPathExtent];
(void) FormatLocaleString(msg,MagickPathExtent,"%d",
(int) ping_color_type);
(void) SetImageProperty(image,"png:IHDR.color-type-orig",msg,exception);
(void) FormatLocaleString(msg,MagickPathExtent,"%d",
(int) ping_bit_depth);
(void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg,exception);
}
(void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans,
&ping_trans_color);
(void) png_get_bKGD(ping, ping_info, &ping_background);
if (ping_bit_depth < 8)
{
png_set_packing(ping);
ping_bit_depth = 8;
}
image->depth=ping_bit_depth;
image->depth=GetImageQuantumDepth(image,MagickFalse);
image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace;
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
image->rendering_intent=UndefinedIntent;
intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent);
(void) ResetMagickMemory(&image->chromaticity,0,
sizeof(image->chromaticity));
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG width: %.20g, height: %.20g\n"
" PNG color_type: %d, bit_depth: %d\n"
" PNG compression_method: %d\n"
" PNG interlace_method: %d, filter_method: %d",
(double) ping_width, (double) ping_height,
ping_color_type, ping_bit_depth,
ping_compression_method,
ping_interlace_method,ping_filter_method);
}
if (png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_gAMA))
{
ping_found_gAMA=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG gAMA chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
ping_found_cHRM=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG cHRM chunk.");
}
if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
ping_found_sRGB=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG sRGB chunk.");
}
#ifdef PNG_READ_iCCP_SUPPORTED
if (ping_found_iCCP !=MagickTrue &&
ping_found_sRGB != MagickTrue &&
png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_iCCP))
{
int
compression;
#if (PNG_LIBPNG_VER < 10500)
png_charp
info;
#else
png_bytep
info;
#endif
png_charp
name;
png_uint_32
profile_length;
(void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info,
&profile_length);
if (profile_length != 0)
{
StringInfo
*profile;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG iCCP chunk.");
profile=BlobToStringInfo(info,profile_length);
if (profile == (StringInfo *) NULL)
{
png_warning(ping, "ICC profile is NULL");
profile=DestroyStringInfo(profile);
}
else
{
if (ping_preserve_iCCP == MagickFalse)
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
break;
}
}
}
if (sRGB_info[icheck].len == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
(void) SetImageProfile(image,"icc",profile,exception);
}
}
else /* Preserve-iCCP */
{
(void) SetImageProfile(image,"icc",profile,exception);
}
profile=DestroyStringInfo(profile);
}
}
}
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
{
if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
if (png_get_sRGB(ping,ping_info,&intent))
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent (intent);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG sRGB chunk: rendering_intent: %d",intent);
}
}
else if (mng_info->have_global_srgb)
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent
(mng_info->global_srgb_intent);
}
}
#endif
{
if (!png_get_gAMA(ping,ping_info,&file_gamma))
if (mng_info->have_global_gama)
png_set_gAMA(ping,ping_info,mng_info->global_gamma);
if (png_get_gAMA(ping,ping_info,&file_gamma))
{
image->gamma=(float) file_gamma;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG gAMA chunk: gamma: %f",file_gamma);
}
}
if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
if (mng_info->have_global_chrm != MagickFalse)
{
(void) png_set_cHRM(ping,ping_info,
mng_info->global_chrm.white_point.x,
mng_info->global_chrm.white_point.y,
mng_info->global_chrm.red_primary.x,
mng_info->global_chrm.red_primary.y,
mng_info->global_chrm.green_primary.x,
mng_info->global_chrm.green_primary.y,
mng_info->global_chrm.blue_primary.x,
mng_info->global_chrm.blue_primary.y);
}
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
(void) png_get_cHRM(ping,ping_info,
&image->chromaticity.white_point.x,
&image->chromaticity.white_point.y,
&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);
ping_found_cHRM=MagickTrue;
if (image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f)
ping_found_sRGB_cHRM=MagickTrue;
}
if (image->rendering_intent != UndefinedIntent)
{
if (ping_found_sRGB != MagickTrue &&
(ping_found_gAMA != MagickTrue ||
(image->gamma > .45 && image->gamma < .46)) &&
(ping_found_cHRM != MagickTrue ||
ping_found_sRGB_cHRM != MagickFalse) &&
ping_found_iCCP != MagickTrue)
{
png_set_sRGB(ping,ping_info,
Magick_RenderingIntent_to_PNG_RenderingIntent
(image->rendering_intent));
file_gamma=1.000f/2.200f;
ping_found_sRGB=MagickTrue;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting sRGB as if in input");
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info);
image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info);
if (logging != MagickFalse)
if (image->page.x || image->page.y)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double)
image->page.x,(double) image->page.y);
}
#endif
#if defined(PNG_pHYs_SUPPORTED)
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
if (mng_info->have_global_phys)
{
png_set_pHYs(ping,ping_info,
mng_info->global_x_pixels_per_unit,
mng_info->global_y_pixels_per_unit,
mng_info->global_phys_unit_type);
}
}
x_resolution=0;
y_resolution=0;
unit_type=0;
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
/*
Set image resolution.
*/
(void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution,
&unit_type);
image->resolution.x=(double) x_resolution;
image->resolution.y=(double) y_resolution;
if (unit_type == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=(double) x_resolution/100.0;
image->resolution.y=(double) y_resolution/100.0;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) x_resolution,(double) y_resolution,unit_type);
}
#endif
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
if ((number_colors == 0) &&
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE))
{
if (mng_info->global_plte_length)
{
png_set_PLTE(ping,ping_info,mng_info->global_plte,
(int) mng_info->global_plte_length);
if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
if (mng_info->global_trns_length)
{
png_warning(ping,
"global tRNS has more entries than global PLTE");
}
else
{
png_set_tRNS(ping,ping_info,mng_info->global_trns,
(int) mng_info->global_trns_length,NULL);
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
mng_info->have_saved_bkgd_index ||
#endif
png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
png_color_16
background;
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
if (mng_info->have_saved_bkgd_index)
background.index=mng_info->saved_bkgd_index;
#endif
if (png_get_valid(ping, ping_info, PNG_INFO_bKGD))
background.index=ping_background->index;
background.red=(png_uint_16)
mng_info->global_plte[background.index].red;
background.green=(png_uint_16)
mng_info->global_plte[background.index].green;
background.blue=(png_uint_16)
mng_info->global_plte[background.index].blue;
background.gray=(png_uint_16)
mng_info->global_plte[background.index].green;
png_set_bKGD(ping,ping_info,&background);
}
#endif
}
else
png_error(ping,"No global PLTE in file");
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (mng_info->have_global_bkgd &&
(!png_get_valid(ping,ping_info,PNG_INFO_bKGD)))
image->background_color=mng_info->mng_global_bkgd;
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
unsigned int
bkgd_scale;
/* Set image background color.
* Scale background components to 16-bit, then scale
* to quantum depth
*/
bkgd_scale = 1;
if (ping_file_depth == 1)
bkgd_scale = 255;
else if (ping_file_depth == 2)
bkgd_scale = 85;
else if (ping_file_depth == 4)
bkgd_scale = 17;
if (ping_file_depth <= 8)
bkgd_scale *= 257;
ping_background->red *= bkgd_scale;
ping_background->green *= bkgd_scale;
ping_background->blue *= bkgd_scale;
if (logging != MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d)\n"
" bkgd_scale=%d. ping_background=(%d,%d,%d)",
ping_background->red,ping_background->green,
ping_background->blue,
bkgd_scale,ping_background->red,
ping_background->green,ping_background->blue);
}
image->background_color.red=
ScaleShortToQuantum(ping_background->red);
image->background_color.green=
ScaleShortToQuantum(ping_background->green);
image->background_color.blue=
ScaleShortToQuantum(ping_background->blue);
image->background_color.alpha=OpaqueAlpha;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->background_color=(%.20g,%.20g,%.20g).",
(double) image->background_color.red,
(double) image->background_color.green,
(double) image->background_color.blue);
}
#endif /* PNG_READ_bKGD_SUPPORTED */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
/*
Image has a tRNS chunk.
*/
int
max_sample;
size_t
one = 1;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG tRNS chunk.");
max_sample = (int) ((one << ping_file_depth) - 1);
if ((ping_color_type == PNG_COLOR_TYPE_GRAY &&
(int)ping_trans_color->gray > max_sample) ||
(ping_color_type == PNG_COLOR_TYPE_RGB &&
((int)ping_trans_color->red > max_sample ||
(int)ping_trans_color->green > max_sample ||
(int)ping_trans_color->blue > max_sample)))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Ignoring PNG tRNS chunk with out-of-range sample.");
png_free_data(ping, ping_info, PNG_FREE_TRNS, 0);
png_set_invalid(ping,ping_info,PNG_INFO_tRNS);
image->alpha_trait=UndefinedPixelTrait;
}
else
{
int
scale_to_short;
scale_to_short = 65535L/((1UL << ping_file_depth)-1);
/* Scale transparent_color to short */
transparent_color.red= scale_to_short*ping_trans_color->red;
transparent_color.green= scale_to_short*ping_trans_color->green;
transparent_color.blue= scale_to_short*ping_trans_color->blue;
transparent_color.alpha= scale_to_short*ping_trans_color->gray;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Raw tRNS graylevel = %d, scaled graylevel = %d.",
(int) ping_trans_color->gray,(int) transparent_color.alpha);
}
transparent_color.red=transparent_color.alpha;
transparent_color.green=transparent_color.alpha;
transparent_color.blue=transparent_color.alpha;
}
}
}
#if defined(PNG_READ_sBIT_SUPPORTED)
if (mng_info->have_global_sbit)
{
if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT))
png_set_sBIT(ping,ping_info,&mng_info->global_sbit);
}
#endif
num_passes=png_set_interlace_handling(ping);
png_read_update_info(ping,ping_info);
ping_rowbytes=png_get_rowbytes(ping,ping_info);
/*
Initialize image structure.
*/
mng_info->image_box.left=0;
mng_info->image_box.right=(ssize_t) ping_width;
mng_info->image_box.top=0;
mng_info->image_box.bottom=(ssize_t) ping_height;
if (mng_info->mng_type == 0)
{
mng_info->mng_width=ping_width;
mng_info->mng_height=ping_height;
mng_info->frame=mng_info->image_box;
mng_info->clip=mng_info->image_box;
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
image->compression=ZipCompression;
image->columns=ping_width;
image->rows=ping_height;
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
double
image_gamma = image->gamma;
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->gamma=%f",(float) image_gamma);
if (image_gamma > 0.75)
{
/* Set image->rendering_intent to Undefined,
* image->colorspace to GRAY, and reset image->chromaticity.
*/
image->intensity = Rec709LuminancePixelIntensityMethod;
SetImageColorspace(image,GRAYColorspace,exception);
}
else
{
RenderingIntent
save_rendering_intent = image->rendering_intent;
ChromaticityInfo
save_chromaticity = image->chromaticity;
SetImageColorspace(image,GRAYColorspace,exception);
image->rendering_intent = save_rendering_intent;
image->chromaticity = save_chromaticity;
}
image->gamma = image_gamma;
}
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colorspace=%d",(int) image->colorspace);
if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
((int) ping_bit_depth < 16 &&
(int) ping_color_type == PNG_COLOR_TYPE_GRAY))
{
size_t
one;
image->storage_class=PseudoClass;
one=1;
image->colors=one << ping_file_depth;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->colors > 256)
image->colors=256;
#else
if (image->colors > 65536L)
image->colors=65536L;
#endif
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
image->colors=(size_t) number_colors;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG PLTE chunk: number_colors: %d.",number_colors);
}
}
if (image->storage_class == PseudoClass)
{
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
png_error(ping,"Memory allocation failed");
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(palette[i].red);
image->colormap[i].green=ScaleCharToQuantum(palette[i].green);
image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue);
}
for ( ; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=0;
image->colormap[i].green=0;
image->colormap[i].blue=0;
}
}
else
{
Quantum
scale;
scale = (Quantum) (65535.0/((1UL << ping_file_depth)-1.0));
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
scale = ScaleShortToQuantum(scale);
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(Quantum) (i*scale);
image->colormap[i].green=(Quantum) (i*scale);
image->colormap[i].blue=(Quantum) (i*scale);
}
}
}
/* Set some properties for reporting by "identify" */
{
char
msg[MagickPathExtent];
/* encode ping_width, ping_height, ping_file_depth, ping_color_type,
ping_interlace_method in value */
(void) FormatLocaleString(msg,MagickPathExtent,
"%d, %d",(int) ping_width, (int) ping_height);
(void) SetImageProperty(image,"png:IHDR.width,height",msg,exception);
(void) FormatLocaleString(msg,MagickPathExtent,"%d",
(int) ping_file_depth);
(void) SetImageProperty(image,"png:IHDR.bit_depth",msg,exception);
(void) FormatLocaleString(msg,MagickPathExtent,"%d (%s)",
(int) ping_color_type,
Magick_ColorType_from_PNG_ColorType((int)ping_color_type));
(void) SetImageProperty(image,"png:IHDR.color_type",msg,exception);
if (ping_interlace_method == 0)
{
(void) FormatLocaleString(msg,MagickPathExtent,"%d (Not interlaced)",
(int) ping_interlace_method);
}
else if (ping_interlace_method == 1)
{
(void) FormatLocaleString(msg,MagickPathExtent,"%d (Adam7 method)",
(int) ping_interlace_method);
}
else
{
(void) FormatLocaleString(msg,MagickPathExtent,"%d (Unknown method)",
(int) ping_interlace_method);
}
(void) SetImageProperty(image,"png:IHDR.interlace_method",
msg,exception);
if (number_colors != 0)
{
(void) FormatLocaleString(msg,MagickPathExtent,"%d",
(int) number_colors);
(void) SetImageProperty(image,"png:PLTE.number_colors",msg,
exception);
}
}
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,ping_info,exception);
#endif
/*
Read image scanlines.
*/
if (image->delay != 0)
mng_info->scenes_found++;
if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || (
(image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t)
(image_info->first_scene+image_info->number_scenes))))
{
/* This happens later in non-ping decodes */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
image->storage_class=DirectClass;
image->alpha_trait=
(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
BlendPixelTrait : UndefinedPixelTrait;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping PNG image data for scene %.20g",(double)
mng_info->scenes_found-1);
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage().");
return(image);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG IDAT chunk(s)");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (num_passes > 1)
pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes*
sizeof(*ping_pixels));
else
pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Memory allocation failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting PNG pixels to pixel packets");
/*
Convert PNG pixels to pixel packets.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Failed to allocate quantum_info");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
{
MagickBooleanType
found_transparent_pixel;
found_transparent_pixel=MagickFalse;
if (image->storage_class == DirectClass)
{
for (pass=0; pass < num_passes; pass++)
{
/*
Convert image to DirectClass pixel packets.
*/
image->alpha_trait=
(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
BlendPixelTrait : UndefinedPixelTrait;
for (y=0; y < (ssize_t) image->rows; y++)
{
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayAlphaQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBAQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
IndexQuantum,ping_pixels+row_offset,exception);
else /* ping_color_type == PNG_COLOR_TYPE_RGB */
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBQuantum,ping_pixels+row_offset,exception);
if (found_transparent_pixel == MagickFalse)
{
/* Is there a transparent pixel in the row? */
if (y== 0 && logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Looking for cheap transparent pixel");
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if ((ping_color_type == PNG_COLOR_TYPE_RGBA ||
ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) &&
(GetPixelAlpha(image,q) != OpaqueAlpha))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
if ((ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_GRAY) &&
(ScaleQuantumToShort(GetPixelRed(image,q)) ==
transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(image,q)) ==
transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(image,q)) ==
transparent_color.blue))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
q+=GetPixelChannels(image);
}
}
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,
(MagickOffsetType) y, image->rows);
if (status == MagickFalse)
break;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
}
}
else /* image->storage_class != DirectClass */
for (pass=0; pass < num_passes; pass++)
{
Quantum
*quantum_scanline;
register Quantum
*r;
/*
Convert grayscale image to PseudoClass pixel packets.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting grayscale pixels to pixel packets");
image->alpha_trait=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ?
BlendPixelTrait : UndefinedPixelTrait;
quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns,
(image->alpha_trait == BlendPixelTrait? 2 : 1)*
sizeof(*quantum_scanline));
if (quantum_scanline == (Quantum *) NULL)
png_error(ping,"Memory allocation failed");
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
alpha;
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=ping_pixels+row_offset;
r=quantum_scanline;
switch (ping_bit_depth)
{
case 8:
{
if (ping_color_type == 4)
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
*r++=*p++;
alpha=ScaleCharToQuantum((unsigned char)*p++);
SetPixelAlpha(image,alpha,q);
if (alpha != OpaqueAlpha)
found_transparent_pixel = MagickTrue;
q+=GetPixelChannels(image);
}
else
for (x=(ssize_t) image->columns-1; x >= 0; x--)
*r++=*p++;
break;
}
case 16:
{
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
#if (MAGICKCORE_QUANTUM_DEPTH >= 16)
unsigned short
quantum;
if (image->colors > 256)
quantum=(((unsigned int) *p++) << 8);
else
quantum=0;
quantum|=(*p++);
*r=ScaleShortToQuantum(quantum);
r++;
if (ping_color_type == 4)
{
if (image->colors > 256)
quantum=(((unsigned int) *p++) << 8);
else
quantum=0;
quantum|=(*p++);
alpha=ScaleShortToQuantum(quantum);
SetPixelAlpha(image,alpha,q);
if (alpha != OpaqueAlpha)
found_transparent_pixel = MagickTrue;
q+=GetPixelChannels(image);
}
#else /* MAGICKCORE_QUANTUM_DEPTH == 8 */
*r++=(*p++);
p++; /* strip low byte */
if (ping_color_type == 4)
{
SetPixelAlpha(image,*p++,q);
if (GetPixelAlpha(image,q) != OpaqueAlpha)
found_transparent_pixel = MagickTrue;
p++;
q+=GetPixelChannels(image);
}
#endif
}
break;
}
default:
break;
}
/*
Transfer image scanline.
*/
r=quantum_scanline;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*r++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline);
}
image->alpha_trait=found_transparent_pixel ? BlendPixelTrait :
UndefinedPixelTrait;
if (logging != MagickFalse)
{
if (found_transparent_pixel != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found transparent pixel");
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No transparent pixel was found");
ping_color_type&=0x03;
}
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->storage_class == PseudoClass)
{
PixelTrait
alpha_trait;
alpha_trait=image->alpha_trait;
image->alpha_trait=UndefinedPixelTrait;
(void) SyncImage(image,exception);
image->alpha_trait=alpha_trait;
}
png_read_end(ping,end_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=%d\n",(int) image->storage_class);
}
if (image_info->number_scenes != 0 && mng_info->scenes_found-1 <
(ssize_t) image_info->first_scene && image->delay != 0)
{
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
image->colors=2;
(void) SetImageBackgroundColor(image,exception);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() early.");
return(image);
}
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
ClassType
storage_class;
/*
Image has a transparent background.
*/
storage_class=image->storage_class;
image->alpha_trait=BlendPixelTrait;
/* Balfour fix from imagemagick discourse server, 5 Feb 2010 */
if (storage_class == PseudoClass)
{
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
for (x=0; x < ping_num_trans; x++)
{
image->colormap[x].alpha_trait=BlendPixelTrait;
image->colormap[x].alpha =
ScaleCharToQuantum((unsigned char)ping_trans_alpha[x]);
}
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
for (x=0; x < (int) image->colors; x++)
{
if (ScaleQuantumToShort(image->colormap[x].red) ==
transparent_color.alpha)
{
image->colormap[x].alpha_trait=BlendPixelTrait;
image->colormap[x].alpha = (Quantum) TransparentAlpha;
}
}
}
(void) SyncImage(image,exception);
}
#if 1 /* Should have already been done above, but glennrp problem P10
* needs this.
*/
else
{
for (y=0; y < (ssize_t) image->rows; y++)
{
image->storage_class=storage_class;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
/* Caution: on a Q8 build, this does not distinguish between
* 16-bit colors that differ only in the low byte
*/
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if (ScaleQuantumToShort(GetPixelRed(image,q)) ==
transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(image,q)) ==
transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(image,q)) ==
transparent_color.blue)
{
SetPixelAlpha(image,TransparentAlpha,q);
}
#if 0 /* I have not found a case where this is needed. */
else
{
SetPixelAlpha(image,q)=(Quantum) OpaqueAlpha;
}
#endif
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
image->storage_class=DirectClass;
}
for (j = 0; j < 2; j++)
{
if (j == 0)
status = png_get_text(ping,ping_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
else
status = png_get_text(ping,end_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
if (status != MagickFalse)
for (i=0; i < (ssize_t) num_text; i++)
{
/* Check for a profile */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG text chunk");
if (strlen(text[i].key) > 16 &&
memcmp(text[i].key, "Raw profile type ",17) == 0)
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember(text[i].key+17,value) == MagickFalse)
{
(void) Magick_png_read_raw_profile(ping,image,image_info,text,
(int) i,exception);
num_raw_profiles++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Read raw profile %s",text[i].key+17);
}
else
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping raw profile %s",text[i].key+17);
}
}
else
{
char
*value;
length=text[i].text_length;
value=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*value));
if (value == (char *) NULL)
{
png_error(ping,"Memory allocation failed");
break;
}
*value='\0';
(void) ConcatenateMagickString(value,text[i].text,length+2);
/* Don't save "density" or "units" property if we have a pHYs
* chunk
*/
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) ||
(LocaleCompare(text[i].key,"density") != 0 &&
LocaleCompare(text[i].key,"units") != 0))
(void) SetImageProperty(image,text[i].key,value,exception);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" length: %lu\n"
" Keyword: %s",
(unsigned long) length,
text[i].key);
}
value=DestroyString(value);
}
}
num_text_total += num_text;
}
#ifdef MNG_OBJECT_BUFFERS
/*
Store the object if necessary.
*/
if (object_id && !mng_info->frozen[object_id])
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
{
/*
create a new object buffer.
*/
mng_info->ob[object_id]=(MngBuffer *)
AcquireMagickMemory(sizeof(MngBuffer));
if (mng_info->ob[object_id] != (MngBuffer *) NULL)
{
mng_info->ob[object_id]->image=(Image *) NULL;
mng_info->ob[object_id]->reference_count=1;
}
}
if ((mng_info->ob[object_id] == (MngBuffer *) NULL) ||
mng_info->ob[object_id]->frozen)
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
png_error(ping,"Memory allocation failed");
if (mng_info->ob[object_id]->frozen)
png_error(ping,"Cannot overwrite frozen MNG object buffer");
}
else
{
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image=DestroyImage
(mng_info->ob[object_id]->image);
mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue,
exception);
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image->file=(FILE *) NULL;
else
png_error(ping, "Cloning image for object buffer failed");
if (ping_width > 250000L || ping_height > 250000L)
png_error(ping,"PNG Image dimensions are too large.");
mng_info->ob[object_id]->width=ping_width;
mng_info->ob[object_id]->height=ping_height;
mng_info->ob[object_id]->color_type=ping_color_type;
mng_info->ob[object_id]->sample_depth=ping_bit_depth;
mng_info->ob[object_id]->interlace_method=ping_interlace_method;
mng_info->ob[object_id]->compression_method=
ping_compression_method;
mng_info->ob[object_id]->filter_method=ping_filter_method;
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
plte;
/*
Copy the PLTE to the object buffer.
*/
png_get_PLTE(ping,ping_info,&plte,&number_colors);
mng_info->ob[object_id]->plte_length=number_colors;
for (i=0; i < number_colors; i++)
{
mng_info->ob[object_id]->plte[i]=plte[i];
}
}
else
mng_info->ob[object_id]->plte_length=0;
}
}
#endif
/* Set image->alpha_trait to MagickTrue if the input colortype supports
* alpha or if a valid tRNS chunk is present, no matter whether there
* is actual transparency present.
*/
image->alpha_trait=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
BlendPixelTrait : UndefinedPixelTrait;
#if 0 /* I'm not sure what's wrong here but it does not work. */
if (image->alpha_trait != UndefinedPixelTrait)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) SetImageType(image,GrayscaleAlphaType,exception);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteAlphaType,exception);
else
(void) SetImageType(image,TrueColorAlphaType,exception);
}
else
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) SetImageType(image,GrayscaleType,exception);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteType,exception);
else
(void) SetImageType(image,TrueColorType,exception);
}
#endif
/* Set more properties for identify to retrieve */
{
char
msg[MagickPathExtent];
if (num_text_total != 0)
{
/* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */
(void) FormatLocaleString(msg,MagickPathExtent,
"%d tEXt/zTXt/iTXt chunks were found", num_text_total);
(void) SetImageProperty(image,"png:text",msg,
exception);
}
if (num_raw_profiles != 0)
{
(void) FormatLocaleString(msg,MagickPathExtent,
"%d were found", num_raw_profiles);
(void) SetImageProperty(image,"png:text-encoded profiles",msg,
exception);
}
/* cHRM chunk: */
if (ping_found_cHRM != MagickFalse)
{
(void) FormatLocaleString(msg,MagickPathExtent,"%s",
"chunk was found (see Chromaticity, above)");
(void) SetImageProperty(image,"png:cHRM",msg,
exception);
}
/* bKGD chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
(void) FormatLocaleString(msg,MagickPathExtent,"%s",
"chunk was found (see Background color, above)");
(void) SetImageProperty(image,"png:bKGD",msg,
exception);
}
(void) FormatLocaleString(msg,MagickPathExtent,"%s",
"chunk was found");
#if defined(PNG_iCCP_SUPPORTED)
/* iCCP chunk: */
if (ping_found_iCCP != MagickFalse)
(void) SetImageProperty(image,"png:iCCP",msg,
exception);
#endif
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
(void) SetImageProperty(image,"png:tRNS",msg,
exception);
#if defined(PNG_sRGB_SUPPORTED)
/* sRGB chunk: */
if (ping_found_sRGB != MagickFalse)
{
(void) FormatLocaleString(msg,MagickPathExtent,
"intent=%d (%s)",
(int) intent,
Magick_RenderingIntentString_from_PNG_RenderingIntent(intent));
(void) SetImageProperty(image,"png:sRGB",msg,
exception);
}
#endif
/* gAMA chunk: */
if (ping_found_gAMA != MagickFalse)
{
(void) FormatLocaleString(msg,MagickPathExtent,
"gamma=%.8g (See Gamma, above)",
file_gamma);
(void) SetImageProperty(image,"png:gAMA",msg,
exception);
}
#if defined(PNG_pHYs_SUPPORTED)
/* pHYs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
(void) FormatLocaleString(msg,MagickPathExtent,
"x_res=%.10g, y_res=%.10g, units=%d",
(double) x_resolution,(double) y_resolution, unit_type);
(void) SetImageProperty(image,"png:pHYs",msg,
exception);
}
#endif
#if defined(PNG_oFFs_SUPPORTED)
/* oFFs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
(void) FormatLocaleString(msg,MagickPathExtent,
"x_off=%.20g, y_off=%.20g",
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:oFFs",msg,
exception);
}
#endif
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,end_info,exception);
#endif
/* caNv chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
(image->page.x != 0 || image->page.y != 0))
{
(void) FormatLocaleString(msg,MagickPathExtent,
"width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:caNv",msg,
exception);
}
/* vpAg chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
(void) FormatLocaleString(msg,MagickPathExtent,
"width=%.20g, height=%.20g",
(double) image->page.width,(double) image->page.height);
(void) SetImageProperty(image,"png:vpAg",msg,
exception);
}
}
/*
Relinquish resources.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block, revert to
* Throwing an Exception when an error occurs.
*/
return(image);
/* end of reading one PNG image */
}
static Image *ReadPNGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MagickPathExtent];
ssize_t
count;
/*
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);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()");
image=AcquireImage(image_info,exception);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
ThrowReaderException(FileOpenError,"UnableToOpenFile");
/*
Verify PNG signature.
*/
count=ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a PNG datastream.
*/
if (GetBlobSize(image) < 61)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOnePNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if ((image->columns == 0) || (image->rows == 0))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error.");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if ((IssRGBColorspace(image->colorspace) != MagickFalse) &&
((image->gamma < .45) || (image->gamma > .46)) &&
!(image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f))
{
SetImageColorspace(image,RGBColorspace,exception);
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colorspace: %d", (int) image->colorspace);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()");
return(image);
}
#if defined(JNG_SUPPORTED)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d O n e J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file
% (minus the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadOneJNGImage method is:
%
% Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o mng_info: Specifies a pointer to a MngInfo structure.
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const Quantum
*s;
register ssize_t
i,
x;
register Quantum
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MagickPathExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MagickPathExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
{
if (color_image != (Image *) NULL)
color_image=DestroyImage(color_image);
if (color_image_info != (ImageInfo *) NULL)
color_image_info=DestroyImageInfo(color_image_info);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(png_uint_32) (((png_uint_32) p[0] << 24) |
((png_uint_32) p[1] << 16) | ((png_uint_32) p[2] << 8) |
(png_uint_32) p[3]);
jng_height=(png_uint_32) (((png_uint_32) p[4] << 24) |
((png_uint_32) p[5] << 16) | ((png_uint_32) p[6] << 8) |
(png_uint_32) p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,
"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info,exception);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
(void) AcquireUniqueFilename(color_image->filename);
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info,exception);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->resolution.x=(double) mng_get_long(p);
image->resolution.y=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=image->resolution.x/100.0f;
image->resolution.y=image->resolution.y/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
alpha samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MagickPathExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->rows=jng_height;
image->columns=jng_width;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
for (x=(ssize_t) image->columns; x != 0; x--)
{
SetPixelRed(image,GetPixelRed(jng_image,s),q);
SetPixelGreen(image,GetPixelGreen(jng_image,s),q);
SetPixelBlue(image,GetPixelBlue(jng_image,s),q);
q+=GetPixelChannels(image);
s+=GetPixelChannels(jng_image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) CloseBlob(alpha_image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading alpha from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->alpha_trait != UndefinedPixelTrait)
for (x=(ssize_t) image->columns; x != 0; x--)
{
SetPixelAlpha(image,GetPixelRed(jng_image,s),q);
q+=GetPixelChannels(image);
s+=GetPixelChannels(jng_image);
}
else
for (x=(ssize_t) image->columns; x != 0; x--)
{
SetPixelAlpha(image,GetPixelRed(jng_image,s),q);
if (GetPixelAlpha(image,q) != OpaqueAlpha)
image->alpha_trait=BlendPixelTrait;
q+=GetPixelChannels(image);
s+=GetPixelChannels(jng_image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage()");
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadJNGImage() reads a JPEG Network Graphics (JNG) image file
% (including the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadJNGImage method is:
%
% Image *ReadJNGImage(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 *ReadJNGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MagickPathExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info,exception);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a JNG datastream.
*/
if (GetBlobSize(image) < 147)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
}
#endif
static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
page_geometry[MagickPathExtent];
Image
*image;
MagickBooleanType
logging;
volatile int
first_mng_object,
object_id,
term_chunk_found,
skip_to_iend;
volatile ssize_t
image_count=0;
MagickBooleanType
status;
MagickOffsetType
offset;
MngBox
default_fb,
fb,
previous_fb;
#if defined(MNG_INSERT_LAYERS)
PixelInfo
mng_background_color;
#endif
register unsigned char
*p;
register ssize_t
i;
size_t
count;
ssize_t
loop_level;
volatile short
skipping_loop;
#if defined(MNG_INSERT_LAYERS)
unsigned int
mandatory_back=0;
#endif
volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
mng_background_object=0,
#endif
mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */
size_t
default_frame_timeout,
frame_timeout,
#if defined(MNG_INSERT_LAYERS)
image_height,
image_width,
#endif
length;
/* These delays are all measured in image ticks_per_second,
* not in MNG ticks_per_second
*/
volatile size_t
default_frame_delay,
final_delay,
final_image_delay,
frame_delay,
#if defined(MNG_INSERT_LAYERS)
insert_layers,
#endif
mng_iterations=1,
simplicity=0,
subframe_height=0,
subframe_width=0;
previous_fb.top=0;
previous_fb.bottom=0;
previous_fb.left=0;
previous_fb.right=0;
default_fb.top=0;
default_fb.bottom=0;
default_fb.left=0;
default_fb.right=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneMNGImage()");
image=mng_info->image;
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
char
magic_number[MagickPathExtent];
/* Verify MNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Initialize some nonzero members of the MngInfo structure. */
for (i=0; i < MNG_MAX_OBJECTS; i++)
{
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
mng_info->exists[0]=MagickTrue;
}
skipping_loop=(-1);
first_mng_object=MagickTrue;
mng_type=0;
#if defined(MNG_INSERT_LAYERS)
insert_layers=MagickFalse; /* should be False during convert or mogrify */
#endif
default_frame_delay=0;
default_frame_timeout=0;
frame_delay=0;
final_delay=1;
mng_info->ticks_per_second=1UL*image->ticks_per_second;
object_id=0;
skip_to_iend=MagickFalse;
term_chunk_found=MagickFalse;
mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
mng_background_color=image->background_color;
#endif
default_fb=mng_info->frame;
previous_fb=mng_info->frame;
do
{
char
type[MagickPathExtent];
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
unsigned char
*chunk;
/*
Read a new chunk.
*/
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MagickPathExtent);
length=ReadBlobMSBLong(image);
count=(size_t) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading MNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX)
{
status=MagickFalse;
break;
}
if (count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
#if !defined(JNG_SUPPORTED)
if (memcmp(type,mng_JHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->jhdr_warning == 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"JNGCompressNotSupported","`%s'",image->filename);
mng_info->jhdr_warning++;
}
#endif
if (memcmp(type,mng_DHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->dhdr_warning == 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"DeltaPNGNotSupported","`%s'",image->filename);
mng_info->dhdr_warning++;
}
if (memcmp(type,mng_MEND,4) == 0)
break;
if (skip_to_iend)
{
if (memcmp(type,mng_IEND,4) == 0)
skip_to_iend=MagickFalse;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skip to IEND.");
continue;
}
if (memcmp(type,mng_MHDR,4) == 0)
{
if (length != 28)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
mng_info->mng_width=(unsigned long) (((png_uint_32) p[0] << 24) |
((png_uint_32) p[1] << 16) | ((png_uint_32) p[2] << 8) |
(png_uint_32) p[3]);
mng_info->mng_height=(unsigned long) (((png_uint_32) p[4] << 24) |
((png_uint_32) p[5] << 16) | ((png_uint_32) p[6] << 8) |
(png_uint_32) p[7]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG width: %.20g",(double) mng_info->mng_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG height: %.20g",(double) mng_info->mng_height);
}
p+=8;
mng_info->ticks_per_second=(size_t) mng_get_long(p);
if (mng_info->ticks_per_second == 0)
default_frame_delay=0;
else
default_frame_delay=1UL*image->ticks_per_second/
mng_info->ticks_per_second;
frame_delay=default_frame_delay;
simplicity=0;
p+=16;
simplicity=(size_t) mng_get_long(p);
mng_type=1; /* Full MNG */
if ((simplicity != 0) && ((simplicity | 11) == 11))
mng_type=2; /* LC */
if ((simplicity != 0) && ((simplicity | 9) == 9))
mng_type=3; /* VLC */
#if defined(MNG_INSERT_LAYERS)
if (mng_type != 3)
insert_layers=MagickTrue;
#endif
if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
{
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return((Image *) NULL);
image=SyncNextImageInList(image);
mng_info->image=image;
}
if ((mng_info->mng_width > 65535L) ||
(mng_info->mng_height > 65535L))
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
}
(void) FormatLocaleString(page_geometry,MagickPathExtent,
"%.20gx%.20g+0+0",(double) mng_info->mng_width,(double)
mng_info->mng_height);
mng_info->frame.left=0;
mng_info->frame.right=(ssize_t) mng_info->mng_width;
mng_info->frame.top=0;
mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
mng_info->clip=default_fb=previous_fb=mng_info->frame;
for (i=0; i < MNG_MAX_OBJECTS; i++)
mng_info->object_clip[i]=mng_info->frame;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_TERM,4) == 0)
{
int
repeat=0;
if (length != 0)
repeat=p[0];
if (repeat == 3 && length > 8)
{
final_delay=(png_uint_32) mng_get_long(&p[2]);
mng_iterations=(png_uint_32) mng_get_long(&p[6]);
if (mng_iterations == PNG_UINT_31_MAX)
mng_iterations=0;
image->iterations=mng_iterations;
term_chunk_found=MagickTrue;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" repeat=%d, final_delay=%.20g, iterations=%.20g",
repeat,(double) final_delay, (double) image->iterations);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_DEFI,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'",
image->filename);
if (length < 2)
{
if (chunk)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
object_id=(p[0] << 8) | p[1];
if (mng_type == 2 && object_id != 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"Nonzero object_id in MNG-LC datastream","`%s'",
image->filename);
if (object_id > MNG_MAX_OBJECTS)
{
/*
Instead of using a warning we should allocate a larger
MngInfo structure and continue.
*/
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"object id too large","`%s'",image->filename);
object_id=MNG_MAX_OBJECTS;
}
if (mng_info->exists[object_id])
if (mng_info->frozen[object_id])
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
(void) ThrowMagickException(exception,
GetMagickModule(),CoderError,
"DEFI cannot redefine a frozen MNG object","`%s'",
image->filename);
continue;
}
mng_info->exists[object_id]=MagickTrue;
if (length > 2)
mng_info->invisible[object_id]=p[2];
/*
Extract object offset info.
*/
if (length > 11)
{
mng_info->x_off[object_id]=(ssize_t)
(((png_uint_32) p[4] << 24) | ((png_uint_32) p[5] << 16) |
((png_uint_32) p[6] << 8) | (png_uint_32) p[7]);
mng_info->y_off[object_id]=(ssize_t)
(((png_uint_32) p[8] << 24) | ((png_uint_32) p[9] << 16) |
((png_uint_32) p[10] << 8) | (png_uint_32) p[11]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_off[%d]: %.20g, y_off[%d]: %.20g",
object_id,(double) mng_info->x_off[object_id],
object_id,(double) mng_info->y_off[object_id]);
}
}
/*
Extract object clipping info.
*/
if (length > 27)
mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0,
&p[12]);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
mng_info->have_global_bkgd=MagickFalse;
if (length > 5)
{
mng_info->mng_global_bkgd.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_info->mng_global_bkgd.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_info->mng_global_bkgd.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_info->have_global_bkgd=MagickTrue;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_BACK,4) == 0)
{
#if defined(MNG_INSERT_LAYERS)
if (length > 6)
mandatory_back=p[6];
else
mandatory_back=0;
if (mandatory_back && length > 5)
{
mng_background_color.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_background_color.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_background_color.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_background_color.alpha=OpaqueAlpha;
}
#ifdef MNG_OBJECT_BUFFERS
if (length > 8)
mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_PLTE,4) == 0)
{
/* Read global PLTE. */
if (length && (length < 769))
{
if (mng_info->global_plte == (png_colorp) NULL)
mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
sizeof(*mng_info->global_plte));
for (i=0; i < (ssize_t) (length/3); i++)
{
mng_info->global_plte[i].red=p[3*i];
mng_info->global_plte[i].green=p[3*i+1];
mng_info->global_plte[i].blue=p[3*i+2];
}
mng_info->global_plte_length=(unsigned int) (length/3);
}
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
{
mng_info->global_plte[i].red=i;
mng_info->global_plte[i].green=i;
mng_info->global_plte[i].blue=i;
}
if (length != 0)
mng_info->global_plte_length=256;
#endif
else
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_tRNS,4) == 0)
{
/* read global tRNS */
if (length > 0 && length < 257)
for (i=0; i < (ssize_t) length; i++)
mng_info->global_trns[i]=p[i];
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
mng_info->global_trns[i]=255;
#endif
mng_info->global_trns_length=(unsigned int) length;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
{
ssize_t
igamma;
igamma=mng_get_long(p);
mng_info->global_gamma=((float) igamma)*0.00001;
mng_info->have_global_gama=MagickTrue;
}
else
mng_info->have_global_gama=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
/* Read global cHRM */
if (length == 32)
{
mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
mng_info->global_chrm.red_primary.y=0.00001*
mng_get_long(&p[12]);
mng_info->global_chrm.green_primary.x=0.00001*
mng_get_long(&p[16]);
mng_info->global_chrm.green_primary.y=0.00001*
mng_get_long(&p[20]);
mng_info->global_chrm.blue_primary.x=0.00001*
mng_get_long(&p[24]);
mng_info->global_chrm.blue_primary.y=0.00001*
mng_get_long(&p[28]);
mng_info->have_global_chrm=MagickTrue;
}
else
mng_info->have_global_chrm=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
/*
Read global sRGB.
*/
if (length != 0)
{
mng_info->global_srgb_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
mng_info->have_global_srgb=MagickTrue;
}
else
mng_info->have_global_srgb=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
/*
Read global iCCP.
*/
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_FRAM,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'",
image->filename);
if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
image->delay=frame_delay;
frame_delay=default_frame_delay;
frame_timeout=default_frame_timeout;
fb=default_fb;
if (length != 0)
if (p[0])
mng_info->framing_mode=p[0];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_mode=%d",mng_info->framing_mode);
if (length > 6)
{
/* Note the delay and frame clipping boundaries. */
p++; /* framing mode */
while (*p && ((p-chunk) < (ssize_t) length))
p++; /* frame name */
p++; /* frame name terminator */
if ((p-chunk) < (ssize_t) (length-4))
{
int
change_delay,
change_timeout,
change_clipping;
change_delay=(*p++);
change_timeout=(*p++);
change_clipping=(*p++);
p++; /* change_sync */
if (change_delay && ((p-chunk) < (ssize_t) (length-4)))
{
frame_delay=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_delay/=mng_info->ticks_per_second;
else
frame_delay=PNG_UINT_31_MAX;
if (change_delay == 2)
default_frame_delay=frame_delay;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_delay=%.20g",(double) frame_delay);
}
if (change_timeout && ((p-chunk) < (ssize_t) (length-4)))
{
frame_timeout=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_timeout/=mng_info->ticks_per_second;
else
frame_timeout=PNG_UINT_31_MAX;
if (change_timeout == 2)
default_frame_timeout=frame_timeout;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_timeout=%.20g",(double) frame_timeout);
}
if (change_clipping && ((p-chunk) < (ssize_t) (length-16)))
{
fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
p+=16;
previous_fb=fb;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g",
(double) fb.left,(double) fb.right,(double) fb.top,
(double) fb.bottom);
if (change_clipping == 2)
default_fb=fb;
}
}
}
mng_info->clip=fb;
mng_info->clip=mng_minimum_box(fb,mng_info->frame);
subframe_width=(size_t) (mng_info->clip.right
-mng_info->clip.left);
subframe_height=(size_t) (mng_info->clip.bottom
-mng_info->clip.top);
/*
Insert a background layer behind the frame if framing_mode is 4.
*/
#if defined(MNG_INSERT_LAYERS)
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" subframe_width=%.20g, subframe_height=%.20g",(double)
subframe_width,(double) subframe_height);
if (insert_layers && (mng_info->framing_mode == 4) &&
(subframe_width) && (subframe_height))
{
/* Allocate next image structure. */
if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
{
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->alpha_trait=UndefinedPixelTrait;
image->delay=0;
(void) SetImageBackgroundColor(image,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,
(double) mng_info->clip.right,
(double) mng_info->clip.top,
(double) mng_info->clip.bottom);
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLIP,4) == 0)
{
unsigned int
first_object,
last_object;
/*
Read CLIP.
*/
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(int) first_object; i <= (int) last_object; i++)
{
if ((i < 0) || (i >= MNG_MAX_OBJECTS))
continue;
if (mng_info->exists[i] && !mng_info->frozen[i])
{
MngBox
box;
box=mng_info->object_clip[i];
if ((p-chunk) < (ssize_t) (length-17))
mng_info->object_clip[i]=
mng_read_box(box,(char) p[0],&p[1]);
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_SAVE,4) == 0)
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
if (mng_info->exists[i])
{
mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
mng_info->ob[i]->frozen=MagickTrue;
#endif
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
{
/* Read DISC or SEEK. */
if ((length == 0) || !memcmp(type,mng_SEEK,4))
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
}
else
{
register ssize_t
j;
for (j=1; j < (ssize_t) length; j+=2)
{
i=p[j-1] << 8 | p[j];
MngInfoDiscardObject(mng_info,i);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_MOVE,4) == 0)
{
size_t
first_object,
last_object;
/* read MOVE */
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
if ((i < 0) || (i >= MNG_MAX_OBJECTS))
continue;
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
MngPair
new_pair;
MngPair
old_pair;
old_pair.a=mng_info->x_off[i];
old_pair.b=mng_info->y_off[i];
new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
mng_info->x_off[i]=new_pair.a;
mng_info->y_off[i]=new_pair.b;
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_LOOP,4) == 0)
{
ssize_t loop_iters=1;
if (length > 4)
{
loop_level=chunk[0];
mng_info->loop_active[loop_level]=1; /* mark loop active */
/* Record starting point. */
loop_iters=mng_get_long(&chunk[1]);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" LOOP level %.20g has %.20g iterations ",
(double) loop_level, (double) loop_iters);
if (loop_iters == 0)
skipping_loop=loop_level;
else
{
mng_info->loop_jump[loop_level]=TellBlob(image);
mng_info->loop_count[loop_level]=loop_iters;
}
mng_info->loop_iteration[loop_level]=0;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_ENDL,4) == 0)
{
if (length > 0)
{
loop_level=chunk[0];
if (skipping_loop > 0)
{
if (skipping_loop == loop_level)
{
/*
Found end of zero-iteration loop.
*/
skipping_loop=(-1);
mng_info->loop_active[loop_level]=0;
}
}
else
{
if (mng_info->loop_active[loop_level] == 1)
{
mng_info->loop_count[loop_level]--;
mng_info->loop_iteration[loop_level]++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ENDL: LOOP level %.20g has %.20g remaining iters",
(double) loop_level,(double)
mng_info->loop_count[loop_level]);
if (mng_info->loop_count[loop_level] != 0)
{
offset=
SeekBlob(image,mng_info->loop_jump[loop_level],
SEEK_SET);
if (offset < 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(
chunk);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
else
{
short
last_level;
/*
Finished loop.
*/
mng_info->loop_active[loop_level]=0;
last_level=(-1);
for (i=0; i < loop_level; i++)
if (mng_info->loop_active[i] == 1)
last_level=(short) i;
loop_level=last_level;
}
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLON,4) == 0)
{
if (mng_info->clon_warning == 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"CLON is not implemented yet","`%s'",
image->filename);
mng_info->clon_warning++;
}
if (memcmp(type,mng_MAGN,4) == 0)
{
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
if (length > 1)
magn_first=(p[0] << 8) | p[1];
else
magn_first=0;
if (length > 3)
magn_last=(p[2] << 8) | p[3];
else
magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
if (magn_first || magn_last)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(exception,
GetMagickModule(),CoderError,
"MAGN is not implemented yet for nonzero objects",
"`%s'",image->filename);
mng_info->magn_warning++;
}
#endif
if (length > 4)
magn_methx=p[4];
else
magn_methx=0;
if (length > 6)
magn_mx=(p[5] << 8) | p[6];
else
magn_mx=1;
if (magn_mx == 0)
magn_mx=1;
if (length > 8)
magn_my=(p[7] << 8) | p[8];
else
magn_my=magn_mx;
if (magn_my == 0)
magn_my=1;
if (length > 10)
magn_ml=(p[9] << 8) | p[10];
else
magn_ml=magn_mx;
if (magn_ml == 0)
magn_ml=1;
if (length > 12)
magn_mr=(p[11] << 8) | p[12];
else
magn_mr=magn_mx;
if (magn_mr == 0)
magn_mr=1;
if (length > 14)
magn_mt=(p[13] << 8) | p[14];
else
magn_mt=magn_my;
if (magn_mt == 0)
magn_mt=1;
if (length > 16)
magn_mb=(p[15] << 8) | p[16];
else
magn_mb=magn_my;
if (magn_mb == 0)
magn_mb=1;
if (length > 17)
magn_methy=p[17];
else
magn_methy=magn_methx;
if (magn_methx > 5 || magn_methy > 5)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(exception,
GetMagickModule(),CoderError,
"Unknown MAGN method in MNG datastream","`%s'",
image->filename);
mng_info->magn_warning++;
}
#ifdef MNG_OBJECT_BUFFERS
/* Magnify existing objects in the range magn_first to magn_last */
#endif
if (magn_first == 0 || magn_last == 0)
{
/* Save the magnification factors for object 0 */
mng_info->magn_mb=magn_mb;
mng_info->magn_ml=magn_ml;
mng_info->magn_mr=magn_mr;
mng_info->magn_mt=magn_mt;
mng_info->magn_mx=magn_mx;
mng_info->magn_my=magn_my;
mng_info->magn_methx=magn_methx;
mng_info->magn_methy=magn_methy;
}
}
if (memcmp(type,mng_PAST,4) == 0)
{
if (mng_info->past_warning == 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"PAST is not implemented yet","`%s'",
image->filename);
mng_info->past_warning++;
}
if (memcmp(type,mng_SHOW,4) == 0)
{
if (mng_info->show_warning == 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"SHOW is not implemented yet","`%s'",
image->filename);
mng_info->show_warning++;
}
if (memcmp(type,mng_sBIT,4) == 0)
{
if (length < 4)
mng_info->have_global_sbit=MagickFalse;
else
{
mng_info->global_sbit.gray=p[0];
mng_info->global_sbit.red=p[0];
mng_info->global_sbit.green=p[1];
mng_info->global_sbit.blue=p[2];
mng_info->global_sbit.alpha=p[3];
mng_info->have_global_sbit=MagickTrue;
}
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
mng_info->global_x_pixels_per_unit=
(size_t) mng_get_long(p);
mng_info->global_y_pixels_per_unit=
(size_t) mng_get_long(&p[4]);
mng_info->global_phys_unit_type=p[8];
mng_info->have_global_phys=MagickTrue;
}
else
mng_info->have_global_phys=MagickFalse;
}
if (memcmp(type,mng_pHYg,4) == 0)
{
if (mng_info->phyg_warning == 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"pHYg is not implemented.","`%s'",image->filename);
mng_info->phyg_warning++;
}
if (memcmp(type,mng_BASI,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->basi_warning == 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"BASI is not implemented yet","`%s'",
image->filename);
mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
basi_width=(unsigned long) (((png_uint_32) p[0] << 24) |
((png_uint_32) p[1] << 16) | ((png_uint_32) p[2] << 8) |
(png_uint_32) p[3]);
basi_height=(unsigned long) (((png_uint_32) p[4] << 24) |
((png_uint_32) p[5] << 16) | ((png_uint_32) p[6] << 8) |
(png_uint_32) p[7]);
basi_color_type=p[8];
basi_compression_method=p[9];
basi_filter_type=p[10];
basi_interlace_method=p[11];
if (length > 11)
basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13];
else
basi_red=0;
if (length > 13)
basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15];
else
basi_green=0;
if (length > 15)
basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17];
else
basi_blue=0;
if (length > 17)
basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19];
else
{
if (basi_sample_depth == 16)
basi_alpha=65535L;
else
basi_alpha=255;
}
if (length > 19)
basi_viewable=p[20];
else
basi_viewable=0;
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
&& memcmp(type,mng_JHDR,4)
#endif
)
{
/* Not an IHDR or JHDR chunk */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
/* Process IHDR */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]);
mng_info->exists[object_id]=MagickTrue;
mng_info->viewable[object_id]=MagickTrue;
if (mng_info->invisible[object_id])
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping invisible object");
skip_to_iend=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if defined(MNG_INSERT_LAYERS)
if (length < 8)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image_width=(size_t) mng_get_long(p);
image_height=(size_t) mng_get_long(&p[4]);
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
/*
Insert a transparent background layer behind the entire animation
if it is not full screen.
*/
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && mng_type && first_mng_object)
{
if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
(image_width < mng_info->mng_width) ||
(mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
(image_height < mng_info->mng_height) ||
(mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
{
if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
/* Make a background rectangle. */
image->delay=0;
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
(void) SetImageBackgroundColor(image,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Inserted transparent background layer, W=%.20g, H=%.20g",
(double) mng_info->mng_width,(double) mng_info->mng_height);
}
}
/*
Insert a background layer behind the upcoming image if
framing_mode is 3, and we haven't already inserted one.
*/
if (insert_layers && (mng_info->framing_mode == 3) &&
(subframe_width) && (subframe_height) && (simplicity == 0 ||
(simplicity & 0x08)))
{
if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->delay=0;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->alpha_trait=UndefinedPixelTrait;
(void) SetImageBackgroundColor(image,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif /* MNG_INSERT_LAYERS */
first_mng_object=MagickFalse;
if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
{
image->delay=frame_delay;
frame_delay=default_frame_delay;
}
else
image->delay=0;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=mng_info->x_off[object_id];
image->page.y=mng_info->y_off[object_id];
image->iterations=mng_iterations;
/*
Seek back to the beginning of the IHDR or JHDR chunk's length field.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Seeking back to beginning of %c%c%c%c chunk",type[0],type[1],
type[2],type[3]);
offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
mng_info->image=image;
mng_info->mng_type=mng_type;
mng_info->object_id=object_id;
if (memcmp(type,mng_IHDR,4) == 0)
image=ReadOnePNGImage(mng_info,image_info,exception);
#if defined(JNG_SUPPORTED)
else
image=ReadOneJNGImage(mng_info,image_info,exception);
#endif
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
if (image->columns == 0 || image->rows == 0)
{
(void) CloseBlob(image);
return(DestroyImageList(image));
}
mng_info->image=image;
if (mng_type)
{
MngBox
crop_box;
if (mng_info->magn_methx || mng_info->magn_methy)
{
png_uint_32
magnified_height,
magnified_width;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing MNG MAGN chunk");
if (mng_info->magn_methx == 1)
{
magnified_width=mng_info->magn_ml;
if (image->columns > 1)
magnified_width += mng_info->magn_mr;
if (image->columns > 2)
magnified_width += (png_uint_32)
((image->columns-2)*(mng_info->magn_mx));
}
else
{
magnified_width=(png_uint_32) image->columns;
if (image->columns > 1)
magnified_width += mng_info->magn_ml-1;
if (image->columns > 2)
magnified_width += mng_info->magn_mr-1;
if (image->columns > 3)
magnified_width += (png_uint_32)
((image->columns-3)*(mng_info->magn_mx-1));
}
if (mng_info->magn_methy == 1)
{
magnified_height=mng_info->magn_mt;
if (image->rows > 1)
magnified_height += mng_info->magn_mb;
if (image->rows > 2)
magnified_height += (png_uint_32)
((image->rows-2)*(mng_info->magn_my));
}
else
{
magnified_height=(png_uint_32) image->rows;
if (image->rows > 1)
magnified_height += mng_info->magn_mt-1;
if (image->rows > 2)
magnified_height += mng_info->magn_mb-1;
if (image->rows > 3)
magnified_height += (png_uint_32)
((image->rows-3)*(mng_info->magn_my-1));
}
if (magnified_height > image->rows ||
magnified_width > image->columns)
{
Image
*large_image;
int
yy;
Quantum
*next,
*prev;
png_uint_16
magn_methx,
magn_methy;
ssize_t
m,
y;
register Quantum
*n,
*q;
register ssize_t
x;
/* Allocate next image structure. */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocate magnified image");
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
large_image=SyncNextImageInList(image);
large_image->columns=magnified_width;
large_image->rows=magnified_height;
magn_methx=mng_info->magn_methx;
magn_methy=mng_info->magn_methy;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
if (magn_methx != 1 || magn_methy != 1)
{
/*
Scale pixels to unsigned shorts to prevent
overflow of intermediate values of interpolations
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(image,ScaleQuantumToShort(
GetPixelRed(image,q)),q);
SetPixelGreen(image,ScaleQuantumToShort(
GetPixelGreen(image,q)),q);
SetPixelBlue(image,ScaleQuantumToShort(
GetPixelBlue(image,q)),q);
SetPixelAlpha(image,ScaleQuantumToShort(
GetPixelAlpha(image,q)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#else
#define QM Quantum
#endif
if (image->alpha_trait != UndefinedPixelTrait)
(void) SetImageBackgroundColor(large_image,exception);
else
{
large_image->background_color.alpha=OpaqueAlpha;
(void) SetImageBackgroundColor(large_image,exception);
if (magn_methx == 4)
magn_methx=2;
if (magn_methx == 5)
magn_methx=3;
if (magn_methy == 4)
magn_methy=2;
if (magn_methy == 5)
magn_methy=3;
}
/* magnify the rows into the right side of the large image */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the rows to %.20g",
(double) large_image->rows);
m=(ssize_t) mng_info->magn_mt;
yy=0;
length=(size_t) GetPixelChannels(image)*image->columns;
next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next));
prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev));
if ((prev == (Quantum *) NULL) ||
(next == (Quantum *) NULL))
{
image=DestroyImageList(image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
(void) CopyMagickMemory(next,n,length);
for (y=0; y < (ssize_t) image->rows; y++)
{
if (y == 0)
m=(ssize_t) mng_info->magn_mt;
else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
m=1;
else
m=(ssize_t) mng_info->magn_my;
n=prev;
prev=next;
next=n;
if (y < (ssize_t) image->rows-1)
{
n=GetAuthenticPixels(image,0,y+1,image->columns,1,
exception);
(void) CopyMagickMemory(next,n,length);
}
for (i=0; i < m; i++, yy++)
{
register Quantum
*pixels;
assert(yy < (ssize_t) large_image->rows);
pixels=prev;
n=next;
q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
1,exception);
q+=(large_image->columns-image->columns)*
GetPixelChannels(large_image);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
/* To do: get color as function of indexes[x] */
/*
if (image->storage_class == PseudoClass)
{
}
*/
if (magn_methy <= 1)
{
/* replicate previous */
SetPixelRed(large_image,GetPixelRed(image,pixels),q);
SetPixelGreen(large_image,GetPixelGreen(image,
pixels),q);
SetPixelBlue(large_image,GetPixelBlue(image,
pixels),q);
SetPixelAlpha(large_image,GetPixelAlpha(image,
pixels),q);
}
else if (magn_methy == 2 || magn_methy == 4)
{
if (i == 0)
{
SetPixelRed(large_image,GetPixelRed(image,
pixels),q);
SetPixelGreen(large_image,GetPixelGreen(image,
pixels),q);
SetPixelBlue(large_image,GetPixelBlue(image,
pixels),q);
SetPixelAlpha(large_image,GetPixelAlpha(image,
pixels),q);
}
else
{
/* Interpolate */
SetPixelRed(large_image,((QM) (((ssize_t)
(2*i*(GetPixelRed(image,n)
-GetPixelRed(image,pixels)+m))/
((ssize_t) (m*2))
+GetPixelRed(image,pixels)))),q);
SetPixelGreen(large_image,((QM) (((ssize_t)
(2*i*(GetPixelGreen(image,n)
-GetPixelGreen(image,pixels)+m))/
((ssize_t) (m*2))
+GetPixelGreen(image,pixels)))),q);
SetPixelBlue(large_image,((QM) (((ssize_t)
(2*i*(GetPixelBlue(image,n)
-GetPixelBlue(image,pixels)+m))/
((ssize_t) (m*2))
+GetPixelBlue(image,pixels)))),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(large_image, ((QM) (((ssize_t)
(2*i*(GetPixelAlpha(image,n)
-GetPixelAlpha(image,pixels)+m))
/((ssize_t) (m*2))+
GetPixelAlpha(image,pixels)))),q);
}
if (magn_methy == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
SetPixelAlpha(large_image,GetPixelAlpha(image,
pixels),q);
else
SetPixelAlpha(large_image,GetPixelAlpha(image,
n),q);
}
}
else /* if (magn_methy == 3 || magn_methy == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRed(large_image,GetPixelRed(image,
pixels),q);
SetPixelGreen(large_image,GetPixelGreen(image,
pixels),q);
SetPixelBlue(large_image,GetPixelBlue(image,
pixels),q);
SetPixelAlpha(large_image,GetPixelAlpha(image,
pixels),q);
}
else
{
SetPixelRed(large_image,GetPixelRed(image,n),q);
SetPixelGreen(large_image,GetPixelGreen(image,n),
q);
SetPixelBlue(large_image,GetPixelBlue(image,n),
q);
SetPixelAlpha(large_image,GetPixelAlpha(image,n),
q);
}
if (magn_methy == 5)
{
SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i*
(GetPixelAlpha(image,n)
-GetPixelAlpha(image,pixels))
+m))/((ssize_t) (m*2))
+GetPixelAlpha(image,pixels)),q);
}
}
n+=GetPixelChannels(image);
q+=GetPixelChannels(large_image);
pixels+=GetPixelChannels(image);
} /* x */
if (SyncAuthenticPixels(large_image,exception) == 0)
break;
} /* i */
} /* y */
prev=(Quantum *) RelinquishMagickMemory(prev);
next=(Quantum *) RelinquishMagickMemory(next);
length=image->columns;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Delete original image");
DeleteImageFromList(&image);
image=large_image;
mng_info->image=image;
/* magnify the columns */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the columns to %.20g",
(double) image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*pixels;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
pixels=q+(image->columns-length)*GetPixelChannels(image);
n=pixels+GetPixelChannels(image);
for (x=(ssize_t) (image->columns-length);
x < (ssize_t) image->columns; x++)
{
/* To do: Rewrite using Get/Set***PixelChannel() */
if (x == (ssize_t) (image->columns-length))
m=(ssize_t) mng_info->magn_ml;
else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx <= 1 &&
x == (ssize_t) image->columns-1)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
m=1;
else
m=(ssize_t) mng_info->magn_mx;
for (i=0; i < m; i++)
{
if (magn_methx <= 1)
{
/* replicate previous */
SetPixelRed(image,GetPixelRed(image,pixels),q);
SetPixelGreen(image,GetPixelGreen(image,pixels),q);
SetPixelBlue(image,GetPixelBlue(image,pixels),q);
SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);
}
else if (magn_methx == 2 || magn_methx == 4)
{
if (i == 0)
{
SetPixelRed(image,GetPixelRed(image,pixels),q);
SetPixelGreen(image,GetPixelGreen(image,pixels),q);
SetPixelBlue(image,GetPixelBlue(image,pixels),q);
SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);
}
/* To do: Rewrite using Get/Set***PixelChannel() */
else
{
/* Interpolate */
SetPixelRed(image,(QM) ((2*i*(
GetPixelRed(image,n)
-GetPixelRed(image,pixels))+m)
/((ssize_t) (m*2))+
GetPixelRed(image,pixels)),q);
SetPixelGreen(image,(QM) ((2*i*(
GetPixelGreen(image,n)
-GetPixelGreen(image,pixels))+m)
/((ssize_t) (m*2))+
GetPixelGreen(image,pixels)),q);
SetPixelBlue(image,(QM) ((2*i*(
GetPixelBlue(image,n)
-GetPixelBlue(image,pixels))+m)
/((ssize_t) (m*2))+
GetPixelBlue(image,pixels)),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,(QM) ((2*i*(
GetPixelAlpha(image,n)
-GetPixelAlpha(image,pixels))+m)
/((ssize_t) (m*2))+
GetPixelAlpha(image,pixels)),q);
}
if (magn_methx == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelAlpha(image,
GetPixelAlpha(image,pixels)+0,q);
}
else
{
SetPixelAlpha(image,
GetPixelAlpha(image,n)+0,q);
}
}
}
else /* if (magn_methx == 3 || magn_methx == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRed(image,GetPixelRed(image,pixels),q);
SetPixelGreen(image,GetPixelGreen(image,
pixels),q);
SetPixelBlue(image,GetPixelBlue(image,pixels),q);
SetPixelAlpha(image,GetPixelAlpha(image,
pixels),q);
}
else
{
SetPixelRed(image,GetPixelRed(image,n),q);
SetPixelGreen(image,GetPixelGreen(image,n),q);
SetPixelBlue(image,GetPixelBlue(image,n),q);
SetPixelAlpha(image,GetPixelAlpha(image,n),q);
}
if (magn_methx == 5)
{
/* Interpolate */
SetPixelAlpha(image,
(QM) ((2*i*( GetPixelAlpha(image,n)
-GetPixelAlpha(image,pixels))+m)/
((ssize_t) (m*2))
+GetPixelAlpha(image,pixels)),q);
}
}
q+=GetPixelChannels(image);
}
n+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
if (magn_methx != 1 || magn_methy != 1)
{
/*
Rescale pixels to Quantum
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(image,ScaleShortToQuantum(
GetPixelRed(image,q)),q);
SetPixelGreen(image,ScaleShortToQuantum(
GetPixelGreen(image,q)),q);
SetPixelBlue(image,ScaleShortToQuantum(
GetPixelBlue(image,q)),q);
SetPixelAlpha(image,ScaleShortToQuantum(
GetPixelAlpha(image,q)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished MAGN processing");
}
}
/*
Crop_box is with respect to the upper left corner of the MNG.
*/
crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
crop_box=mng_minimum_box(crop_box,mng_info->clip);
crop_box=mng_minimum_box(crop_box,mng_info->frame);
crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
if ((crop_box.left != (mng_info->image_box.left
+mng_info->x_off[object_id])) ||
(crop_box.right != (mng_info->image_box.right
+mng_info->x_off[object_id])) ||
(crop_box.top != (mng_info->image_box.top
+mng_info->y_off[object_id])) ||
(crop_box.bottom != (mng_info->image_box.bottom
+mng_info->y_off[object_id])))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Crop the PNG image");
if ((crop_box.left < crop_box.right) &&
(crop_box.top < crop_box.bottom))
{
Image
*im;
RectangleInfo
crop_info;
/*
Crop_info is with respect to the upper left corner of
the image.
*/
crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
crop_info.width=(size_t) (crop_box.right-crop_box.left);
crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=0;
image->page.y=0;
im=CropImage(image,&crop_info,exception);
if (im != (Image *) NULL)
{
image->columns=im->columns;
image->rows=im->rows;
im=DestroyImage(im);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=crop_box.left;
image->page.y=crop_box.top;
}
}
else
{
/*
No pixels in crop area. The MNG spec still requires
a layer, though, so make a single transparent pixel in
the top left corner.
*/
image->columns=1;
image->rows=1;
image->colors=2;
(void) SetImageBackgroundColor(image,exception);
image->page.width=1;
image->page.height=1;
image->page.x=0;
image->page.y=0;
}
}
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
image=mng_info->image;
#endif
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy.
*/
if (image->depth > 16)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (LosslessReduceDepthOK(image,exception) != MagickFalse)
image->depth = 8;
#endif
if (image_info->number_scenes != 0)
{
if (mng_info->scenes_found >
(ssize_t) (image_info->first_scene+image_info->number_scenes))
break;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading image datastream.");
} while (LocaleCompare(image_info->magick,"MNG") == 0);
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading all image datastreams.");
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
(mng_info->mng_height))
{
/*
Insert a background layer if nothing else was found.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No images found. Inserting a background layer.");
if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocation failed, returning NULL.");
return(DestroyImageList(image));;
}
image=SyncNextImageInList(image);
}
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
image->alpha_trait=UndefinedPixelTrait;
if (image_info->ping == MagickFalse)
(void) SetImageBackgroundColor(image,exception);
mng_info->image_found++;
}
#endif
image->iterations=mng_iterations;
if (mng_iterations == 1)
image->start_loop=MagickTrue;
while (GetPreviousImageInList(image) != (Image *) NULL)
{
image_count++;
if (image_count > 10*mng_info->image_found)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning");
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"Linked list is corrupted, beginning of list not found",
"`%s'",image_info->filename);
return(DestroyImageList(image));
}
image=GetPreviousImageInList(image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list");
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"Linked list is corrupted; next_image is NULL","`%s'",
image_info->filename);
}
}
if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
GetNextImageInList(image) ==
(Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" First image null");
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"image->next for first image is NULL but shouldn't be.",
"`%s'",image_info->filename);
}
if (mng_info->image_found == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No visible images found.");
(void) ThrowMagickException(exception,GetMagickModule(),
CoderError,"No visible images in file","`%s'",image_info->filename);
return(DestroyImageList(image));
}
if (mng_info->ticks_per_second)
final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
final_delay/mng_info->ticks_per_second;
else
image->start_loop=MagickTrue;
/* Find final nonzero image delay */
final_image_delay=0;
while (GetNextImageInList(image) != (Image *) NULL)
{
if (image->delay)
final_image_delay=image->delay;
image=GetNextImageInList(image);
}
if (final_delay < final_image_delay)
final_delay=final_image_delay;
image->delay=final_delay;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->delay=%.20g, final_delay=%.20g",(double) image->delay,
(double) final_delay);
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g",(double) image->delay);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g",(double) scene++,
(double) image->delay);
}
}
image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
if (insert_layers)
{
Image
*next_image,
*next;
size_t
scene;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Coalesce Images");
scene=image->scene;
next_image=CoalesceImages(image,exception);
if (next_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImageList(image);
image=next_image;
for (next=image; next != (Image *) NULL; next=next_image)
{
next->page.width=mng_info->mng_width;
next->page.height=mng_info->mng_height;
next->page.x=0;
next->page.y=0;
next->scene=scene++;
next_image=GetNextImageInList(next);
if (next_image == (Image *) NULL)
break;
if (next->delay == 0)
{
scene--;
next_image->previous=GetPreviousImageInList(next);
if (GetPreviousImageInList(next) == (Image *) NULL)
image=next_image;
else
next->previous->next=next_image;
next=DestroyImage(next);
}
}
}
#endif
while (GetNextImageInList(image) != (Image *) NULL)
image=GetNextImageInList(image);
image->dispose=BackgroundDispose;
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" After coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g dispose=%.20g",(double) image->delay,
(double) image->dispose);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g dispose=%.20g",(double) scene++,
(double) image->delay,(double) image->dispose);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneMNGImage();");
return(image);
}
static Image *ReadMNGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
/* Open image file. */
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()");
image=AcquireImage(image_info,exception);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneMNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadMNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()");
return(GetFirstImageInList(image));
}
#else /* PNG_LIBPNG_VER > 10011 */
static Image *ReadPNGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
printf("Your PNG library is too old: You have libpng-%s\n",
PNG_LIBPNG_VER_STRING);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"PNG library is too old","`%s'",image_info->filename);
return(Image *) NULL;
}
static Image *ReadMNGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
return(ReadPNGImage(image_info,exception));
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNGImage() adds properties for the PNG 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 RegisterPNGImage method is:
%
% size_t RegisterPNGImage(void)
%
*/
ModuleExport size_t RegisterPNGImage(void)
{
char
version[MagickPathExtent];
MagickInfo
*entry;
static const char
*PNGNote=
{
"See http://www.libpng.org/ for details about the PNG format."
},
*JNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the JNG\n"
"format."
},
*MNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the MNG\n"
"format."
};
*version='\0';
#if defined(PNG_LIBPNG_VER_STRING)
(void) ConcatenateMagickString(version,"libpng ",MagickPathExtent);
(void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,
MagickPathExtent);
if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0)
{
(void) ConcatenateMagickString(version,",",MagickPathExtent);
(void) ConcatenateMagickString(version,png_get_libpng_ver(NULL),
MagickPathExtent);
}
#endif
entry=AcquireMagickInfo("PNG","MNG","Multiple-image Network Graphics");
entry->flags|=CoderDecoderSeekableStreamFlag;
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadMNGImage;
entry->encoder=(EncodeImageHandler *) WriteMNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsMNG;
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("video/x-mng");
entry->note=ConstantString(MNGNote);
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNG","PNG","Portable Network Graphics");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->mime_type=ConstantString("image/png");
if (*version != '\0')
entry->version=ConstantString(version);
entry->note=ConstantString(PNGNote);
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNG","PNG8",
"8-bit indexed with optional binary transparency");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->mime_type=ConstantString("image/png");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNG","PNG24",
"opaque or binary transparent 24-bit RGB");
*version='\0';
#if defined(ZLIB_VERSION)
(void) ConcatenateMagickString(version,"zlib ",MagickPathExtent);
(void) ConcatenateMagickString(version,ZLIB_VERSION,MagickPathExtent);
if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0)
{
(void) ConcatenateMagickString(version,",",MagickPathExtent);
(void) ConcatenateMagickString(version,zlib_version,MagickPathExtent);
}
#endif
if (*version != '\0')
entry->version=ConstantString(version);
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->mime_type=ConstantString("image/png");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNG","PNG32","opaque or transparent 32-bit RGBA");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->mime_type=ConstantString("image/png");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNG","PNG48",
"opaque or binary transparent 48-bit RGB");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->mime_type=ConstantString("image/png");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNG","PNG64","opaque or transparent 64-bit RGBA");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->mime_type=ConstantString("image/png");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNG","PNG00",
"PNG inheriting bit-depth, color-type from original, if possible");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->mime_type=ConstantString("image/png");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNG","JNG","JPEG Network Graphics");
#if defined(JNG_SUPPORTED)
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJNGImage;
entry->encoder=(EncodeImageHandler *) WriteJNGImage;
#endif
#endif
entry->magick=(IsImageFormatHandler *) IsJNG;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->mime_type=ConstantString("image/x-jng");
entry->note=ConstantString(JNGNote);
(void) RegisterMagickInfo(entry);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
ping_semaphore=AcquireSemaphoreInfo();
#endif
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNGImage() removes format registrations made by the
% PNG module from the list of supported formats.
%
% The format of the UnregisterPNGImage method is:
%
% UnregisterPNGImage(void)
%
*/
ModuleExport void UnregisterPNGImage(void)
{
(void) UnregisterMagickInfo("MNG");
(void) UnregisterMagickInfo("PNG");
(void) UnregisterMagickInfo("PNG8");
(void) UnregisterMagickInfo("PNG24");
(void) UnregisterMagickInfo("PNG32");
(void) UnregisterMagickInfo("PNG48");
(void) UnregisterMagickInfo("PNG64");
(void) UnregisterMagickInfo("PNG00");
(void) UnregisterMagickInfo("JNG");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
if (ping_semaphore != (SemaphoreInfo *) NULL)
RelinquishSemaphoreInfo(&ping_semaphore);
#endif
}
#if defined(MAGICKCORE_PNG_DELEGATE)
#if PNG_LIBPNG_VER > 10011
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMNGImage() writes an image in the Portable Network Graphics
% Group's "Multiple-image Network Graphics" encoded image format.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WriteMNGImage method is:
%
% MagickBooleanType WriteMNGImage(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.
%
% To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also
% "To do" under ReadPNGImage):
%
% Preserve all unknown and not-yet-handled known chunks found in input
% PNG file and copy them into output PNG files according to the PNG
% copying rules.
%
% Write the iCCP chunk at MNG level when (icc profile length > 0)
%
% Improve selection of color type (use indexed-colour or indexed-colour
% with tRNS when 256 or fewer unique RGBA values are present).
%
% Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3)
% This will be complicated if we limit ourselves to generating MNG-LC
% files. For now we ignore disposal method 3 and simply overlay the next
% image on it.
%
% Check for identical PLTE's or PLTE/tRNS combinations and use a
% global MNG PLTE or PLTE/tRNS combination when appropriate.
% [mostly done 15 June 1999 but still need to take care of tRNS]
%
% Check for identical sRGB and replace with a global sRGB (and remove
% gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and
% replace with global gAMA/cHRM (or with sRGB if appropriate; replace
% local gAMA/cHRM with local sRGB if appropriate).
%
% Check for identical sBIT chunks and write global ones.
%
% Provide option to skip writing the signature tEXt chunks.
%
% Use signatures to detect identical objects and reuse the first
% instance of such objects instead of writing duplicate objects.
%
% Use a smaller-than-32k value of compression window size when
% appropriate.
%
% Encode JNG datastreams. Mostly done as of 5.5.2; need to write
% ancillary text chunks and save profiles.
%
% Provide an option to force LC files (to ensure exact framing rate)
% instead of VLC.
%
% Provide an option to force VLC files instead of LC, even when offsets
% are present. This will involve expanding the embedded images with a
% transparent region at the top and/or left.
*/
static void
Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping,
png_info *ping_info, unsigned char *profile_type, unsigned char
*profile_description, unsigned char *profile_data, png_uint_32 length)
{
png_textp
text;
register ssize_t
i;
unsigned char
*sp;
png_charp
dp;
png_uint_32
allocated_length,
description_length;
unsigned char
hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0)
return;
if (image_info->verbose)
{
(void) printf("writing raw profile: type=%s, length=%.20g\n",
(char *) profile_type, (double) length);
}
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
description_length=(png_uint_32) strlen((const char *) profile_description);
allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20
+ description_length);
#if PNG_LIBPNG_VER >= 10400
text[0].text=(png_charp) png_malloc(ping,
(png_alloc_size_t) allocated_length);
text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80);
#else
text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length);
text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80);
#endif
text[0].key[0]='\0';
(void) ConcatenateMagickString(text[0].key,
"Raw profile type ",MagickPathExtent);
(void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62);
sp=profile_data;
dp=text[0].text;
*dp++='\n';
(void) CopyMagickString(dp,(const char *) profile_description,
allocated_length);
dp+=description_length;
*dp++='\n';
(void) FormatLocaleString(dp,allocated_length-
(png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length);
dp+=8;
for (i=0; i < (ssize_t) length; i++)
{
if (i%36 == 0)
*dp++='\n';
*(dp++)=(char) hex[((*sp >> 4) & 0x0f)];
*(dp++)=(char) hex[((*sp++ ) & 0x0f)];
}
*dp++='\n';
*dp='\0';
text[0].text_length=(png_size_t) (dp-text[0].text);
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? -1 : 0;
if (text[0].text_length <= allocated_length)
png_set_text(ping,ping_info,text,1);
png_free(ping,text[0].text);
png_free(ping,text[0].key);
png_free(ping,text);
}
static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image,
const char *string, MagickBooleanType logging)
{
char
*name;
const StringInfo
*profile;
unsigned char
*data;
png_uint_32 length;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (const StringInfo *) NULL)
{
StringInfo
*ping_profile;
if (LocaleNCompare(name,string,11) == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found %s profile",name);
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
data[4]=data[3];
data[3]=data[2];
data[2]=data[1];
data[1]=data[0];
(void) WriteBlobMSBULong(image,length-5); /* data length */
(void) WriteBlob(image,length-1,data+1);
(void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1));
ping_profile=DestroyStringInfo(ping_profile);
}
}
name=GetNextImageProfile(image);
}
return(MagickTrue);
}
static inline MagickBooleanType Magick_png_color_equal(const Image *image,
const Quantum *p, const PixelInfo *q)
{
MagickRealType
value;
value=(MagickRealType) p[image->channel_map[RedPixelChannel].offset];
if (AbsolutePixelValue(value-q->red) >= MagickEpsilon)
return(MagickFalse);
value=(MagickRealType) p[image->channel_map[GreenPixelChannel].offset];
if (AbsolutePixelValue(value-q->green) >= MagickEpsilon)
return(MagickFalse);
value=(MagickRealType) p[image->channel_map[BluePixelChannel].offset];
if (AbsolutePixelValue(value-q->blue) >= MagickEpsilon)
return(MagickFalse);
return(MagickTrue);
}
#if defined(PNG_tIME_SUPPORTED)
static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info,
const char *date,ExceptionInfo *exception)
{
unsigned int
day,
hour,
minute,
month,
second,
year;
png_time
ptime;
time_t
ttime;
if (date != (const char *) NULL)
{
if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute,
&second) != 6)
{
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"Invalid date format specified for png:tIME","`%s'",
image->filename);
return;
}
ptime.year=(png_uint_16) year;
ptime.month=(png_byte) month;
ptime.day=(png_byte) day;
ptime.hour=(png_byte) hour;
ptime.minute=(png_byte) minute;
ptime.second=(png_byte) second;
}
else
{
time(&ttime);
png_convert_from_time_t(&ptime,ttime);
}
png_set_tIME(ping,info,&ptime);
}
#endif
/* Write one PNG image */
static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,
const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception)
{
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
Image
*image;
ImageInfo
*image_info;
char
s[2];
const char
*name,
*property,
*value;
const StringInfo
*profile;
int
num_passes,
pass,
ping_wrote_caNv;
png_byte
ping_trans_alpha[256];
png_color
palette[257];
png_color_16
ping_background,
ping_trans_color;
png_info
*ping_info;
png_struct
*ping;
png_uint_32
ping_height,
ping_width;
ssize_t
y;
MagickBooleanType
image_matte,
logging,
matte,
ping_have_blob,
ping_have_cheap_transparency,
ping_have_color,
ping_have_non_bw,
ping_have_PLTE,
ping_have_bKGD,
ping_have_eXIf,
ping_have_iCCP,
ping_have_pHYs,
ping_have_sRGB,
ping_have_tRNS,
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
/* ping_exclude_EXIF, */
ping_exclude_eXIf,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tIME,
/* ping_exclude_tRNS, */
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
ping_preserve_iCCP,
ping_need_colortype_warning,
status,
tried_332,
tried_333,
tried_444;
MemoryInfo
*volatile pixel_info;
QuantumInfo
*quantum_info;
PNGErrorInfo
error_info;
register ssize_t
i,
x;
unsigned char
*ping_pixels;
volatile int
image_colors,
ping_bit_depth,
ping_color_type,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans;
volatile size_t
image_depth,
old_bit_depth;
size_t
quality,
rowbytes,
save_image_depth;
int
j,
number_colors,
number_opaque,
number_semitransparent,
number_transparent,
ping_pHYs_unit_type;
png_uint_32
ping_pHYs_x_resolution,
ping_pHYs_y_resolution;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOnePNGImage()");
image = CloneImage(IMimage,0,0,MagickFalse,exception);
image_info=(ImageInfo *) CloneImageInfo(IMimage_info);
if (image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed");
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,MagickPathExtent);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,MagickPathExtent);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s",
im_vers);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s",
libpng_vers);
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
/* Initialize some stuff */
ping_bit_depth=0,
ping_color_type=0,
ping_interlace_method=0,
ping_compression_method=0,
ping_filter_method=0,
ping_num_trans = 0;
ping_background.red = 0;
ping_background.green = 0;
ping_background.blue = 0;
ping_background.gray = 0;
ping_background.index = 0;
ping_trans_color.red=0;
ping_trans_color.green=0;
ping_trans_color.blue=0;
ping_trans_color.gray=0;
ping_pHYs_unit_type = 0;
ping_pHYs_x_resolution = 0;
ping_pHYs_y_resolution = 0;
ping_have_blob=MagickFalse;
ping_have_cheap_transparency=MagickFalse;
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
ping_have_PLTE=MagickFalse;
ping_have_bKGD=MagickFalse;
ping_have_eXIf=MagickTrue;
ping_have_iCCP=MagickFalse;
ping_have_pHYs=MagickFalse;
ping_have_sRGB=MagickFalse;
ping_have_tRNS=MagickFalse;
ping_exclude_bKGD=mng_info->ping_exclude_bKGD;
ping_exclude_caNv=mng_info->ping_exclude_caNv;
ping_exclude_cHRM=mng_info->ping_exclude_cHRM;
ping_exclude_date=mng_info->ping_exclude_date;
ping_exclude_eXIf=mng_info->ping_exclude_eXIf;
ping_exclude_gAMA=mng_info->ping_exclude_gAMA;
ping_exclude_iCCP=mng_info->ping_exclude_iCCP;
/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */
ping_exclude_oFFs=mng_info->ping_exclude_oFFs;
ping_exclude_pHYs=mng_info->ping_exclude_pHYs;
ping_exclude_sRGB=mng_info->ping_exclude_sRGB;
ping_exclude_tEXt=mng_info->ping_exclude_tEXt;
ping_exclude_tIME=mng_info->ping_exclude_tIME;
/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */
ping_exclude_vpAg=mng_info->ping_exclude_vpAg;
ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */
ping_exclude_zTXt=mng_info->ping_exclude_zTXt;
ping_preserve_colormap = mng_info->ping_preserve_colormap;
ping_preserve_iCCP = mng_info->ping_preserve_iCCP;
ping_need_colortype_warning = MagickFalse;
/* Recognize the ICC sRGB profile and convert it to the sRGB chunk,
* i.e., eliminate the ICC profile and set image->rendering_intent.
* Note that this will not involve any changes to the actual pixels
* but merely passes information to applications that read the resulting
* PNG image.
*
* To do: recognize other variants of the sRGB profile, using the CRC to
* verify all recognized variants including the 7 already known.
*
* Work around libpng16+ rejecting some "known invalid sRGB profiles".
*
* Use something other than image->rendering_intent to record the fact
* that the sRGB profile was found.
*
* Record the ICC version (currently v2 or v4) of the incoming sRGB ICC
* profile. Record the Blackpoint Compensation, if any.
*/
if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)
{
char
*name;
const StringInfo
*profile;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
ping_exclude_iCCP = MagickTrue;
ping_exclude_zCCP = MagickTrue;
ping_have_sRGB = MagickTrue;
break;
}
}
}
if (sRGB_info[icheck].len == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
}
}
name=GetNextImageProfile(image);
}
}
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
if (logging != MagickFalse)
{
if (image->storage_class == UndefinedClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=UndefinedClass");
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=DirectClass");
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?
" image->taint=MagickTrue":
" image->taint=MagickFalse");
}
if (image->storage_class == PseudoClass &&
(mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(mng_info->write_png_colortype != 1 &&
mng_info->write_png_colortype != 5)))
{
(void) SyncImage(image,exception);
image->storage_class = DirectClass;
}
if (ping_preserve_colormap == MagickFalse)
{
if (image->storage_class != PseudoClass && image->colormap != NULL)
{
/* Free the bogus colormap; it can cause trouble later */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Freeing bogus colormap");
(void) RelinquishMagickMemory(image->colormap);
image->colormap=NULL;
}
}
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Sometimes we get PseudoClass images whose RGB values don't match
the colors in the colormap. This code syncs the RGB values.
*/
if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->depth > 8)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reducing PNG bit depth to 8 since this is a Q8 build.");
image->depth=8;
}
#endif
/* Respect the -depth option */
if (image->depth < 4)
{
register Quantum
*r;
if (image->depth > 2)
{
/* Scale to 4-bit */
LBR04PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR04PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR04PacketRGBO(image->colormap[i]);
}
}
}
else if (image->depth > 1)
{
/* Scale to 2-bit */
LBR02PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR02PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR02PacketRGBO(image->colormap[i]);
}
}
}
else
{
/* Scale to 1-bit */
LBR01PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR01PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR01PacketRGBO(image->colormap[i]);
}
}
}
}
/* To do: set to next higher multiple of 8 */
if (image->depth < 8)
image->depth=8;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy
*/
if (image->depth > 8)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (image->depth == 16 && mng_info->write_png_depth != 16)
if (mng_info->write_png8 ||
LosslessReduceDepthOK(image,exception) != MagickFalse)
image->depth = 8;
#endif
image_colors = (int) image->colors;
number_opaque = (int) image->colors;
number_transparent = 0;
number_semitransparent = 0;
if (mng_info->write_png_colortype &&
(mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&
mng_info->write_png_colortype < 4 &&
image->alpha_trait == UndefinedPixelTrait)))
{
/* Avoid the expensive BUILD_PALETTE operation if we're sure that we
* are not going to need the result.
*/
if (mng_info->write_png_colortype == 1 ||
mng_info->write_png_colortype == 5)
ping_have_color=MagickFalse;
if (image->alpha_trait != UndefinedPixelTrait)
{
number_transparent = 2;
number_semitransparent = 1;
}
}
if (mng_info->write_png_colortype < 7)
{
/* BUILD_PALETTE
*
* Normally we run this just once, but in the case of writing PNG8
* we reduce the transparency to binary and run again, then if there
* are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1
* RGBA palette and run again, and then to a simple 3-3-2-1 RGBA
* palette. Then (To do) we take care of a final reduction that is only
* needed if there are still 256 colors present and one of them has both
* transparent and opaque instances.
*/
tried_332 = MagickFalse;
tried_333 = MagickFalse;
tried_444 = MagickFalse;
for (j=0; j<6; j++)
{
/*
* Sometimes we get DirectClass images that have 256 colors or fewer.
* This code will build a colormap.
*
* Also, sometimes we get PseudoClass images with an out-of-date
* colormap. This code will replace the colormap with a new one.
* Sometimes we get PseudoClass images that have more than 256 colors.
* This code will delete the colormap and change the image to
* DirectClass.
*
* If image->alpha_trait is MagickFalse, we ignore the alpha channel
* even though it sometimes contains left-over non-opaque values.
*
* Also we gather some information (number of opaque, transparent,
* and semitransparent pixels, and whether the image has any non-gray
* pixels or only black-and-white pixels) that we might need later.
*
* Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)
* we need to check for bogus non-opaque values, at least.
*/
int
n;
PixelInfo
opaque[260],
semitransparent[260],
transparent[260];
register const Quantum
*s;
register Quantum
*q,
*r;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter BUILD_PALETTE:");
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->columns=%.20g",(double) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->rows=%.20g",(double) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->alpha_trait=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Original colormap:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < 256; i++)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
for (i=image->colors - 10; i < (ssize_t) image->colors; i++)
{
if (i > 255)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d",(int) image->colors);
if (image->colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" (zero means unknown)");
if (ping_preserve_colormap == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Regenerate the colormap");
}
image_colors=0;
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
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++)
{
if (image->alpha_trait == UndefinedPixelTrait ||
GetPixelAlpha(image,q) == OpaqueAlpha)
{
if (number_opaque < 259)
{
if (number_opaque == 0)
{
GetPixelInfoPixel(image, q, opaque);
opaque[0].alpha=OpaqueAlpha;
number_opaque=1;
}
for (i=0; i< (ssize_t) number_opaque; i++)
{
if (Magick_png_color_equal(image,q,opaque+i))
break;
}
if (i == (ssize_t) number_opaque && number_opaque < 259)
{
number_opaque++;
GetPixelInfoPixel(image, q, opaque+i);
opaque[i].alpha=OpaqueAlpha;
}
}
}
else if (GetPixelAlpha(image,q) == TransparentAlpha)
{
if (number_transparent < 259)
{
if (number_transparent == 0)
{
GetPixelInfoPixel(image, q, transparent);
ping_trans_color.red=(unsigned short)
GetPixelRed(image,q);
ping_trans_color.green=(unsigned short)
GetPixelGreen(image,q);
ping_trans_color.blue=(unsigned short)
GetPixelBlue(image,q);
ping_trans_color.gray=(unsigned short)
GetPixelGray(image,q);
number_transparent = 1;
}
for (i=0; i< (ssize_t) number_transparent; i++)
{
if (Magick_png_color_equal(image,q,transparent+i))
break;
}
if (i == (ssize_t) number_transparent &&
number_transparent < 259)
{
number_transparent++;
GetPixelInfoPixel(image,q,transparent+i);
}
}
}
else
{
if (number_semitransparent < 259)
{
if (number_semitransparent == 0)
{
GetPixelInfoPixel(image,q,semitransparent);
number_semitransparent = 1;
}
for (i=0; i< (ssize_t) number_semitransparent; i++)
{
if (Magick_png_color_equal(image,q,semitransparent+i)
&& GetPixelAlpha(image,q) ==
semitransparent[i].alpha)
break;
}
if (i == (ssize_t) number_semitransparent &&
number_semitransparent < 259)
{
number_semitransparent++;
GetPixelInfoPixel(image, q, semitransparent+i);
}
}
}
q+=GetPixelChannels(image);
}
}
if (mng_info->write_png8 == MagickFalse &&
ping_exclude_bKGD == MagickFalse)
{
/* Add the background color to the palette, if it
* isn't already there.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Check colormap for background (%d,%d,%d)",
(int) image->background_color.red,
(int) image->background_color.green,
(int) image->background_color.blue);
}
for (i=0; i<number_opaque; i++)
{
if (opaque[i].red == image->background_color.red &&
opaque[i].green == image->background_color.green &&
opaque[i].blue == image->background_color.blue)
break;
}
if (number_opaque < 259 && i == number_opaque)
{
opaque[i] = image->background_color;
ping_background.index = i;
number_opaque++;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",(int) i);
}
}
else if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in the colormap to add background color");
}
image_colors=number_opaque+number_transparent+number_semitransparent;
if (logging != MagickFalse)
{
if (image_colors > 256)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has more than 256 colors");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has %d colors",image_colors);
}
if (ping_preserve_colormap != MagickFalse)
break;
if (mng_info->write_png_colortype != 7) /* We won't need this info */
{
ping_have_color=MagickFalse;
ping_have_non_bw=MagickFalse;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"incompatible colorspace");
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
}
if(image_colors > 256)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != GetPixelGreen(image,s) ||
GetPixelRed(image,s) != GetPixelBlue(image,s))
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
if (ping_have_color != MagickFalse)
break;
/* Worst case is black-and-white; we are looking at every
* pixel twice.
*/
if (ping_have_non_bw == MagickFalse)
{
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != 0 &&
GetPixelRed(image,s) != QuantumRange)
{
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
}
}
}
}
if (image_colors < 257)
{
PixelInfo
colormap[260];
/*
* Initialize image colormap.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Sort the new colormap");
/* Sort palette, transparent first */;
n = 0;
for (i=0; i<number_transparent; i++)
colormap[n++] = transparent[i];
for (i=0; i<number_semitransparent; i++)
colormap[n++] = semitransparent[i];
for (i=0; i<number_opaque; i++)
colormap[n++] = opaque[i];
ping_background.index +=
(number_transparent + number_semitransparent);
/* image_colors < 257; search the colormap instead of the pixels
* to get ping_have_color and ping_have_non_bw
*/
for (i=0; i<n; i++)
{
if (ping_have_color == MagickFalse)
{
if (colormap[i].red != colormap[i].green ||
colormap[i].red != colormap[i].blue)
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
}
if (ping_have_non_bw == MagickFalse)
{
if (colormap[i].red != 0 && colormap[i].red != QuantumRange)
ping_have_non_bw=MagickTrue;
}
}
if ((mng_info->ping_exclude_tRNS == MagickFalse ||
(number_transparent == 0 && number_semitransparent == 0)) &&
(((mng_info->write_png_colortype-1) ==
PNG_COLOR_TYPE_PALETTE) ||
(mng_info->write_png_colortype == 0)))
{
if (logging != MagickFalse)
{
if (n != (ssize_t) image_colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_colors (%d) and n (%d) don't match",
image_colors, n);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireImageColormap");
}
image->colors = image_colors;
if (AcquireImageColormap(image,image_colors,exception) ==
MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=0; i< (ssize_t) image_colors; i++)
image->colormap[i] = colormap[i];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d (%d)",
(int) image->colors, image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Update the pixel indexes");
}
/* Sync the pixel indices with the new colormap */
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++)
{
for (i=0; i< (ssize_t) image_colors; i++)
{
if ((image->alpha_trait == UndefinedPixelTrait ||
image->colormap[i].alpha == GetPixelAlpha(image,q)) &&
image->colormap[i].red == GetPixelRed(image,q) &&
image->colormap[i].green == GetPixelGreen(image,q) &&
image->colormap[i].blue == GetPixelBlue(image,q))
{
SetPixelIndex(image,i,q);
break;
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d", (int) image->colors);
if (image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < (ssize_t) image->colors; i++)
{
if (i < 300 || i >= (ssize_t) image->colors - 10)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
if (number_transparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent = %d",
number_transparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent > 256");
if (number_opaque < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque = %d",
number_opaque);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque > 256");
if (number_semitransparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent = %d",
number_semitransparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent > 256");
if (ping_have_non_bw == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are black or white");
else if (ping_have_color == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are gray");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" At least one pixel or the background is non-gray");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Exit BUILD_PALETTE:");
}
if (mng_info->write_png8 == MagickFalse)
break;
/* Make any reductions necessary for the PNG8 format */
if (image_colors <= 256 &&
image_colors != 0 && image->colormap != NULL &&
number_semitransparent == 0 &&
number_transparent <= 1)
break;
/* PNG8 can't have semitransparent colors so we threshold the
* opacity to 0 or OpaqueOpacity, and PNG8 can only have one
* transparent color so if more than one is transparent we merge
* them into image->background_color.
*/
if (number_semitransparent != 0 || number_transparent > 1)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Thresholding the alpha channel to binary");
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) < OpaqueAlpha/2)
{
SetPixelViaPixelInfo(image,&image->background_color,r);
SetPixelAlpha(image,TransparentAlpha,r);
}
else
SetPixelAlpha(image,OpaqueAlpha,r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image_colors != 0 && image_colors <= 256 &&
image->colormap != NULL)
for (i=0; i<image_colors; i++)
image->colormap[i].alpha =
(image->colormap[i].alpha > TransparentAlpha/2 ?
TransparentAlpha : OpaqueAlpha);
}
continue;
}
/* PNG8 can't have more than 256 colors so we quantize the pixels and
* background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the
* image is mostly gray, the 4-4-4-1 palette is likely to end up with 256
* colors or less.
*/
if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 4-4-4");
tried_444 = MagickTrue;
LBR04PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 4-4-4");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR04PixelRGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 4-4-4");
for (i=0; i<image_colors; i++)
{
LBR04PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-3");
tried_333 = MagickTrue;
LBR03PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-3-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR03RGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-3-1");
for (i=0; i<image_colors; i++)
{
LBR03PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-2");
tried_332 = MagickTrue;
/* Red and green were already done so we only quantize the blue
* channel
*/
LBR02PacketBlue(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR02PixelBlue(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-2-1");
for (i=0; i<image_colors; i++)
{
LBR02PacketBlue(image->colormap[i]);
}
}
continue;
}
if (image_colors == 0 || image_colors > 256)
{
/* Take care of special case with 256 opaque colors + 1 transparent
* color. We don't need to quantize to 2-3-2-1; we only need to
* eliminate one color, so we'll merge the two darkest red
* colors (0x49, 0, 0) -> (0x24, 0, 0).
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red background colors to 3-3-2-1");
if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&
ScaleQuantumToChar(image->background_color.green) == 0x00 &&
ScaleQuantumToChar(image->background_color.blue) == 0x00)
{
image->background_color.red=ScaleCharToQuantum(0x24);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 &&
ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 &&
ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 &&
GetPixelAlpha(image,r) == OpaqueAlpha)
{
SetPixelRed(image,ScaleCharToQuantum(0x24),r);
}
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else
{
for (i=0; i<image_colors; i++)
{
if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 &&
ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&
ScaleQuantumToChar(image->colormap[i].blue) == 0x00)
{
image->colormap[i].red=ScaleCharToQuantum(0x24);
}
}
}
}
}
}
/* END OF BUILD_PALETTE */
/* If we are excluding the tRNS chunk and there is transparency,
* then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)
* PNG.
*/
if (mng_info->ping_exclude_tRNS != MagickFalse &&
(number_transparent != 0 || number_semitransparent != 0))
{
unsigned int colortype=mng_info->write_png_colortype;
if (ping_have_color == MagickFalse)
mng_info->write_png_colortype = 5;
else
mng_info->write_png_colortype = 7;
if (colortype != 0 &&
mng_info->write_png_colortype != colortype)
ping_need_colortype_warning=MagickTrue;
}
/* See if cheap transparency is possible. It is only possible
* when there is a single transparent color, no semitransparent
* color, and no opaque color that has the same RGB components
* as the transparent color. We only need this information if
* we are writing a PNG with colortype 0 or 2, and we have not
* excluded the tRNS chunk.
*/
if (number_transparent == 1 &&
mng_info->write_png_colortype < 4)
{
ping_have_cheap_transparency = MagickTrue;
if (number_semitransparent != 0)
ping_have_cheap_transparency = MagickFalse;
else if (image_colors == 0 || image_colors > 256 ||
image->colormap == NULL)
{
register const Quantum
*q;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) != TransparentAlpha &&
(unsigned short) GetPixelRed(image,q) ==
ping_trans_color.red &&
(unsigned short) GetPixelGreen(image,q) ==
ping_trans_color.green &&
(unsigned short) GetPixelBlue(image,q) ==
ping_trans_color.blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
q+=GetPixelChannels(image);
}
if (ping_have_cheap_transparency == MagickFalse)
break;
}
}
else
{
/* Assuming that image->colormap[0] is the one transparent color
* and that all others are opaque.
*/
if (image_colors > 1)
for (i=1; i<image_colors; i++)
if (image->colormap[i].red == image->colormap[0].red &&
image->colormap[i].green == image->colormap[0].green &&
image->colormap[i].blue == image->colormap[0].blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
}
if (logging != MagickFalse)
{
if (ping_have_cheap_transparency == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is not possible.");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is possible.");
}
}
else
ping_have_cheap_transparency = MagickFalse;
image_depth=image->depth;
quantum_info = (QuantumInfo *) NULL;
number_colors=0;
image_colors=(int) image->colors;
image_matte=image->alpha_trait !=
UndefinedPixelTrait ? MagickTrue : MagickFalse;
if (mng_info->write_png_colortype < 5)
mng_info->IsPalette=image->storage_class == PseudoClass &&
image_colors <= 256 && image->colormap != NULL;
else
mng_info->IsPalette = MagickFalse;
if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&
(image->colors == 0 || image->colormap == NULL))
{
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"Cannot write PNG8 or color-type 3; colormap is NULL",
"`%s'",IMimage->filename);
return(MagickFalse);
}
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
error_info.image=image;
error_info.exception=exception;
ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_write_struct(&ping,(png_info **) NULL);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
png_set_write_fn(ping,image,png_put_data,png_flush_data);
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG write failed.
*/
#ifdef PNG_DEBUG
if (image_info->verbose)
(void) printf("PNG write has failed.\n");
#endif
png_destroy_write_struct(&ping,&ping_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
return(MagickFalse);
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for writing.
*/
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if (mng_info->write_mng)
{
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature when writing a MNG because
* zero-length PLTE is OK
*/
png_set_check_for_invalid_index (ping, 0);
# endif
}
#else
# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if (mng_info->write_mng)
png_permit_empty_plte(ping,MagickTrue);
# endif
#endif
x=0;
ping_width=(png_uint_32) image->columns;
ping_height=(png_uint_32) image->rows;
if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)
image_depth=8;
if (mng_info->write_png48 || mng_info->write_png64)
image_depth=16;
if (mng_info->write_png_depth != 0)
image_depth=mng_info->write_png_depth;
/* Adjust requested depth to next higher valid depth if necessary */
if (image_depth > 8)
image_depth=16;
if ((image_depth > 4) && (image_depth < 8))
image_depth=8;
if (image_depth == 3)
image_depth=4;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width=%.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height=%.20g",(double) ping_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_matte=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative ping_bit_depth=%.20g",(double) image_depth);
}
save_image_depth=image_depth;
ping_bit_depth=(png_byte) save_image_depth;
#if defined(PNG_pHYs_SUPPORTED)
if (ping_exclude_pHYs == MagickFalse)
{
if ((image->resolution.x != 0) && (image->resolution.y != 0) &&
(!mng_info->write_mng || !mng_info->equal_physs))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
if (image->units == PixelsPerInchResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=
(png_uint_32) ((100.0*image->resolution.x+0.5)/2.54);
ping_pHYs_y_resolution=
(png_uint_32) ((100.0*image->resolution.y+0.5)/2.54);
}
else if (image->units == PixelsPerCentimeterResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5);
ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5);
}
else
{
ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;
ping_pHYs_x_resolution=(png_uint_32) image->resolution.x;
ping_pHYs_y_resolution=(png_uint_32) image->resolution.y;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,
(int) ping_pHYs_unit_type);
ping_have_pHYs = MagickTrue;
}
}
#endif
if (ping_exclude_bKGD == MagickFalse)
{
if ((!mng_info->adjoin || !mng_info->equal_backgrounds))
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_background.red=(png_uint_16)
(ScaleQuantumToShort(image->background_color.red) & mask);
ping_background.green=(png_uint_16)
(ScaleQuantumToShort(image->background_color.green) & mask);
ping_background.blue=(png_uint_16)
(ScaleQuantumToShort(image->background_color.blue) & mask);
ping_background.gray=(png_uint_16) ping_background.green;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (1)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth=%d",ping_bit_depth);
}
ping_have_bKGD = MagickTrue;
}
/*
Select the color type.
*/
matte=image_matte;
old_bit_depth=0;
if (mng_info->IsPalette && mng_info->write_png8)
{
/* To do: make this a function cause it's used twice, except
for reducing the sample depth from 8. */
number_colors=image_colors;
ping_have_tRNS=MagickFalse;
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors (%d)",
number_colors, image_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
#if MAGICKCORE_QUANTUM_DEPTH == 8
" %3ld (%3d,%3d,%3d)",
#else
" %5ld (%5d,%5d,%5d)",
#endif
(long) i,palette[i].red,palette[i].green,palette[i].blue);
}
ping_have_PLTE=MagickTrue;
image_depth=ping_bit_depth;
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
Identify which colormap entry is transparent.
*/
assert(number_colors <= 256);
assert(image->colormap != NULL);
for (i=0; i < (ssize_t) number_transparent; i++)
ping_trans_alpha[i]=0;
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
ping_have_tRNS=MagickTrue;
}
if (ping_exclude_bKGD == MagickFalse)
{
/*
* Identify which colormap entry is the background color.
*/
for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)
if (IsPNGColorEqual(ping_background,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
}
}
} /* end of write_png8 */
else if (mng_info->write_png_colortype == 1)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
}
else if (mng_info->write_png24 || mng_info->write_png48 ||
mng_info->write_png_colortype == 3)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
}
else if (mng_info->write_png32 || mng_info->write_png64 ||
mng_info->write_png_colortype == 7)
{
image_matte=MagickTrue;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
}
else /* mng_info->write_pngNN not specified */
{
image_depth=ping_bit_depth;
if (mng_info->write_png_colortype != 0)
{
ping_color_type=(png_byte) mng_info->write_png_colortype-1;
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
image_matte=MagickTrue;
else
image_matte=MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG colortype %d was specified:",(int) ping_color_type);
}
else /* write_png_colortype not specified */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selecting PNG colortype:");
ping_color_type=(png_byte) ((matte != MagickFalse)?
PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);
if (image_info->type == TrueColorType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
if (image_info->type == TrueColorAlphaType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
image_matte=MagickTrue;
}
if (image_info->type == PaletteType ||
image_info->type == PaletteAlphaType)
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (mng_info->write_png_colortype == 0 &&
image_info->type == UndefinedType)
{
if (ping_have_color == MagickFalse)
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;
image_matte=MagickTrue;
}
}
else
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;
image_matte=MagickTrue;
}
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selected PNG colortype=%d",ping_color_type);
if (ping_bit_depth < 8)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
ping_bit_depth=8;
}
old_bit_depth=ping_bit_depth;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->alpha_trait == UndefinedPixelTrait &&
ping_have_non_bw == MagickFalse)
ping_bit_depth=1;
}
if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
size_t one = 1;
ping_bit_depth=1;
if (image->colors == 0)
{
/* DO SOMETHING */
png_error(ping,"image has 0 colors");
}
while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG bit depth: %d",ping_bit_depth);
}
if (ping_bit_depth < (int) mng_info->write_png_depth)
ping_bit_depth = mng_info->write_png_depth;
}
image_depth=ping_bit_depth;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG color type: %s (%.20g)",
PngColorTypeToString(ping_color_type),
(double) ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->type: %.20g",(double) image_info->type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_depth: %.20g",(double) image_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth: %.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth: %.20g",(double) ping_bit_depth);
}
if (matte != MagickFalse)
{
if (mng_info->IsPalette)
{
if (mng_info->write_png_colortype == 0)
{
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
if (ping_have_color != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_RGBA;
}
/*
* Determine if there is any transparent color.
*/
if (number_transparent + number_semitransparent == 0)
{
/*
No transparent pixels are present. Change 4 or 6 to 0 or 2.
*/
image_matte=MagickFalse;
if (mng_info->write_png_colortype == 0)
ping_color_type&=0x03;
}
else
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_trans_color.red=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].red) & mask);
ping_trans_color.green=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].green) & mask);
ping_trans_color.blue=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].blue) & mask);
ping_trans_color.gray=(png_uint_16)
(ScaleQuantumToShort(GetPixelInfoIntensity(image,
image->colormap)) & mask);
ping_trans_color.index=(png_byte) 0;
ping_have_tRNS=MagickTrue;
}
if (ping_have_tRNS != MagickFalse)
{
/*
* Determine if there is one and only one transparent color
* and if so if it is fully transparent.
*/
if (ping_have_cheap_transparency == MagickFalse)
ping_have_tRNS=MagickFalse;
}
if (ping_have_tRNS != MagickFalse)
{
if (mng_info->write_png_colortype == 0)
ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
else
{
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
matte=image_matte;
if (ping_have_tRNS != MagickFalse)
image_matte=MagickFalse;
if ((mng_info->IsPalette) &&
mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&
ping_have_color == MagickFalse &&
(image_matte == MagickFalse || image_depth >= 8))
{
size_t one=1;
if (image_matte != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)
{
ping_color_type=PNG_COLOR_TYPE_GRAY;
if (save_image_depth == 16 && image_depth == 8)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (0)");
}
ping_trans_color.gray*=0x0101;
}
}
if (image_depth > MAGICKCORE_QUANTUM_DEPTH)
image_depth=MAGICKCORE_QUANTUM_DEPTH;
if ((image_colors == 0) ||
((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))
image_colors=(int) (one << image_depth);
if (image_depth > 8)
ping_bit_depth=16;
else
{
ping_bit_depth=8;
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
if(!mng_info->write_png_depth)
{
ping_bit_depth=1;
while ((int) (one << ping_bit_depth)
< (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
}
else if (ping_color_type ==
PNG_COLOR_TYPE_GRAY && image_colors < 17 &&
mng_info->IsPalette)
{
/* Check if grayscale is reducible */
int
depth_4_ok=MagickTrue,
depth_2_ok=MagickTrue,
depth_1_ok=MagickTrue;
for (i=0; i < (ssize_t) image_colors; i++)
{
unsigned char
intensity;
intensity=ScaleQuantumToChar(image->colormap[i].red);
if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))
depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))
depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))
depth_1_ok=MagickFalse;
}
if (depth_1_ok && mng_info->write_png_depth <= 1)
ping_bit_depth=1;
else if (depth_2_ok && mng_info->write_png_depth <= 2)
ping_bit_depth=2;
else if (depth_4_ok && mng_info->write_png_depth <= 4)
ping_bit_depth=4;
}
}
image_depth=ping_bit_depth;
}
else
if (mng_info->IsPalette)
{
number_colors=image_colors;
if (image_depth <= 8)
{
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (!(mng_info->have_write_global_plte && matte == MagickFalse))
{
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=
ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors",
number_colors);
ping_have_PLTE=MagickTrue;
}
/* color_type is PNG_COLOR_TYPE_PALETTE */
if (mng_info->write_png_depth == 0)
{
size_t
one;
ping_bit_depth=1;
one=1;
while ((one << ping_bit_depth) < (size_t) number_colors)
ping_bit_depth <<= 1;
}
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
* Set up trans_colors array.
*/
assert(number_colors <= 256);
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (1)");
}
ping_have_tRNS=MagickTrue;
for (i=0; i < ping_num_trans; i++)
{
ping_trans_alpha[i]= (png_byte)
ScaleQuantumToChar(image->colormap[i].alpha);
}
}
}
}
}
else
{
if (image_depth < 8)
image_depth=8;
if ((save_image_depth == 16) && (image_depth == 8))
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color from (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
ping_trans_color.red*=0x0101;
ping_trans_color.green*=0x0101;
ping_trans_color.blue*=0x0101;
ping_trans_color.gray*=0x0101;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)
ping_bit_depth = (ssize_t) mng_info->write_png_depth;
/*
Adjust background and transparency samples in sub-8-bit grayscale files.
*/
if (ping_bit_depth < 8 && ping_color_type ==
PNG_COLOR_TYPE_GRAY)
{
png_uint_16
maxval;
size_t
one=1;
maxval=(png_uint_16) ((one << ping_bit_depth)-1);
if (ping_exclude_bKGD == MagickFalse)
{
ping_background.gray=(png_uint_16) ((maxval/65535.)*
(ScaleQuantumToShort(((GetPixelInfoIntensity(image,
&image->background_color))) +.5)));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (2)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
ping_have_bKGD = MagickTrue;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color.gray from %d",
(int)ping_trans_color.gray);
ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(
ping_trans_color.gray)+.5);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to %d", (int)ping_trans_color.gray);
}
if (ping_exclude_bKGD == MagickFalse)
{
if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
/*
Identify which colormap entry is the background color.
*/
number_colors=image_colors;
for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)
if (IsPNGColorEqual(image->background_color,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk with index=%d",(int) i);
}
if (i < (ssize_t) number_colors)
{
ping_have_bKGD = MagickTrue;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background =(%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
}
}
else /* Can't happen */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in PLTE to add bKGD color");
ping_have_bKGD = MagickFalse;
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color type: %s (%d)", PngColorTypeToString(ping_color_type),
ping_color_type);
/*
Initialize compression level and filtering.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up deflate compression");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression buffer size: 32768");
}
png_set_compression_buffer_size(ping,32768L);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression mem level: 9");
png_set_compression_mem_level(ping, 9);
/* Untangle the "-quality" setting:
Undefined is 0; the default is used.
Default is 75
10's digit:
0 or omitted: Use Z_HUFFMAN_ONLY strategy with the
zlib default compression level
1-9: the zlib compression level
1's digit:
0-4: the PNG filter method
5: libpng adaptive filtering if compression level > 5
libpng filter type "none" if compression level <= 5
or if image is grayscale or palette
6: libpng adaptive filtering
7: "LOCO" filtering (intrapixel differing) if writing
a MNG, otherwise "none". Did not work in IM-6.7.0-9
and earlier because of a missing "else".
8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive
filtering. Unused prior to IM-6.7.0-10, was same as 6
9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters
Unused prior to IM-6.7.0-10, was same as 6
Note that using the -quality option, not all combinations of
PNG filter type, zlib compression level, and zlib compression
strategy are possible. This will be addressed soon in a
release that accomodates "-define png:compression-strategy", etc.
*/
quality=image_info->quality == UndefinedCompressionQuality ? 75UL :
image_info->quality;
if (quality <= 9)
{
if (mng_info->write_png_compression_strategy == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
}
else if (mng_info->write_png_compression_level == 0)
{
int
level;
level=(int) MagickMin((ssize_t) quality/10,9);
mng_info->write_png_compression_level = level+1;
}
if (mng_info->write_png_compression_strategy == 0)
{
if ((quality %10) == 8 || (quality %10) == 9)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy=Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
}
if (mng_info->write_png_compression_filter == 0)
mng_info->write_png_compression_filter=((int) quality % 10) + 1;
if (logging != MagickFalse)
{
if (mng_info->write_png_compression_level)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression level: %d",
(int) mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_strategy)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression strategy: %d",
(int) mng_info->write_png_compression_strategy-1);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up filtering");
if (mng_info->write_png_compression_filter == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: ADAPTIVE");
else if (mng_info->write_png_compression_filter == 0 ||
mng_info->write_png_compression_filter == 1)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: NONE");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: %d",
(int) mng_info->write_png_compression_filter-1);
}
if (mng_info->write_png_compression_level != 0)
png_set_compression_level(ping,mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_filter == 6)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
(quality < 50))
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
}
else if (mng_info->write_png_compression_filter == 7 ||
mng_info->write_png_compression_filter == 10)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
else if (mng_info->write_png_compression_filter == 8)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)
if (mng_info->write_mng)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||
((int) ping_color_type == PNG_COLOR_TYPE_RGBA))
ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;
}
#endif
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
}
else if (mng_info->write_png_compression_filter == 9)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else if (mng_info->write_png_compression_filter != 0)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,
mng_info->write_png_compression_filter-1);
if (mng_info->write_png_compression_strategy != 0)
png_set_compression_strategy(ping,
mng_info->write_png_compression_strategy-1);
ping_interlace_method=image_info->interlace != NoInterlace;
if (mng_info->write_mng)
png_set_sig_bytes(ping,8);
/* Bail out if cannot meet defined png:bit-depth or png:color-type */
if (mng_info->write_png_colortype != 0)
{
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)
if (ping_have_color != MagickFalse)
{
ping_color_type = PNG_COLOR_TYPE_RGB;
if (ping_bit_depth < 8)
ping_bit_depth=8;
}
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)
if (ping_have_color != MagickFalse)
ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
if (ping_need_colortype_warning != MagickFalse ||
((mng_info->write_png_depth &&
(int) mng_info->write_png_depth != ping_bit_depth) ||
(mng_info->write_png_colortype &&
((int) mng_info->write_png_colortype-1 != ping_color_type &&
mng_info->write_png_colortype != 7 &&
!(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))
{
if (logging != MagickFalse)
{
if (ping_need_colortype_warning != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image has transparency but tRNS chunk was excluded");
}
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth=%u, Computed depth=%u",
mng_info->write_png_depth,
ping_bit_depth);
}
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type=%u, Computed color type=%u",
mng_info->write_png_colortype-1,
ping_color_type);
}
}
png_warning(ping,
"Cannot write image with defined png:bit-depth or png:color-type.");
}
if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait)
{
/* Add an opaque matte channel */
image->alpha_trait = BlendPixelTrait;
(void) SetImageAlpha(image,OpaqueAlpha,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Added an opaque matte channel");
}
if (number_transparent != 0 || number_semitransparent != 0)
{
if (ping_color_type < 4)
{
ping_have_tRNS=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting ping_have_tRNS=MagickTrue.");
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG header chunks");
png_set_IHDR(ping,ping_info,ping_width,ping_height,
ping_bit_depth,ping_color_type,
ping_interlace_method,ping_compression_method,
ping_filter_method);
if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)
{
png_set_PLTE(ping,ping_info,palette,number_colors);
if (logging != MagickFalse)
{
for (i=0; i< (ssize_t) number_colors; i++)
{
if (i < ping_num_trans)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue,
(int) i,
(int) ping_trans_alpha[i]);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue);
}
}
}
/* Only write the iCCP chunk if we are not writing the sRGB chunk. */
if (ping_exclude_sRGB != MagickFalse ||
(!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if ((ping_exclude_tEXt == MagickFalse ||
ping_exclude_zTXt == MagickFalse) &&
(ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
#ifdef PNG_WRITE_iCCP_SUPPORTED
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
ping_have_iCCP = MagickTrue;
if (ping_exclude_iCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up iCCP chunk");
png_set_iCCP(ping,ping_info,(png_charp) name,0,
#if (PNG_LIBPNG_VER < 10500)
(png_charp) GetStringInfoDatum(profile),
#else
(const png_byte *) GetStringInfoDatum(profile),
#endif
(png_uint_32) GetStringInfoLength(profile));
}
else
{
/* Do not write hex-encoded ICC chunk */
name=GetNextImageProfile(image);
continue;
}
}
#endif /* WRITE_iCCP */
if (LocaleCompare(name,"exif") == 0)
{
/* Do not write hex-encoded ICC chunk; we will
write it later as an eXIf chunk */
name=GetNextImageProfile(image);
continue;
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up zTXt chunk with uuencoded %s profile",
name);
Magick_png_write_raw_profile(image_info,ping,ping_info,
(unsigned char *) name,(unsigned char *) name,
GetStringInfoDatum(profile),
(png_uint_32) GetStringInfoLength(profile));
}
name=GetNextImageProfile(image);
}
}
}
#if defined(PNG_WRITE_sRGB_SUPPORTED)
if ((mng_info->have_write_global_srgb == 0) &&
ping_have_iCCP != MagickTrue &&
(ping_have_sRGB != MagickFalse ||
png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if (ping_exclude_sRGB == MagickFalse)
{
/*
Note image rendering intent.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up sRGB chunk");
(void) png_set_sRGB(ping,ping_info,(
Magick_RenderingIntent_to_PNG_RenderingIntent(
image->rendering_intent)));
ping_have_sRGB = MagickTrue;
}
}
if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
#endif
{
if (ping_exclude_gAMA == MagickFalse &&
ping_have_iCCP == MagickFalse &&
ping_have_sRGB == MagickFalse &&
(ping_exclude_sRGB == MagickFalse ||
(image->gamma < .45 || image->gamma > .46)))
{
if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))
{
/*
Note image gamma.
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up gAMA chunk");
png_set_gAMA(ping,ping_info,image->gamma);
}
}
if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)
{
if ((mng_info->have_write_global_chrm == 0) &&
(image->chromaticity.red_primary.x != 0.0))
{
/*
Note image chromaticity.
Note: if cHRM+gAMA == sRGB write sRGB instead.
*/
PrimaryInfo
bp,
gp,
rp,
wp;
wp=image->chromaticity.white_point;
rp=image->chromaticity.red_primary;
gp=image->chromaticity.green_primary;
bp=image->chromaticity.blue_primary;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up cHRM chunk");
png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,
bp.x,bp.y);
}
}
}
if (ping_exclude_bKGD == MagickFalse)
{
if (ping_have_bKGD != MagickFalse)
{
png_set_bKGD(ping,ping_info,&ping_background);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background color = (%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" index = %d, gray=%d",
(int) ping_background.index,
(int) ping_background.gray);
}
}
}
if (ping_exclude_pHYs == MagickFalse)
{
if (ping_have_pHYs != MagickFalse)
{
png_set_pHYs(ping,ping_info,
ping_pHYs_x_resolution,
ping_pHYs_y_resolution,
ping_pHYs_unit_type);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_resolution=%lu",
(unsigned long) ping_pHYs_x_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" y_resolution=%lu",
(unsigned long) ping_pHYs_y_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unit_type=%lu",
(unsigned long) ping_pHYs_unit_type);
}
}
}
#if defined(PNG_tIME_SUPPORTED)
if (ping_exclude_tIME == MagickFalse)
{
const char
*timestamp;
if (image->taint == MagickFalse)
{
timestamp=GetImageOption(image_info,"png:tIME");
if (timestamp == (const char *) NULL)
timestamp=GetImageProperty(image,"png:tIME",exception);
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reset tIME in tainted image");
timestamp=GetImageProperty(image,"date:modify",exception);
}
if (timestamp != (const char *) NULL)
write_tIME_chunk(image,ping,ping_info,timestamp,exception);
}
#endif
if (mng_info->need_blob != MagickFalse)
{
if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) ==
MagickFalse)
png_error(ping,"WriteBlob Failed");
ping_have_blob=MagickTrue;
}
png_write_info_before_PLTE(ping, ping_info);
if (ping_have_tRNS != MagickFalse && ping_color_type < 4)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Calling png_set_tRNS with num_trans=%d",ping_num_trans);
}
if (ping_color_type == 3)
(void) png_set_tRNS(ping, ping_info,
ping_trans_alpha,
ping_num_trans,
NULL);
else
{
(void) png_set_tRNS(ping, ping_info,
NULL,
0,
&ping_trans_color);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS color =(%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
/* write any png-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging);
png_write_info(ping,ping_info);
/* write any PNG-chunk-m profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging);
ping_wrote_caNv = MagickFalse;
/* write caNv chunk */
if (ping_exclude_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
image->page.x != 0 || image->page.y != 0)
{
unsigned char
chunk[20];
(void) WriteBlobMSBULong(image,16L); /* data length=8 */
PNGType(chunk,mng_caNv);
LogPNGChunk(logging,mng_caNv,16L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
PNGsLong(chunk+12,(png_int_32) image->page.x);
PNGsLong(chunk+16,(png_int_32) image->page.y);
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
ping_wrote_caNv = MagickTrue;
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if (image->page.x || image->page.y)
{
png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,
(png_int_32) image->page.y, 0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up oFFs chunk with x=%d, y=%d, units=0",
(int) image->page.x, (int) image->page.y);
}
}
#endif
/* write vpAg chunk (deprecated, replaced by caNv) */
if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
unsigned char
chunk[14];
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
}
#if (PNG_LIBPNG_VER == 10206)
/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */
#define PNG_HAVE_IDAT 0x04
ping->mode |= PNG_HAVE_IDAT;
#undef PNG_HAVE_IDAT
#endif
png_set_packing(ping);
/*
Allocate memory.
*/
rowbytes=image->columns;
if (image_depth > 8)
rowbytes*=2;
switch (ping_color_type)
{
case PNG_COLOR_TYPE_RGB:
rowbytes*=3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
rowbytes*=2;
break;
case PNG_COLOR_TYPE_RGBA:
rowbytes*=4;
break;
default:
break;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocating %.20g bytes of memory for pixels",(double) rowbytes);
}
pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Allocation of memory for pixels failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Initialize image scanlines.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Memory allocation for quantum_info failed");
quantum_info->format=UndefinedQuantumFormat;
SetQuantumDepth(image,quantum_info,image_depth);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
num_passes=png_set_interlace_handling(ping);
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) &&
(mng_info->IsPalette ||
(image_info->type == BilevelType)) &&
image_matte == MagickFalse &&
ping_have_non_bw == MagickFalse)
{
/* Palette, Bilevel, or Opaque Monochrome */
register const Quantum
*p;
SetQuantumDepth(image,quantum_info,8);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert PseudoClass image to a PNG monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (0)");
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (mng_info->IsPalette)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&
mng_info->write_png_depth &&
mng_info->write_png_depth != old_bit_depth)
{
/* Undo pixel scaling */
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)
>> (8-old_bit_depth));
}
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
}
if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?
255 : 0);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (1)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else /* Not Palette, Bilevel, or Opaque Monochrome */
{
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) && (image_matte != MagickFalse ||
(ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&
(mng_info->IsPalette) && ping_have_color == MagickFalse)
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (mng_info->IsPalette)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY PNG pixels (2)");
}
else /* PNG_COLOR_TYPE_GRAY_ALPHA */
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (2)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,exception);
}
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (2)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
if ((image_depth > 8) ||
mng_info->write_png24 ||
mng_info->write_png32 ||
mng_info->write_png48 ||
mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->storage_class == DirectClass)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (3)");
}
else if (image_matte != MagickFalse)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBAQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (3)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
else
/* not ((image_depth > 8) ||
mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
*/
{
if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&
(ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is not GRAY or GRAY_ALPHA",pass);
SetQuantumDepth(image,quantum_info,8);
image_depth=8;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",
pass);
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
SetQuantumDepth(image,quantum_info,image->depth);
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (4)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,IndexQuantum,ping_pixels,exception);
if (logging != MagickFalse && y <= 2)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of non-gray pixels (4)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_pixels[0]=%d,ping_pixels[1]=%d",
(int)ping_pixels[0],(int)ping_pixels[1]);
}
}
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Wrote PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Width: %.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Height: %.20g",(double) ping_height);
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth: %d",mng_info->write_png_depth);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG bit-depth written: %d",ping_bit_depth);
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type: %d",mng_info->write_png_colortype-1);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color-type written: %d",ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG Interlace method: %d",ping_interlace_method);
}
/*
Generate text chunks after IDAT.
*/
if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
png_textp
text;
value=GetImageProperty(image,property,exception);
/* Don't write any "png:" or "jpeg:" properties; those are just for
* "identify" or for passing through to another JPEG
*/
if ((LocaleNCompare(property,"png:",4) != 0 &&
LocaleNCompare(property,"jpeg:",5) != 0) &&
/* Suppress density and units if we wrote a pHYs chunk */
(ping_exclude_pHYs != MagickFalse ||
LocaleCompare(property,"density") != 0 ||
LocaleCompare(property,"units") != 0) &&
/* Suppress the IM-generated Date:create and Date:modify */
(ping_exclude_date == MagickFalse ||
LocaleNCompare(property, "Date:",5) != 0))
{
if (value != (const char *) NULL)
{
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,
(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
text[0].key=(char *) property;
text[0].text=(char *) value;
text[0].text_length=strlen(value);
if (ping_exclude_tEXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_zTXt;
else if (ping_exclude_zTXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_NONE;
else
{
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :
PNG_TEXT_COMPRESSION_zTXt ;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" keyword: '%s'",text[0].key);
}
png_set_text(ping,ping_info,text,1);
png_free(ping,text);
}
}
property=GetNextImageProperty(image);
}
}
/* write any PNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging);
/* write exIf profile */
if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)
{
char
*name;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
if (LocaleCompare(name,"exif") == 0)
{
const StringInfo
*profile;
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
png_uint_32
length;
unsigned char
chunk[4],
*data;
StringInfo
*ping_profile;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Have eXIf profile");
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
PNGType(chunk,mng_eXIf);
if (length < 7)
{
ping_profile=DestroyStringInfo(ping_profile);
break; /* otherwise crashes */
}
/* skip the "Exif\0\0" JFIF Exif Header ID */
length -= 6;
LogPNGChunk(logging,chunk,length);
(void) WriteBlobMSBULong(image,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,data+6);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),
data+6, (uInt) length));
ping_profile=DestroyStringInfo(ping_profile);
break;
}
}
name=GetNextImageProfile(image);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG end info");
png_write_end(ping,ping_info);
if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)
{
if (mng_info->page.x || mng_info->page.y ||
(ping_width != mng_info->page.width) ||
(ping_height != mng_info->page.height))
{
unsigned char
chunk[32];
/*
Write FRAM 4 with clipping boundaries followed by FRAM 1.
*/
(void) WriteBlobMSBULong(image,27L); /* data length=27 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,27L);
chunk[4]=4;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=1; /* flag for changing delay, for next frame only */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=1; /* flag for changing frame clipping for next frame */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */
chunk[14]=0; /* clipping boundaries delta type */
PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */
PNGLong(chunk+19,
(png_uint_32) (mng_info->page.x + ping_width));
PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */
PNGLong(chunk+27,
(png_uint_32) (mng_info->page.y + ping_height));
(void) WriteBlob(image,31,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,31));
mng_info->old_framing_mode=4;
mng_info->framing_mode=1;
}
else
mng_info->framing_mode=3;
}
if (mng_info->write_mng && !mng_info->need_fram &&
((int) image->dispose == 3))
png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC");
/*
Free PNG resources.
*/
png_destroy_write_struct(&ping,&ping_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
/* Store bit depth actually written */
s[0]=(char) ping_bit_depth;
s[1]='\0';
(void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block. Revert to
* Throwing an Exception when an error occurs.
*/
return(MagickTrue);
/* End write one PNG image */
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNGImage() writes a Portable Network Graphics (PNG) or
% Multiple-image Network Graphics (MNG) image file.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WritePNGImage method is:
%
% MagickBooleanType WritePNGImage(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.
%
% Returns MagickTrue on success, MagickFalse on failure.
%
% Communicating with the PNG encoder:
%
% While the datastream written is always in PNG format and normally would
% be given the "png" file extension, this method also writes the following
% pseudo-formats which are subsets of png:
%
% o PNG8: An 8-bit indexed PNG datastream is written. If the image has
% a depth greater than 8, the depth is reduced. If transparency
% is present, the tRNS chunk must only have values 0 and 255
% (i.e., transparency is binary: fully opaque or fully
% transparent). If other values are present they will be
% 50%-thresholded to binary transparency. If more than 256
% colors are present, they will be quantized to the 4-4-4-1,
% 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color
% of any resulting fully-transparent pixels is changed to
% the image's background color.
%
% If you want better quantization or dithering of the colors
% or alpha than that, you need to do it before calling the
% PNG encoder. The pixels contain 8-bit indices even if
% they could be represented with 1, 2, or 4 bits. Grayscale
% images will be written as indexed PNG files even though the
% PNG grayscale type might be slightly more efficient. Please
% note that writing to the PNG8 format may result in loss
% of color and alpha data.
%
% o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS
% chunk can be present to convey binary transparency by naming
% one of the colors as transparent. The only loss incurred
% is reduction of sample depth to 8. If the image has more
% than one transparent color, has semitransparent pixels, or
% has an opaque pixel with the same RGB components as the
% transparent color, an image is not written.
%
% o PNG32: An 8-bit per sample RGBA PNG is written. Partial
% transparency is permitted, i.e., the alpha sample for
% each pixel can have any value from 0 to 255. The alpha
% channel is present even if the image is fully opaque.
% The only loss in data is the reduction of the sample depth
% to 8.
%
% o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS
% chunk can be present to convey binary transparency by naming
% one of the colors as transparent. If the image has more
% than one transparent color, has semitransparent pixels, or
% has an opaque pixel with the same RGB components as the
% transparent color, an image is not written.
%
% o PNG64: A 16-bit per sample RGBA PNG is written. Partial
% transparency is permitted, i.e., the alpha sample for
% each pixel can have any value from 0 to 65535. The alpha
% channel is present even if the image is fully opaque.
%
% o PNG00: A PNG that inherits its colortype and bit-depth from the input
% image, if the input was a PNG, is written. If these values
% cannot be found, or if the pixels have been changed in a way
% that makes this impossible, then "PNG00" falls back to the
% regular "PNG" format.
%
% o -define: For more precise control of the PNG output, you can use the
% Image options "png:bit-depth" and "png:color-type". These
% can be set from the commandline with "-define" and also
% from the application programming interfaces. The options
% are case-independent and are converted to lowercase before
% being passed to this encoder.
%
% png:color-type can be 0, 2, 3, 4, or 6.
%
% When png:color-type is 0 (Grayscale), png:bit-depth can
% be 1, 2, 4, 8, or 16.
%
% When png:color-type is 2 (RGB), png:bit-depth can
% be 8 or 16.
%
% When png:color-type is 3 (Indexed), png:bit-depth can
% be 1, 2, 4, or 8. This refers to the number of bits
% used to store the index. The color samples always have
% bit-depth 8 in indexed PNG files.
%
% When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte),
% png:bit-depth can be 8 or 16.
%
% If the image cannot be written without loss with the
% requested bit-depth and color-type, a PNG file will not
% be written, a warning will be issued, and the encoder will
% return MagickFalse.
%
% Since image encoders should not be responsible for the "heavy lifting",
% the user should make sure that ImageMagick has already reduced the
% image depth and number of colors and limit transparency to binary
% transparency prior to attempting to write the image with depth, color,
% or transparency limitations.
%
% Note that another definition, "png:bit-depth-written" exists, but it
% is not intended for external use. It is only used internally by the
% PNG encoder to inform the JNG encoder of the depth of the alpha channel.
%
% It is possible to request that the PNG encoder write previously-formatted
% ancillary chunks in the output PNG file, using the "-profile" commandline
% option as shown below or by setting the profile via a programming
% interface:
%
% -profile PNG-chunk-x:<file>
%
% where x is a location flag and <file> is a file containing the chunk
% name in the first 4 bytes, then a colon (":"), followed by the chunk data.
% This encoder will compute the chunk length and CRC, so those must not
% be included in the file.
%
% "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT),
% or "e" (end, i.e., after IDAT). If you want to write multiple chunks
% of the same type, then add a short unique string after the "x" to prevent
% subsequent profiles from overwriting the preceding ones, e.g.,
%
% -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02
%
% As of version 6.6.6 the following optimizations are always done:
%
% o 32-bit depth is reduced to 16.
% o 16-bit depth is reduced to 8 if all pixels contain samples whose
% high byte and low byte are identical.
% o Palette is sorted to remove unused entries and to put a
% transparent color first, if BUILD_PNG_PALETTE is defined.
% o Opaque matte channel is removed when writing an indexed PNG.
% o Grayscale images are reduced to 1, 2, or 4 bit depth if
% this can be done without loss and a larger bit depth N was not
% requested via the "-define png:bit-depth=N" option.
% o If matte channel is present but only one transparent color is
% present, RGB+tRNS is written instead of RGBA
% o Opaque matte channel is removed (or added, if color-type 4 or 6
% was requested when converting an opaque image).
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
static MagickBooleanType WritePNGImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
MagickBooleanType
excluding,
logging,
status;
MngInfo
*mng_info;
const char
*value;
int
source;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
mng_info->equal_backgrounds=MagickTrue;
/* See if user has requested a specific PNG subformat */
mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0;
mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0;
mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0;
mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0;
mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0;
value=GetImageOption(image_info,"png:format");
if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format=%s",value);
mng_info->write_png8 = MagickFalse;
mng_info->write_png24 = MagickFalse;
mng_info->write_png32 = MagickFalse;
mng_info->write_png48 = MagickFalse;
mng_info->write_png64 = MagickFalse;
if (LocaleCompare(value,"png8") == 0)
mng_info->write_png8 = MagickTrue;
else if (LocaleCompare(value,"png24") == 0)
mng_info->write_png24 = MagickTrue;
else if (LocaleCompare(value,"png32") == 0)
mng_info->write_png32 = MagickTrue;
else if (LocaleCompare(value,"png48") == 0)
mng_info->write_png48 = MagickTrue;
else if (LocaleCompare(value,"png64") == 0)
mng_info->write_png64 = MagickTrue;
else if ((LocaleCompare(value,"png00") == 0) ||
LocaleCompare(image_info->magick,"PNG00") == 0)
{
/* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig. */
value=GetImageProperty(image,"png:IHDR.bit-depth-orig",exception);
if (value != (char *) NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png00 inherited bit depth=%s",value);
if (LocaleCompare(value,"1") == 0)
mng_info->write_png_depth = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_depth = 2;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_depth = 4;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_depth = 8;
else if (LocaleCompare(value,"16") == 0)
mng_info->write_png_depth = 16;
}
value=GetImageProperty(image,"png:IHDR.color-type-orig",exception);
if (value != (char *) NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png00 inherited color type=%s",value);
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_colortype = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_colortype = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_colortype = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_colortype = 5;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_colortype = 7;
}
}
}
if (mng_info->write_png8)
{
mng_info->write_png_colortype = /* 3 */ 4;
mng_info->write_png_depth = 8;
image->depth = 8;
}
if (mng_info->write_png24)
{
mng_info->write_png_colortype = /* 2 */ 3;
mng_info->write_png_depth = 8;
image->depth = 8;
if (image->alpha_trait != UndefinedPixelTrait)
(void) SetImageType(image,TrueColorAlphaType,exception);
else
(void) SetImageType(image,TrueColorType,exception);
(void) SyncImage(image,exception);
}
if (mng_info->write_png32)
{
mng_info->write_png_colortype = /* 6 */ 7;
mng_info->write_png_depth = 8;
image->depth = 8;
image->alpha_trait = BlendPixelTrait;
(void) SetImageType(image,TrueColorAlphaType,exception);
(void) SyncImage(image,exception);
}
if (mng_info->write_png48)
{
mng_info->write_png_colortype = /* 2 */ 3;
mng_info->write_png_depth = 16;
image->depth = 16;
if (image->alpha_trait != UndefinedPixelTrait)
(void) SetImageType(image,TrueColorAlphaType,exception);
else
(void) SetImageType(image,TrueColorType,exception);
(void) SyncImage(image,exception);
}
if (mng_info->write_png64)
{
mng_info->write_png_colortype = /* 6 */ 7;
mng_info->write_png_depth = 16;
image->depth = 16;
image->alpha_trait = BlendPixelTrait;
(void) SetImageType(image,TrueColorAlphaType,exception);
(void) SyncImage(image,exception);
}
value=GetImageOption(image_info,"png:bit-depth");
if (value != (char *) NULL)
{
if (LocaleCompare(value,"1") == 0)
mng_info->write_png_depth = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_depth = 2;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_depth = 4;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_depth = 8;
else if (LocaleCompare(value,"16") == 0)
mng_info->write_png_depth = 16;
else
(void) ThrowMagickException(exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:bit-depth",
"=%s",value);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:bit-depth=%d was defined.\n",mng_info->write_png_depth);
}
value=GetImageOption(image_info,"png:color-type");
if (value != (char *) NULL)
{
/* We must store colortype+1 because 0 is a valid colortype */
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_colortype = 1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_colortype = 2;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_colortype = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_colortype = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_colortype = 5;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_colortype = 7;
else
(void) ThrowMagickException(exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:color-type",
"=%s",value);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:color-type=%d was defined.\n",
mng_info->write_png_colortype-1);
}
/* Check for chunks to be excluded:
*
* The default is to not exclude any known chunks except for any
* listed in the "unused_chunks" array, above.
*
* Chunks can be listed for exclusion via a "png:exclude-chunk"
* define (in the image properties or in the image artifacts)
* or via a mng_info member. For convenience, in addition
* to or instead of a comma-separated list of chunks, the
* "exclude-chunk" string can be simply "all" or "none".
*
* The exclude-chunk define takes priority over the mng_info.
*
* A "png:include-chunk" define takes priority over both the
* mng_info and the "png:exclude-chunk" define. Like the
* "exclude-chunk" string, it can define "all" or "none" as
* well as a comma-separated list. Chunks that are unknown to
* ImageMagick are always excluded, regardless of their "copy-safe"
* status according to the PNG specification, and even if they
* appear in the "include-chunk" list. Such defines appearing among
* the image options take priority over those found among the image
* artifacts.
*
* Finally, all chunks listed in the "unused_chunks" array are
* automatically excluded, regardless of the other instructions
* or lack thereof.
*
* if you exclude sRGB but not gAMA (recommended), then sRGB chunk
* will not be written and the gAMA chunk will only be written if it
* is not between .45 and .46, or approximately (1.0/2.2).
*
* If you exclude tRNS and the image has transparency, the colortype
* is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA).
*
* The -strip option causes StripImage() to set the png:include-chunk
* artifact to "none,trns,gama".
*/
mng_info->ping_exclude_bKGD=MagickFalse;
mng_info->ping_exclude_caNv=MagickFalse;
mng_info->ping_exclude_cHRM=MagickFalse;
mng_info->ping_exclude_date=MagickFalse;
mng_info->ping_exclude_eXIf=MagickFalse;
mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */
mng_info->ping_exclude_gAMA=MagickFalse;
mng_info->ping_exclude_iCCP=MagickFalse;
/* mng_info->ping_exclude_iTXt=MagickFalse; */
mng_info->ping_exclude_oFFs=MagickFalse;
mng_info->ping_exclude_pHYs=MagickFalse;
mng_info->ping_exclude_sRGB=MagickFalse;
mng_info->ping_exclude_tEXt=MagickFalse;
mng_info->ping_exclude_tIME=MagickFalse;
mng_info->ping_exclude_tRNS=MagickFalse;
mng_info->ping_exclude_vpAg=MagickFalse;
mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */
mng_info->ping_exclude_zTXt=MagickFalse;
mng_info->ping_preserve_colormap=MagickFalse;
value=GetImageOption(image_info,"png:preserve-colormap");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-colormap");
if (value != NULL)
mng_info->ping_preserve_colormap=MagickTrue;
mng_info->ping_preserve_iCCP=MagickFalse;
value=GetImageOption(image_info,"png:preserve-iCCP");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-iCCP");
if (value != NULL)
mng_info->ping_preserve_iCCP=MagickTrue;
/* These compression-level, compression-strategy, and compression-filter
* defines take precedence over values from the -quality option.
*/
value=GetImageOption(image_info,"png:compression-level");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-level");
if (value != NULL)
{
/* We have to add 1 to everything because 0 is a valid input,
* and we want to use 0 (the default) to mean undefined.
*/
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_level = 1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_level = 2;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_level = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_compression_level = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_compression_level = 5;
else if (LocaleCompare(value,"5") == 0)
mng_info->write_png_compression_level = 6;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_compression_level = 7;
else if (LocaleCompare(value,"7") == 0)
mng_info->write_png_compression_level = 8;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_compression_level = 9;
else if (LocaleCompare(value,"9") == 0)
mng_info->write_png_compression_level = 10;
else
(void) ThrowMagickException(exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-level",
"=%s",value);
}
value=GetImageOption(image_info,"png:compression-strategy");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-strategy");
if (value != NULL)
{
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_strategy = Z_FILTERED+1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
else if (LocaleCompare(value,"3") == 0)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy = Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
else if (LocaleCompare(value,"4") == 0)
#ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */
mng_info->write_png_compression_strategy = Z_FIXED+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
else
(void) ThrowMagickException(exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-strategy",
"=%s",value);
}
value=GetImageOption(image_info,"png:compression-filter");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-filter");
if (value != NULL)
{
/* To do: combinations of filters allowed by libpng
* masks 0x08 through 0xf8
*
* Implement this as a comma-separated list of 0,1,2,3,4,5
* where 5 is a special case meaning PNG_ALL_FILTERS.
*/
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_filter = 1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_filter = 2;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_filter = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_compression_filter = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_compression_filter = 5;
else if (LocaleCompare(value,"5") == 0)
mng_info->write_png_compression_filter = 6;
else
(void) ThrowMagickException(exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-filter",
"=%s",value);
}
for (source=0; source<8; source++)
{
value = NULL;
if (source == 0)
value=GetImageOption(image_info,"png:exclude-chunks");
if (source == 1)
value=GetImageArtifact(image,"png:exclude-chunks");
if (source == 2)
value=GetImageOption(image_info,"png:exclude-chunk");
if (source == 3)
value=GetImageArtifact(image,"png:exclude-chunk");
if (source == 4)
value=GetImageOption(image_info,"png:include-chunks");
if (source == 5)
value=GetImageArtifact(image,"png:include-chunks");
if (source == 6)
value=GetImageOption(image_info,"png:include-chunk");
if (source == 7)
value=GetImageArtifact(image,"png:include-chunk");
if (value == NULL)
continue;
if (source < 4)
excluding = MagickTrue;
else
excluding = MagickFalse;
if (logging != MagickFalse)
{
if (source == 0 || source == 2)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:exclude-chunk=%s found in image options.\n", value);
else if (source == 1 || source == 3)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:exclude-chunk=%s found in image artifacts.\n", value);
else if (source == 4 || source == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:include-chunk=%s found in image options.\n", value);
else /* if (source == 5 || source == 7) */
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:include-chunk=%s found in image artifacts.\n", value);
}
if (IsOptionMember("all",value) != MagickFalse)
{
mng_info->ping_exclude_bKGD=excluding;
mng_info->ping_exclude_caNv=excluding;
mng_info->ping_exclude_cHRM=excluding;
mng_info->ping_exclude_date=excluding;
mng_info->ping_exclude_EXIF=excluding;
mng_info->ping_exclude_eXIf=excluding;
mng_info->ping_exclude_gAMA=excluding;
mng_info->ping_exclude_iCCP=excluding;
/* mng_info->ping_exclude_iTXt=excluding; */
mng_info->ping_exclude_oFFs=excluding;
mng_info->ping_exclude_pHYs=excluding;
mng_info->ping_exclude_sRGB=excluding;
mng_info->ping_exclude_tEXt=excluding;
mng_info->ping_exclude_tIME=excluding;
mng_info->ping_exclude_tRNS=excluding;
mng_info->ping_exclude_vpAg=excluding;
mng_info->ping_exclude_zCCP=excluding;
mng_info->ping_exclude_zTXt=excluding;
}
if (IsOptionMember("none",value) != MagickFalse)
{
mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse :
MagickTrue;
/* mng_info->ping_exclude_iTXt=!excluding; */
mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse :
MagickTrue;
}
if (IsOptionMember("bkgd",value) != MagickFalse)
mng_info->ping_exclude_bKGD=excluding;
if (IsOptionMember("caNv",value) != MagickFalse)
mng_info->ping_exclude_caNv=excluding;
if (IsOptionMember("chrm",value) != MagickFalse)
mng_info->ping_exclude_cHRM=excluding;
if (IsOptionMember("date",value) != MagickFalse)
mng_info->ping_exclude_date=excluding;
if (IsOptionMember("exif",value) != MagickFalse)
{
mng_info->ping_exclude_EXIF=excluding;
mng_info->ping_exclude_eXIf=excluding;
}
if (IsOptionMember("gama",value) != MagickFalse)
mng_info->ping_exclude_gAMA=excluding;
if (IsOptionMember("iccp",value) != MagickFalse)
mng_info->ping_exclude_iCCP=excluding;
#if 0
if (IsOptionMember("itxt",value) != MagickFalse)
mng_info->ping_exclude_iTXt=excluding;
#endif
if (IsOptionMember("offs",value) != MagickFalse)
mng_info->ping_exclude_oFFs=excluding;
if (IsOptionMember("phys",value) != MagickFalse)
mng_info->ping_exclude_pHYs=excluding;
if (IsOptionMember("srgb",value) != MagickFalse)
mng_info->ping_exclude_sRGB=excluding;
if (IsOptionMember("text",value) != MagickFalse)
mng_info->ping_exclude_tEXt=excluding;
if (IsOptionMember("time",value) != MagickFalse)
mng_info->ping_exclude_tIME=excluding;
if (IsOptionMember("trns",value) != MagickFalse)
mng_info->ping_exclude_tRNS=excluding;
if (IsOptionMember("vpag",value) != MagickFalse)
mng_info->ping_exclude_vpAg=excluding;
if (IsOptionMember("zccp",value) != MagickFalse)
mng_info->ping_exclude_zCCP=excluding;
if (IsOptionMember("ztxt",value) != MagickFalse)
mng_info->ping_exclude_zTXt=excluding;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Chunks to be excluded from the output png:");
if (mng_info->ping_exclude_bKGD != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" bKGD");
if (mng_info->ping_exclude_caNv != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" caNv");
if (mng_info->ping_exclude_cHRM != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" cHRM");
if (mng_info->ping_exclude_date != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" date");
if (mng_info->ping_exclude_EXIF != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" EXIF");
if (mng_info->ping_exclude_eXIf != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" eXIf");
if (mng_info->ping_exclude_gAMA != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" gAMA");
if (mng_info->ping_exclude_iCCP != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" iCCP");
#if 0
if (mng_info->ping_exclude_iTXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" iTXt");
#endif
if (mng_info->ping_exclude_oFFs != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" oFFs");
if (mng_info->ping_exclude_pHYs != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pHYs");
if (mng_info->ping_exclude_sRGB != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" sRGB");
if (mng_info->ping_exclude_tEXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tEXt");
if (mng_info->ping_exclude_tIME != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tIME");
if (mng_info->ping_exclude_tRNS != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS");
if (mng_info->ping_exclude_vpAg != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" vpAg");
if (mng_info->ping_exclude_zCCP != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" zCCP");
if (mng_info->ping_exclude_zTXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" zTXt");
}
mng_info->need_blob = MagickTrue;
status=WriteOnePNGImage(mng_info,image_info,image,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()");
return(status);
}
#if defined(JNG_SUPPORTED)
/* Write one JNG image */
static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info,Image *image,ExceptionInfo *exception)
{
Image
*jpeg_image;
ImageInfo
*jpeg_image_info;
MagickBooleanType
logging,
status;
size_t
length;
unsigned char
*blob,
chunk[80],
*p;
unsigned int
jng_alpha_compression_method,
jng_alpha_sample_depth,
jng_color_type,
transparent;
size_t
jng_alpha_quality,
jng_quality;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOneJNGImage()");
blob=(unsigned char *) NULL;
jpeg_image=(Image *) NULL;
jpeg_image_info=(ImageInfo *) NULL;
length=0;
status=MagickTrue;
transparent=image_info->type==GrayscaleAlphaType ||
image_info->type==TrueColorAlphaType ||
image->alpha_trait != UndefinedPixelTrait;
jng_alpha_sample_depth = 0;
jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000;
jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0;
jng_alpha_quality=image_info->quality == 0UL ? 75UL :
image_info->quality;
if (jng_alpha_quality >= 1000)
jng_alpha_quality /= 1000;
length=0;
if (transparent != 0)
{
jng_color_type=14;
/* Create JPEG blob, image, and image_info */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image_info for alpha.");
jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);
if (jpeg_image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image.");
jpeg_image=SeparateImage(image,AlphaChannel,exception);
if (jpeg_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent);
jpeg_image->alpha_trait=UndefinedPixelTrait;
jpeg_image->quality=jng_alpha_quality;
jpeg_image_info->type=GrayscaleType;
(void) SetImageType(jpeg_image,GrayscaleType,exception);
(void) AcquireUniqueFilename(jpeg_image->filename);
(void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent,
"%s",jpeg_image->filename);
}
else
{
jng_alpha_compression_method=0;
jng_color_type=10;
jng_alpha_sample_depth=0;
}
/* To do: check bit depth of PNG alpha channel */
/* Check if image is grayscale. */
if (image_info->type != TrueColorAlphaType && image_info->type !=
TrueColorType && SetImageGray(image,exception))
jng_color_type-=2;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Quality = %d",(int) jng_quality);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Color Type = %d",jng_color_type);
if (transparent != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Compression = %d",jng_alpha_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Depth = %d",jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Quality = %d",(int) jng_alpha_quality);
}
}
if (transparent != 0)
{
if (jng_alpha_compression_method==0)
{
const char
*value;
/* Encode alpha as a grayscale PNG blob */
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating PNG blob.");
(void) CopyMagickString(jpeg_image_info->magick,"PNG",
MagickPathExtent);
(void) CopyMagickString(jpeg_image->magick,"PNG",MagickPathExtent);
jpeg_image_info->interlace=NoInterlace;
/* Exclude all ancillary chunks */
(void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all");
blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image,
&length,exception);
/* Retrieve sample depth used */
value=GetImageProperty(jpeg_image,"png:bit-depth-written",exception);
if (value != (char *) NULL)
jng_alpha_sample_depth= (unsigned int) value[0];
}
else
{
/* Encode alpha as a grayscale JPEG blob */
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image_info->magick,"JPEG",
MagickPathExtent);
(void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent);
jpeg_image_info->interlace=NoInterlace;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating blob.");
blob=(unsigned char *) ImageToBlob(jpeg_image_info,
jpeg_image,&length,
exception);
jng_alpha_sample_depth=8;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Successfully read jpeg_image into a blob, length=%.20g.",
(double) length);
}
/* Destroy JPEG image and image_info */
jpeg_image=DestroyImage(jpeg_image);
(void) RelinquishUniqueFileResource(jpeg_image_info->filename);
jpeg_image_info=DestroyImageInfo(jpeg_image_info);
}
/* Write JHDR chunk */
(void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */
PNGType(chunk,mng_JHDR);
LogPNGChunk(logging,mng_JHDR,16L);
PNGLong(chunk+4,(png_uint_32) image->columns);
PNGLong(chunk+8,(png_uint_32) image->rows);
chunk[12]=jng_color_type;
chunk[13]=8; /* sample depth */
chunk[14]=8; /*jng_image_compression_method */
chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8);
chunk[16]=jng_alpha_sample_depth;
chunk[17]=jng_alpha_compression_method;
chunk[18]=0; /*jng_alpha_filter_method */
chunk[19]=0; /*jng_alpha_interlace_method */
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG width:%15lu",(unsigned long) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG height:%14lu",(unsigned long) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG color type:%10d",jng_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG sample depth:%8d",8);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG compression:%9d",8);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG interlace:%11d",0);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha depth:%9d",jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha compression:%3d",jng_alpha_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha filter:%8d",0);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha interlace:%5d",0);
}
/* Write any JNG-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging);
/*
Write leading ancillary chunks
*/
if (transparent != 0)
{
/*
Write JNG bKGD chunk
*/
unsigned char
blue,
green,
red;
ssize_t
num_bytes;
if (jng_color_type == 8 || jng_color_type == 12)
num_bytes=6L;
else
num_bytes=10L;
(void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L));
PNGType(chunk,mng_bKGD);
LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L));
red=ScaleQuantumToChar(image->background_color.red);
green=ScaleQuantumToChar(image->background_color.green);
blue=ScaleQuantumToChar(image->background_color.blue);
*(chunk+4)=0;
*(chunk+5)=red;
*(chunk+6)=0;
*(chunk+7)=green;
*(chunk+8)=0;
*(chunk+9)=blue;
(void) WriteBlob(image,(size_t) num_bytes,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes));
}
if ((image->colorspace == sRGBColorspace || image->rendering_intent))
{
/*
Write JNG sRGB chunk
*/
(void) WriteBlobMSBULong(image,1L);
PNGType(chunk,mng_sRGB);
LogPNGChunk(logging,mng_sRGB,1L);
if (image->rendering_intent != UndefinedIntent)
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(image->rendering_intent));
else
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(PerceptualIntent));
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
else
{
if (image->gamma != 0.0)
{
/*
Write JNG gAMA chunk
*/
(void) WriteBlobMSBULong(image,4L);
PNGType(chunk,mng_gAMA);
LogPNGChunk(logging,mng_gAMA,4L);
PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5));
(void) WriteBlob(image,8,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,8));
}
if ((mng_info->equal_chrms == MagickFalse) &&
(image->chromaticity.red_primary.x != 0.0))
{
PrimaryInfo
primary;
/*
Write JNG cHRM chunk
*/
(void) WriteBlobMSBULong(image,32L);
PNGType(chunk,mng_cHRM);
LogPNGChunk(logging,mng_cHRM,32L);
primary=image->chromaticity.white_point;
PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.red_primary;
PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.green_primary;
PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.blue_primary;
PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5));
(void) WriteBlob(image,36,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,36));
}
}
if (image->resolution.x && image->resolution.y && !mng_info->equal_physs)
{
/*
Write JNG pHYs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_pHYs);
LogPNGChunk(logging,mng_pHYs,9L);
if (image->units == PixelsPerInchResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->resolution.x*100.0/2.54+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->resolution.y*100.0/2.54+0.5));
chunk[12]=1;
}
else
{
if (image->units == PixelsPerCentimeterResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->resolution.x*100.0+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->resolution.y*100.0+0.5));
chunk[12]=1;
}
else
{
PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5));
PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5));
chunk[12]=0;
}
}
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (mng_info->write_mng == 0 && (image->page.x || image->page.y))
{
/*
Write JNG oFFs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_oFFs);
LogPNGChunk(logging,mng_oFFs,9L);
PNGsLong(chunk+4,(ssize_t) (image->page.x));
PNGsLong(chunk+8,(ssize_t) (image->page.y));
chunk[12]=0;
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (mng_info->write_mng == 0 && (image->page.width || image->page.height))
{
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (transparent != 0)
{
if (jng_alpha_compression_method==0)
{
register ssize_t
i;
size_t
len;
/* Write IDAT chunk header */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write IDAT chunks from blob, length=%.20g.",(double)
length);
/* Copy IDAT chunks */
len=0;
p=blob+8;
for (i=8; i<(ssize_t) length; i+=len+12)
{
len=(((unsigned int) *(p ) & 0xff) << 24) +
(((unsigned int) *(p + 1) & 0xff) << 16) +
(((unsigned int) *(p + 2) & 0xff) << 8) +
(((unsigned int) *(p + 3) & 0xff) ) ;
p+=4;
if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */
{
/* Found an IDAT chunk. */
(void) WriteBlobMSBULong(image,len);
LogPNGChunk(logging,mng_IDAT,len);
(void) WriteBlob(image,len+4,p);
(void) WriteBlobMSBULong(image, crc32(0,p,(uInt) len+4));
}
else
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping %c%c%c%c chunk, length=%.20g.",
*(p),*(p+1),*(p+2),*(p+3),(double) len);
}
p+=(8+len);
}
}
else if (length != 0)
{
/* Write JDAA chunk header */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write JDAA chunk, length=%.20g.",(double) length);
(void) WriteBlobMSBULong(image,(size_t) length);
PNGType(chunk,mng_JDAA);
LogPNGChunk(logging,mng_JDAA,length);
/* Write JDAT chunk(s) data */
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,blob);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,
(uInt) length));
}
blob=(unsigned char *) RelinquishMagickMemory(blob);
}
/* Encode image as a JPEG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image_info.");
jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);
if (jpeg_image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image.");
jpeg_image=CloneImage(image,0,0,MagickTrue,exception);
if (jpeg_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent);
(void) AcquireUniqueFilename(jpeg_image->filename);
(void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent,"%s",
jpeg_image->filename);
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns,
(double) jpeg_image->rows);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (jng_color_type == 8 || jng_color_type == 12)
jpeg_image_info->type=GrayscaleType;
jpeg_image_info->quality=jng_quality;
jpeg_image->quality=jng_quality;
(void) CopyMagickString(jpeg_image_info->magick,"JPEG",MagickPathExtent);
(void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating blob.");
blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image,&length,
exception);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Successfully read jpeg_image into a blob, length=%.20g.",
(double) length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write JDAT chunk, length=%.20g.",(double) length);
}
/* Write JDAT chunk(s) */
(void) WriteBlobMSBULong(image,(size_t) length);
PNGType(chunk,mng_JDAT);
LogPNGChunk(logging,mng_JDAT,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,blob);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length));
jpeg_image=DestroyImage(jpeg_image);
(void) RelinquishUniqueFileResource(jpeg_image_info->filename);
jpeg_image_info=DestroyImageInfo(jpeg_image_info);
blob=(unsigned char *) RelinquishMagickMemory(blob);
/* Write any JNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging);
/* Write IEND chunk */
(void) WriteBlobMSBULong(image,0L);
PNGType(chunk,mng_IEND);
LogPNGChunk(logging,mng_IEND,0);
(void) WriteBlob(image,4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,4));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOneJNGImage()");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteJNGImage() writes a JPEG Network Graphics (JNG) image file.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WriteJNGImage method is:
%
% MagickBooleanType WriteJNGImage(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 MagickBooleanType WriteJNGImage(const ImageInfo *image_info,
Image *image, ExceptionInfo *exception)
{
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if ((image->columns > 65535UL) || (image->rows > 65535UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
(void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n");
status=WriteOneJNGImage(mng_info,image_info,image,exception);
mng_info=MngInfoFreeStruct(mng_info);
(void) CloseBlob(image);
(void) CatchImageException(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteJNGImage()");
return(status);
}
#endif
static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,
Image *image, ExceptionInfo *exception)
{
Image
*next_image;
MagickBooleanType
status;
volatile MagickBooleanType
logging;
MngInfo
*mng_info;
int
image_count,
need_iterations,
need_matte;
volatile int
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
need_local_plte,
#endif
all_images_are_gray,
need_defi,
use_global_plte;
register ssize_t
i;
unsigned char
chunk[800];
volatile unsigned int
write_jng,
write_mng;
volatile size_t
scene;
size_t
final_delay=0,
initial_delay;
#if (PNG_LIBPNG_VER < 10200)
if (image_info->verbose)
printf("Your PNG library (libpng-%s) is rather old.\n",
PNG_LIBPNG_VER_STRING);
#endif
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
write_mng=LocaleCompare(image_info->magick,"MNG") == 0;
/*
* See if user has requested a specific PNG subformat to be used
* for all of the PNGs in the MNG being written, e.g.,
*
* convert *.png png8:animation.mng
*
* To do: check -define png:bit_depth and png:color_type as well,
* or perhaps use mng:bit_depth and mng:color_type instead for
* global settings.
*/
mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0;
mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0;
mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0;
write_jng=MagickFalse;
if (image_info->compression == JPEGCompression)
write_jng=MagickTrue;
mng_info->adjoin=image_info->adjoin &&
(GetNextImageInList(image) != (Image *) NULL) && write_mng;
if (logging != MagickFalse)
{
/* Log some info about the input */
Image
*p;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Checking input image(s)\n"
" Image_info depth: %.20g, Type: %d",
(double) image_info->depth, image_info->type);
scene=0;
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scene: %.20g\n, Image depth: %.20g",
(double) scene++, (double) p->depth);
if (p->alpha_trait != UndefinedPixelTrait)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte: True");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte: False");
if (p->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class: PseudoClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class: DirectClass");
if (p->colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) p->colors);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: unspecified");
if (mng_info->adjoin == MagickFalse)
break;
}
}
use_global_plte=MagickFalse;
all_images_are_gray=MagickFalse;
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
need_local_plte=MagickTrue;
#endif
need_defi=MagickFalse;
need_matte=MagickFalse;
mng_info->framing_mode=1;
mng_info->old_framing_mode=1;
if (write_mng)
if (image_info->page != (char *) NULL)
{
/*
Determine image bounding box.
*/
SetGeometry(image,&mng_info->page);
(void) ParseMetaGeometry(image_info->page,&mng_info->page.x,
&mng_info->page.y,&mng_info->page.width,&mng_info->page.height);
}
if (write_mng)
{
unsigned int
need_geom;
unsigned short
red,
green,
blue;
const char *
option;
mng_info->page=image->page;
need_geom=MagickTrue;
if (mng_info->page.width || mng_info->page.height)
need_geom=MagickFalse;
/*
Check all the scenes.
*/
initial_delay=image->delay;
need_iterations=MagickFalse;
mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0;
mng_info->equal_physs=MagickTrue,
mng_info->equal_gammas=MagickTrue;
mng_info->equal_srgbs=MagickTrue;
mng_info->equal_backgrounds=MagickTrue;
image_count=0;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
all_images_are_gray=MagickTrue;
mng_info->equal_palettes=MagickFalse;
need_local_plte=MagickFalse;
#endif
for (next_image=image; next_image != (Image *) NULL; )
{
if (need_geom)
{
if ((next_image->columns+next_image->page.x) > mng_info->page.width)
mng_info->page.width=next_image->columns+next_image->page.x;
if ((next_image->rows+next_image->page.y) > mng_info->page.height)
mng_info->page.height=next_image->rows+next_image->page.y;
}
if (next_image->page.x || next_image->page.y)
need_defi=MagickTrue;
if (next_image->alpha_trait != UndefinedPixelTrait)
need_matte=MagickTrue;
if ((int) next_image->dispose >= BackgroundDispose)
if ((next_image->alpha_trait != UndefinedPixelTrait) ||
next_image->page.x || next_image->page.y ||
((next_image->columns < mng_info->page.width) &&
(next_image->rows < mng_info->page.height)))
mng_info->need_fram=MagickTrue;
if (next_image->iterations)
need_iterations=MagickTrue;
final_delay=next_image->delay;
if (final_delay != initial_delay || final_delay > 1UL*
next_image->ticks_per_second)
mng_info->need_fram=1;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
/*
check for global palette possibility.
*/
if (image->alpha_trait != UndefinedPixelTrait)
need_local_plte=MagickTrue;
if (need_local_plte == 0)
{
if (SetImageGray(image,exception) == MagickFalse)
all_images_are_gray=MagickFalse;
mng_info->equal_palettes=PalettesAreEqual(image,next_image);
if (use_global_plte == 0)
use_global_plte=mng_info->equal_palettes;
need_local_plte=!mng_info->equal_palettes;
}
#endif
if (GetNextImageInList(next_image) != (Image *) NULL)
{
if (next_image->background_color.red !=
next_image->next->background_color.red ||
next_image->background_color.green !=
next_image->next->background_color.green ||
next_image->background_color.blue !=
next_image->next->background_color.blue)
mng_info->equal_backgrounds=MagickFalse;
if (next_image->gamma != next_image->next->gamma)
mng_info->equal_gammas=MagickFalse;
if (next_image->rendering_intent !=
next_image->next->rendering_intent)
mng_info->equal_srgbs=MagickFalse;
if ((next_image->units != next_image->next->units) ||
(next_image->resolution.x != next_image->next->resolution.x) ||
(next_image->resolution.y != next_image->next->resolution.y))
mng_info->equal_physs=MagickFalse;
if (mng_info->equal_chrms)
{
if (next_image->chromaticity.red_primary.x !=
next_image->next->chromaticity.red_primary.x ||
next_image->chromaticity.red_primary.y !=
next_image->next->chromaticity.red_primary.y ||
next_image->chromaticity.green_primary.x !=
next_image->next->chromaticity.green_primary.x ||
next_image->chromaticity.green_primary.y !=
next_image->next->chromaticity.green_primary.y ||
next_image->chromaticity.blue_primary.x !=
next_image->next->chromaticity.blue_primary.x ||
next_image->chromaticity.blue_primary.y !=
next_image->next->chromaticity.blue_primary.y ||
next_image->chromaticity.white_point.x !=
next_image->next->chromaticity.white_point.x ||
next_image->chromaticity.white_point.y !=
next_image->next->chromaticity.white_point.y)
mng_info->equal_chrms=MagickFalse;
}
}
image_count++;
next_image=GetNextImageInList(next_image);
}
if (image_count < 2)
{
mng_info->equal_backgrounds=MagickFalse;
mng_info->equal_chrms=MagickFalse;
mng_info->equal_gammas=MagickFalse;
mng_info->equal_srgbs=MagickFalse;
mng_info->equal_physs=MagickFalse;
use_global_plte=MagickFalse;
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
need_local_plte=MagickTrue;
#endif
need_iterations=MagickFalse;
}
if (mng_info->need_fram == MagickFalse)
{
/*
Only certain framing rates 100/n are exactly representable without
the FRAM chunk but we'll allow some slop in VLC files
*/
if (final_delay == 0)
{
if (need_iterations != MagickFalse)
{
/*
It's probably a GIF with loop; don't run it *too* fast.
*/
if (mng_info->adjoin)
{
final_delay=10;
(void) ThrowMagickException(exception,GetMagickModule(),
CoderWarning,
"input has zero delay between all frames; assuming",
" 10 cs `%s'","");
}
}
else
mng_info->ticks_per_second=0;
}
if (final_delay != 0)
mng_info->ticks_per_second=(png_uint_32)
(image->ticks_per_second/final_delay);
if (final_delay > 50)
mng_info->ticks_per_second=2;
if (final_delay > 75)
mng_info->ticks_per_second=1;
if (final_delay > 125)
mng_info->need_fram=MagickTrue;
if (need_defi && final_delay > 2 && (final_delay != 4) &&
(final_delay != 5) && (final_delay != 10) && (final_delay != 20) &&
(final_delay != 25) && (final_delay != 50) &&
(final_delay != (size_t) image->ticks_per_second))
mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */
}
if (mng_info->need_fram != MagickFalse)
mng_info->ticks_per_second=image->ticks_per_second;
/*
If pseudocolor, we should also check to see if all the
palettes are identical and write a global PLTE if they are.
../glennrp Feb 99.
*/
/*
Write the MNG version 1.0 signature and MHDR chunk.
*/
(void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n");
(void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */
PNGType(chunk,mng_MHDR);
LogPNGChunk(logging,mng_MHDR,28L);
PNGLong(chunk+4,(png_uint_32) mng_info->page.width);
PNGLong(chunk+8,(png_uint_32) mng_info->page.height);
PNGLong(chunk+12,mng_info->ticks_per_second);
PNGLong(chunk+16,0L); /* layer count=unknown */
PNGLong(chunk+20,0L); /* frame count=unknown */
PNGLong(chunk+24,0L); /* play time=unknown */
if (write_jng)
{
if (need_matte)
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,27L); /* simplicity=LC+JNG */
else
PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */
}
else
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */
else
PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */
}
}
else
{
if (need_matte)
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,11L); /* simplicity=LC */
else
PNGLong(chunk+28,9L); /* simplicity=VLC */
}
else
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */
else
PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */
}
}
(void) WriteBlob(image,32,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,32));
option=GetImageOption(image_info,"mng:need-cacheoff");
if (option != (const char *) NULL)
{
size_t
length;
/*
Write "nEED CACHEOFF" to turn playback caching off for streaming MNG.
*/
PNGType(chunk,mng_nEED);
length=CopyMagickString((char *) chunk+4,"CACHEOFF",20);
(void) WriteBlobMSBULong(image,(size_t) length);
LogPNGChunk(logging,mng_nEED,(size_t) length);
length+=4;
(void) WriteBlob(image,length,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length));
}
if ((GetPreviousImageInList(image) == (Image *) NULL) &&
(GetNextImageInList(image) != (Image *) NULL) &&
(image->iterations != 1))
{
/*
Write MNG TERM chunk
*/
(void) WriteBlobMSBULong(image,10L); /* data length=10 */
PNGType(chunk,mng_TERM);
LogPNGChunk(logging,mng_TERM,10L);
chunk[4]=3; /* repeat animation */
chunk[5]=0; /* show last frame when done */
PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second*
final_delay/MagickMax(image->ticks_per_second,1)));
if (image->iterations == 0)
PNGLong(chunk+10,PNG_UINT_31_MAX);
else
PNGLong(chunk+10,(png_uint_32) image->iterations);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" TERM delay: %.20g",(double) (mng_info->ticks_per_second*
final_delay/MagickMax(image->ticks_per_second,1)));
if (image->iterations == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" TERM iterations: %.20g",(double) PNG_UINT_31_MAX);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image iterations: %.20g",(double) image->iterations);
}
(void) WriteBlob(image,14,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,14));
}
/*
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if ((image->colorspace == sRGBColorspace || image->rendering_intent) &&
mng_info->equal_srgbs)
{
/*
Write MNG sRGB chunk
*/
(void) WriteBlobMSBULong(image,1L);
PNGType(chunk,mng_sRGB);
LogPNGChunk(logging,mng_sRGB,1L);
if (image->rendering_intent != UndefinedIntent)
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(image->rendering_intent));
else
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(PerceptualIntent));
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
mng_info->have_write_global_srgb=MagickTrue;
}
else
{
if (image->gamma && mng_info->equal_gammas)
{
/*
Write MNG gAMA chunk
*/
(void) WriteBlobMSBULong(image,4L);
PNGType(chunk,mng_gAMA);
LogPNGChunk(logging,mng_gAMA,4L);
PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5));
(void) WriteBlob(image,8,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,8));
mng_info->have_write_global_gama=MagickTrue;
}
if (mng_info->equal_chrms)
{
PrimaryInfo
primary;
/*
Write MNG cHRM chunk
*/
(void) WriteBlobMSBULong(image,32L);
PNGType(chunk,mng_cHRM);
LogPNGChunk(logging,mng_cHRM,32L);
primary=image->chromaticity.white_point;
PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.red_primary;
PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.green_primary;
PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.blue_primary;
PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5));
(void) WriteBlob(image,36,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,36));
mng_info->have_write_global_chrm=MagickTrue;
}
}
if (image->resolution.x && image->resolution.y && mng_info->equal_physs)
{
/*
Write MNG pHYs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_pHYs);
LogPNGChunk(logging,mng_pHYs,9L);
if (image->units == PixelsPerInchResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->resolution.x*100.0/2.54+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->resolution.y*100.0/2.54+0.5));
chunk[12]=1;
}
else
{
if (image->units == PixelsPerCentimeterResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->resolution.x*100.0+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->resolution.y*100.0+0.5));
chunk[12]=1;
}
else
{
PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5));
PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5));
chunk[12]=0;
}
}
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
/*
Write MNG BACK chunk and global bKGD chunk, if the image is transparent
or does not cover the entire frame.
*/
if (write_mng && ((image->alpha_trait != UndefinedPixelTrait) ||
image->page.x > 0 || image->page.y > 0 || (image->page.width &&
(image->page.width+image->page.x < mng_info->page.width))
|| (image->page.height && (image->page.height+image->page.y
< mng_info->page.height))))
{
(void) WriteBlobMSBULong(image,6L);
PNGType(chunk,mng_BACK);
LogPNGChunk(logging,mng_BACK,6L);
red=ScaleQuantumToShort(image->background_color.red);
green=ScaleQuantumToShort(image->background_color.green);
blue=ScaleQuantumToShort(image->background_color.blue);
PNGShort(chunk+4,red);
PNGShort(chunk+6,green);
PNGShort(chunk+8,blue);
(void) WriteBlob(image,10,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,10));
if (mng_info->equal_backgrounds)
{
(void) WriteBlobMSBULong(image,6L);
PNGType(chunk,mng_bKGD);
LogPNGChunk(logging,mng_bKGD,6L);
(void) WriteBlob(image,10,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,10));
}
}
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if ((need_local_plte == MagickFalse) &&
(image->storage_class == PseudoClass) &&
(all_images_are_gray == MagickFalse))
{
size_t
data_length;
/*
Write MNG PLTE chunk
*/
data_length=3*image->colors;
(void) WriteBlobMSBULong(image,data_length);
PNGType(chunk,mng_PLTE);
LogPNGChunk(logging,mng_PLTE,data_length);
for (i=0; i < (ssize_t) image->colors; i++)
{
chunk[4+i*3]=(unsigned char) (ScaleQuantumToChar(
image->colormap[i].red) & 0xff);
chunk[5+i*3]=(unsigned char) (ScaleQuantumToChar(
image->colormap[i].green) & 0xff);
chunk[6+i*3]=(unsigned char) (ScaleQuantumToChar(
image->colormap[i].blue) & 0xff);
}
(void) WriteBlob(image,data_length+4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4)));
mng_info->have_write_global_plte=MagickTrue;
}
#endif
}
scene=0;
mng_info->delay=0;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
mng_info->equal_palettes=MagickFalse;
#endif
do
{
if (mng_info->adjoin)
{
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
/*
If we aren't using a global palette for the entire MNG, check to
see if we can use one for two or more consecutive images.
*/
if (need_local_plte && use_global_plte && !all_images_are_gray)
{
if (mng_info->IsPalette)
{
/*
When equal_palettes is true, this image has the same palette
as the previous PseudoClass image
*/
mng_info->have_write_global_plte=mng_info->equal_palettes;
mng_info->equal_palettes=PalettesAreEqual(image,image->next);
if (mng_info->equal_palettes && !mng_info->have_write_global_plte)
{
/*
Write MNG PLTE chunk
*/
size_t
data_length;
data_length=3*image->colors;
(void) WriteBlobMSBULong(image,data_length);
PNGType(chunk,mng_PLTE);
LogPNGChunk(logging,mng_PLTE,data_length);
for (i=0; i < (ssize_t) image->colors; i++)
{
chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red);
chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green);
chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue);
}
(void) WriteBlob(image,data_length+4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,
(uInt) (data_length+4)));
mng_info->have_write_global_plte=MagickTrue;
}
}
else
mng_info->have_write_global_plte=MagickFalse;
}
#endif
if (need_defi)
{
ssize_t
previous_x,
previous_y;
if (scene)
{
previous_x=mng_info->page.x;
previous_y=mng_info->page.y;
}
else
{
previous_x=0;
previous_y=0;
}
mng_info->page=image->page;
if ((mng_info->page.x != previous_x) ||
(mng_info->page.y != previous_y))
{
(void) WriteBlobMSBULong(image,12L); /* data length=12 */
PNGType(chunk,mng_DEFI);
LogPNGChunk(logging,mng_DEFI,12L);
chunk[4]=0; /* object 0 MSB */
chunk[5]=0; /* object 0 LSB */
chunk[6]=0; /* visible */
chunk[7]=0; /* abstract */
PNGLong(chunk+8,(png_uint_32) mng_info->page.x);
PNGLong(chunk+12,(png_uint_32) mng_info->page.y);
(void) WriteBlob(image,16,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,16));
}
}
}
mng_info->write_mng=write_mng;
if ((int) image->dispose >= 3)
mng_info->framing_mode=3;
if (mng_info->need_fram && mng_info->adjoin &&
((image->delay != mng_info->delay) ||
(mng_info->framing_mode != mng_info->old_framing_mode)))
{
if (image->delay == mng_info->delay)
{
/*
Write a MNG FRAM chunk with the new framing mode.
*/
(void) WriteBlobMSBULong(image,1L); /* data length=1 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,1L);
chunk[4]=(unsigned char) mng_info->framing_mode;
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
else
{
/*
Write a MNG FRAM chunk with the delay.
*/
(void) WriteBlobMSBULong(image,10L); /* data length=10 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,10L);
chunk[4]=(unsigned char) mng_info->framing_mode;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=2; /* flag for changing default delay */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=0; /* flag for changing frame clipping */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32)
((mng_info->ticks_per_second*
image->delay)/MagickMax(image->ticks_per_second,1)));
(void) WriteBlob(image,14,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,14));
mng_info->delay=(png_uint_32) image->delay;
}
mng_info->old_framing_mode=mng_info->framing_mode;
}
#if defined(JNG_SUPPORTED)
if (image_info->compression == JPEGCompression)
{
ImageInfo
*write_info;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing JNG object.");
/* To do: specify the desired alpha compression method. */
write_info=CloneImageInfo(image_info);
write_info->compression=UndefinedCompression;
status=WriteOneJNGImage(mng_info,write_info,image,exception);
write_info=DestroyImageInfo(write_info);
}
else
#endif
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG object.");
mng_info->need_blob = MagickFalse;
mng_info->ping_preserve_colormap = MagickFalse;
/* We don't want any ancillary chunks written */
mng_info->ping_exclude_bKGD=MagickTrue;
mng_info->ping_exclude_caNv=MagickTrue;
mng_info->ping_exclude_cHRM=MagickTrue;
mng_info->ping_exclude_date=MagickTrue;
mng_info->ping_exclude_EXIF=MagickTrue;
mng_info->ping_exclude_gAMA=MagickTrue;
mng_info->ping_exclude_iCCP=MagickTrue;
/* mng_info->ping_exclude_iTXt=MagickTrue; */
mng_info->ping_exclude_oFFs=MagickTrue;
mng_info->ping_exclude_pHYs=MagickTrue;
mng_info->ping_exclude_sRGB=MagickTrue;
mng_info->ping_exclude_tEXt=MagickTrue;
mng_info->ping_exclude_tRNS=MagickTrue;
mng_info->ping_exclude_vpAg=MagickTrue;
mng_info->ping_exclude_zCCP=MagickTrue;
mng_info->ping_exclude_zTXt=MagickTrue;
status=WriteOnePNGImage(mng_info,image_info,image,exception);
}
if (status == MagickFalse)
{
mng_info=MngInfoFreeStruct(mng_info);
(void) CloseBlob(image);
return(MagickFalse);
}
(void) CatchImageException(image);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (mng_info->adjoin);
if (write_mng)
{
while (GetPreviousImageInList(image) != (Image *) NULL)
image=GetPreviousImageInList(image);
/*
Write the MEND chunk.
*/
(void) WriteBlobMSBULong(image,0x00000000L);
PNGType(chunk,mng_MEND);
LogPNGChunk(logging,mng_MEND,0L);
(void) WriteBlob(image,4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,4));
}
/*
Relinquish resources.
*/
(void) CloseBlob(image);
mng_info=MngInfoFreeStruct(mng_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()");
return(MagickTrue);
}
#else /* PNG_LIBPNG_VER > 10011 */
static MagickBooleanType WritePNGImage(const ImageInfo *image_info,
Image *image)
{
(void) image;
printf("Your PNG library is too old: You have libpng-%s\n",
PNG_LIBPNG_VER_STRING);
ThrowBinaryException(CoderError,"PNG library is too old",
image_info->filename);
}
static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,
Image *image)
{
return(WritePNGImage(image_info,image));
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_2583_0 |
crossvul-cpp_data_bad_3060_7 |
#include <linux/ceph/ceph_debug.h>
#include <linux/err.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include <crypto/hash.h>
#include <linux/key-type.h>
#include <keys/ceph-type.h>
#include <keys/user-type.h>
#include <linux/ceph/decode.h>
#include "crypto.h"
int ceph_crypto_key_clone(struct ceph_crypto_key *dst,
const struct ceph_crypto_key *src)
{
memcpy(dst, src, sizeof(struct ceph_crypto_key));
dst->key = kmemdup(src->key, src->len, GFP_NOFS);
if (!dst->key)
return -ENOMEM;
return 0;
}
int ceph_crypto_key_encode(struct ceph_crypto_key *key, void **p, void *end)
{
if (*p + sizeof(u16) + sizeof(key->created) +
sizeof(u16) + key->len > end)
return -ERANGE;
ceph_encode_16(p, key->type);
ceph_encode_copy(p, &key->created, sizeof(key->created));
ceph_encode_16(p, key->len);
ceph_encode_copy(p, key->key, key->len);
return 0;
}
int ceph_crypto_key_decode(struct ceph_crypto_key *key, void **p, void *end)
{
ceph_decode_need(p, end, 2*sizeof(u16) + sizeof(key->created), bad);
key->type = ceph_decode_16(p);
ceph_decode_copy(p, &key->created, sizeof(key->created));
key->len = ceph_decode_16(p);
ceph_decode_need(p, end, key->len, bad);
key->key = kmalloc(key->len, GFP_NOFS);
if (!key->key)
return -ENOMEM;
ceph_decode_copy(p, key->key, key->len);
return 0;
bad:
dout("failed to decode crypto key\n");
return -EINVAL;
}
int ceph_crypto_key_unarmor(struct ceph_crypto_key *key, const char *inkey)
{
int inlen = strlen(inkey);
int blen = inlen * 3 / 4;
void *buf, *p;
int ret;
dout("crypto_key_unarmor %s\n", inkey);
buf = kmalloc(blen, GFP_NOFS);
if (!buf)
return -ENOMEM;
blen = ceph_unarmor(buf, inkey, inkey+inlen);
if (blen < 0) {
kfree(buf);
return blen;
}
p = buf;
ret = ceph_crypto_key_decode(key, &p, p + blen);
kfree(buf);
if (ret)
return ret;
dout("crypto_key_unarmor key %p type %d len %d\n", key,
key->type, key->len);
return 0;
}
#define AES_KEY_SIZE 16
static struct crypto_blkcipher *ceph_crypto_alloc_cipher(void)
{
return crypto_alloc_blkcipher("cbc(aes)", 0, CRYPTO_ALG_ASYNC);
}
static const u8 *aes_iv = (u8 *)CEPH_AES_IV;
static int ceph_aes_encrypt(const void *key, int key_len,
void *dst, size_t *dst_len,
const void *src, size_t src_len)
{
struct scatterlist sg_in[2], sg_out[1];
struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher();
struct blkcipher_desc desc = { .tfm = tfm, .flags = 0 };
int ret;
void *iv;
int ivsize;
size_t zero_padding = (0x10 - (src_len & 0x0f));
char pad[16];
if (IS_ERR(tfm))
return PTR_ERR(tfm);
memset(pad, zero_padding, zero_padding);
*dst_len = src_len + zero_padding;
crypto_blkcipher_setkey((void *)tfm, key, key_len);
sg_init_table(sg_in, 2);
sg_set_buf(&sg_in[0], src, src_len);
sg_set_buf(&sg_in[1], pad, zero_padding);
sg_init_table(sg_out, 1);
sg_set_buf(sg_out, dst, *dst_len);
iv = crypto_blkcipher_crt(tfm)->iv;
ivsize = crypto_blkcipher_ivsize(tfm);
memcpy(iv, aes_iv, ivsize);
/*
print_hex_dump(KERN_ERR, "enc key: ", DUMP_PREFIX_NONE, 16, 1,
key, key_len, 1);
print_hex_dump(KERN_ERR, "enc src: ", DUMP_PREFIX_NONE, 16, 1,
src, src_len, 1);
print_hex_dump(KERN_ERR, "enc pad: ", DUMP_PREFIX_NONE, 16, 1,
pad, zero_padding, 1);
*/
ret = crypto_blkcipher_encrypt(&desc, sg_out, sg_in,
src_len + zero_padding);
crypto_free_blkcipher(tfm);
if (ret < 0)
pr_err("ceph_aes_crypt failed %d\n", ret);
/*
print_hex_dump(KERN_ERR, "enc out: ", DUMP_PREFIX_NONE, 16, 1,
dst, *dst_len, 1);
*/
return 0;
}
static int ceph_aes_encrypt2(const void *key, int key_len, void *dst,
size_t *dst_len,
const void *src1, size_t src1_len,
const void *src2, size_t src2_len)
{
struct scatterlist sg_in[3], sg_out[1];
struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher();
struct blkcipher_desc desc = { .tfm = tfm, .flags = 0 };
int ret;
void *iv;
int ivsize;
size_t zero_padding = (0x10 - ((src1_len + src2_len) & 0x0f));
char pad[16];
if (IS_ERR(tfm))
return PTR_ERR(tfm);
memset(pad, zero_padding, zero_padding);
*dst_len = src1_len + src2_len + zero_padding;
crypto_blkcipher_setkey((void *)tfm, key, key_len);
sg_init_table(sg_in, 3);
sg_set_buf(&sg_in[0], src1, src1_len);
sg_set_buf(&sg_in[1], src2, src2_len);
sg_set_buf(&sg_in[2], pad, zero_padding);
sg_init_table(sg_out, 1);
sg_set_buf(sg_out, dst, *dst_len);
iv = crypto_blkcipher_crt(tfm)->iv;
ivsize = crypto_blkcipher_ivsize(tfm);
memcpy(iv, aes_iv, ivsize);
/*
print_hex_dump(KERN_ERR, "enc key: ", DUMP_PREFIX_NONE, 16, 1,
key, key_len, 1);
print_hex_dump(KERN_ERR, "enc src1: ", DUMP_PREFIX_NONE, 16, 1,
src1, src1_len, 1);
print_hex_dump(KERN_ERR, "enc src2: ", DUMP_PREFIX_NONE, 16, 1,
src2, src2_len, 1);
print_hex_dump(KERN_ERR, "enc pad: ", DUMP_PREFIX_NONE, 16, 1,
pad, zero_padding, 1);
*/
ret = crypto_blkcipher_encrypt(&desc, sg_out, sg_in,
src1_len + src2_len + zero_padding);
crypto_free_blkcipher(tfm);
if (ret < 0)
pr_err("ceph_aes_crypt2 failed %d\n", ret);
/*
print_hex_dump(KERN_ERR, "enc out: ", DUMP_PREFIX_NONE, 16, 1,
dst, *dst_len, 1);
*/
return 0;
}
static int ceph_aes_decrypt(const void *key, int key_len,
void *dst, size_t *dst_len,
const void *src, size_t src_len)
{
struct scatterlist sg_in[1], sg_out[2];
struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher();
struct blkcipher_desc desc = { .tfm = tfm };
char pad[16];
void *iv;
int ivsize;
int ret;
int last_byte;
if (IS_ERR(tfm))
return PTR_ERR(tfm);
crypto_blkcipher_setkey((void *)tfm, key, key_len);
sg_init_table(sg_in, 1);
sg_init_table(sg_out, 2);
sg_set_buf(sg_in, src, src_len);
sg_set_buf(&sg_out[0], dst, *dst_len);
sg_set_buf(&sg_out[1], pad, sizeof(pad));
iv = crypto_blkcipher_crt(tfm)->iv;
ivsize = crypto_blkcipher_ivsize(tfm);
memcpy(iv, aes_iv, ivsize);
/*
print_hex_dump(KERN_ERR, "dec key: ", DUMP_PREFIX_NONE, 16, 1,
key, key_len, 1);
print_hex_dump(KERN_ERR, "dec in: ", DUMP_PREFIX_NONE, 16, 1,
src, src_len, 1);
*/
ret = crypto_blkcipher_decrypt(&desc, sg_out, sg_in, src_len);
crypto_free_blkcipher(tfm);
if (ret < 0) {
pr_err("ceph_aes_decrypt failed %d\n", ret);
return ret;
}
if (src_len <= *dst_len)
last_byte = ((char *)dst)[src_len - 1];
else
last_byte = pad[src_len - *dst_len - 1];
if (last_byte <= 16 && src_len >= last_byte) {
*dst_len = src_len - last_byte;
} else {
pr_err("ceph_aes_decrypt got bad padding %d on src len %d\n",
last_byte, (int)src_len);
return -EPERM; /* bad padding */
}
/*
print_hex_dump(KERN_ERR, "dec out: ", DUMP_PREFIX_NONE, 16, 1,
dst, *dst_len, 1);
*/
return 0;
}
static int ceph_aes_decrypt2(const void *key, int key_len,
void *dst1, size_t *dst1_len,
void *dst2, size_t *dst2_len,
const void *src, size_t src_len)
{
struct scatterlist sg_in[1], sg_out[3];
struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher();
struct blkcipher_desc desc = { .tfm = tfm };
char pad[16];
void *iv;
int ivsize;
int ret;
int last_byte;
if (IS_ERR(tfm))
return PTR_ERR(tfm);
sg_init_table(sg_in, 1);
sg_set_buf(sg_in, src, src_len);
sg_init_table(sg_out, 3);
sg_set_buf(&sg_out[0], dst1, *dst1_len);
sg_set_buf(&sg_out[1], dst2, *dst2_len);
sg_set_buf(&sg_out[2], pad, sizeof(pad));
crypto_blkcipher_setkey((void *)tfm, key, key_len);
iv = crypto_blkcipher_crt(tfm)->iv;
ivsize = crypto_blkcipher_ivsize(tfm);
memcpy(iv, aes_iv, ivsize);
/*
print_hex_dump(KERN_ERR, "dec key: ", DUMP_PREFIX_NONE, 16, 1,
key, key_len, 1);
print_hex_dump(KERN_ERR, "dec in: ", DUMP_PREFIX_NONE, 16, 1,
src, src_len, 1);
*/
ret = crypto_blkcipher_decrypt(&desc, sg_out, sg_in, src_len);
crypto_free_blkcipher(tfm);
if (ret < 0) {
pr_err("ceph_aes_decrypt failed %d\n", ret);
return ret;
}
if (src_len <= *dst1_len)
last_byte = ((char *)dst1)[src_len - 1];
else if (src_len <= *dst1_len + *dst2_len)
last_byte = ((char *)dst2)[src_len - *dst1_len - 1];
else
last_byte = pad[src_len - *dst1_len - *dst2_len - 1];
if (last_byte <= 16 && src_len >= last_byte) {
src_len -= last_byte;
} else {
pr_err("ceph_aes_decrypt got bad padding %d on src len %d\n",
last_byte, (int)src_len);
return -EPERM; /* bad padding */
}
if (src_len < *dst1_len) {
*dst1_len = src_len;
*dst2_len = 0;
} else {
*dst2_len = src_len - *dst1_len;
}
/*
print_hex_dump(KERN_ERR, "dec out1: ", DUMP_PREFIX_NONE, 16, 1,
dst1, *dst1_len, 1);
print_hex_dump(KERN_ERR, "dec out2: ", DUMP_PREFIX_NONE, 16, 1,
dst2, *dst2_len, 1);
*/
return 0;
}
int ceph_decrypt(struct ceph_crypto_key *secret, void *dst, size_t *dst_len,
const void *src, size_t src_len)
{
switch (secret->type) {
case CEPH_CRYPTO_NONE:
if (*dst_len < src_len)
return -ERANGE;
memcpy(dst, src, src_len);
*dst_len = src_len;
return 0;
case CEPH_CRYPTO_AES:
return ceph_aes_decrypt(secret->key, secret->len, dst,
dst_len, src, src_len);
default:
return -EINVAL;
}
}
int ceph_decrypt2(struct ceph_crypto_key *secret,
void *dst1, size_t *dst1_len,
void *dst2, size_t *dst2_len,
const void *src, size_t src_len)
{
size_t t;
switch (secret->type) {
case CEPH_CRYPTO_NONE:
if (*dst1_len + *dst2_len < src_len)
return -ERANGE;
t = min(*dst1_len, src_len);
memcpy(dst1, src, t);
*dst1_len = t;
src += t;
src_len -= t;
if (src_len) {
t = min(*dst2_len, src_len);
memcpy(dst2, src, t);
*dst2_len = t;
}
return 0;
case CEPH_CRYPTO_AES:
return ceph_aes_decrypt2(secret->key, secret->len,
dst1, dst1_len, dst2, dst2_len,
src, src_len);
default:
return -EINVAL;
}
}
int ceph_encrypt(struct ceph_crypto_key *secret, void *dst, size_t *dst_len,
const void *src, size_t src_len)
{
switch (secret->type) {
case CEPH_CRYPTO_NONE:
if (*dst_len < src_len)
return -ERANGE;
memcpy(dst, src, src_len);
*dst_len = src_len;
return 0;
case CEPH_CRYPTO_AES:
return ceph_aes_encrypt(secret->key, secret->len, dst,
dst_len, src, src_len);
default:
return -EINVAL;
}
}
int ceph_encrypt2(struct ceph_crypto_key *secret, void *dst, size_t *dst_len,
const void *src1, size_t src1_len,
const void *src2, size_t src2_len)
{
switch (secret->type) {
case CEPH_CRYPTO_NONE:
if (*dst_len < src1_len + src2_len)
return -ERANGE;
memcpy(dst, src1, src1_len);
memcpy(dst + src1_len, src2, src2_len);
*dst_len = src1_len + src2_len;
return 0;
case CEPH_CRYPTO_AES:
return ceph_aes_encrypt2(secret->key, secret->len, dst, dst_len,
src1, src1_len, src2, src2_len);
default:
return -EINVAL;
}
}
static int ceph_key_preparse(struct key_preparsed_payload *prep)
{
struct ceph_crypto_key *ckey;
size_t datalen = prep->datalen;
int ret;
void *p;
ret = -EINVAL;
if (datalen <= 0 || datalen > 32767 || !prep->data)
goto err;
ret = -ENOMEM;
ckey = kmalloc(sizeof(*ckey), GFP_KERNEL);
if (!ckey)
goto err;
/* TODO ceph_crypto_key_decode should really take const input */
p = (void *)prep->data;
ret = ceph_crypto_key_decode(ckey, &p, (char*)prep->data+datalen);
if (ret < 0)
goto err_ckey;
prep->payload[0] = ckey;
prep->quotalen = datalen;
return 0;
err_ckey:
kfree(ckey);
err:
return ret;
}
static void ceph_key_free_preparse(struct key_preparsed_payload *prep)
{
struct ceph_crypto_key *ckey = prep->payload[0];
ceph_crypto_key_destroy(ckey);
kfree(ckey);
}
static void ceph_key_destroy(struct key *key)
{
struct ceph_crypto_key *ckey = key->payload.data;
ceph_crypto_key_destroy(ckey);
kfree(ckey);
}
struct key_type key_type_ceph = {
.name = "ceph",
.preparse = ceph_key_preparse,
.free_preparse = ceph_key_free_preparse,
.instantiate = generic_key_instantiate,
.match = user_match,
.destroy = ceph_key_destroy,
};
int ceph_crypto_init(void) {
return register_key_type(&key_type_ceph);
}
void ceph_crypto_shutdown(void) {
unregister_key_type(&key_type_ceph);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_3060_7 |
crossvul-cpp_data_bad_5714_1 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* RDP Security
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "security.h"
/* 0x36 repeated 40 times */
static const BYTE pad1[40] =
{
"\x36\x36\x36\x36\x36\x36\x36\x36"
"\x36\x36\x36\x36\x36\x36\x36\x36"
"\x36\x36\x36\x36\x36\x36\x36\x36"
"\x36\x36\x36\x36\x36\x36\x36\x36"
"\x36\x36\x36\x36\x36\x36\x36\x36"
};
/* 0x5C repeated 48 times */
static const BYTE pad2[48] =
{
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
};
static const BYTE
fips_reverse_table[256] =
{
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff
};
static const BYTE
fips_oddparity_table[256] =
{
0x01, 0x01, 0x02, 0x02, 0x04, 0x04, 0x07, 0x07,
0x08, 0x08, 0x0b, 0x0b, 0x0d, 0x0d, 0x0e, 0x0e,
0x10, 0x10, 0x13, 0x13, 0x15, 0x15, 0x16, 0x16,
0x19, 0x19, 0x1a, 0x1a, 0x1c, 0x1c, 0x1f, 0x1f,
0x20, 0x20, 0x23, 0x23, 0x25, 0x25, 0x26, 0x26,
0x29, 0x29, 0x2a, 0x2a, 0x2c, 0x2c, 0x2f, 0x2f,
0x31, 0x31, 0x32, 0x32, 0x34, 0x34, 0x37, 0x37,
0x38, 0x38, 0x3b, 0x3b, 0x3d, 0x3d, 0x3e, 0x3e,
0x40, 0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46,
0x49, 0x49, 0x4a, 0x4a, 0x4c, 0x4c, 0x4f, 0x4f,
0x51, 0x51, 0x52, 0x52, 0x54, 0x54, 0x57, 0x57,
0x58, 0x58, 0x5b, 0x5b, 0x5d, 0x5d, 0x5e, 0x5e,
0x61, 0x61, 0x62, 0x62, 0x64, 0x64, 0x67, 0x67,
0x68, 0x68, 0x6b, 0x6b, 0x6d, 0x6d, 0x6e, 0x6e,
0x70, 0x70, 0x73, 0x73, 0x75, 0x75, 0x76, 0x76,
0x79, 0x79, 0x7a, 0x7a, 0x7c, 0x7c, 0x7f, 0x7f,
0x80, 0x80, 0x83, 0x83, 0x85, 0x85, 0x86, 0x86,
0x89, 0x89, 0x8a, 0x8a, 0x8c, 0x8c, 0x8f, 0x8f,
0x91, 0x91, 0x92, 0x92, 0x94, 0x94, 0x97, 0x97,
0x98, 0x98, 0x9b, 0x9b, 0x9d, 0x9d, 0x9e, 0x9e,
0xa1, 0xa1, 0xa2, 0xa2, 0xa4, 0xa4, 0xa7, 0xa7,
0xa8, 0xa8, 0xab, 0xab, 0xad, 0xad, 0xae, 0xae,
0xb0, 0xb0, 0xb3, 0xb3, 0xb5, 0xb5, 0xb6, 0xb6,
0xb9, 0xb9, 0xba, 0xba, 0xbc, 0xbc, 0xbf, 0xbf,
0xc1, 0xc1, 0xc2, 0xc2, 0xc4, 0xc4, 0xc7, 0xc7,
0xc8, 0xc8, 0xcb, 0xcb, 0xcd, 0xcd, 0xce, 0xce,
0xd0, 0xd0, 0xd3, 0xd3, 0xd5, 0xd5, 0xd6, 0xd6,
0xd9, 0xd9, 0xda, 0xda, 0xdc, 0xdc, 0xdf, 0xdf,
0xe0, 0xe0, 0xe3, 0xe3, 0xe5, 0xe5, 0xe6, 0xe6,
0xe9, 0xe9, 0xea, 0xea, 0xec, 0xec, 0xef, 0xef,
0xf1, 0xf1, 0xf2, 0xf2, 0xf4, 0xf4, 0xf7, 0xf7,
0xf8, 0xf8, 0xfb, 0xfb, 0xfd, 0xfd, 0xfe, 0xfe
};
static void security_salted_hash(const BYTE* salt, const BYTE* input, int length,
const BYTE* salt1, const BYTE* salt2, BYTE* output)
{
CryptoMd5 md5;
CryptoSha1 sha1;
BYTE sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH];
/* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1(Input + Salt + Salt1 + Salt2)) */
/* SHA1_Digest = SHA1(Input + Salt + Salt1 + Salt2) */
sha1 = crypto_sha1_init();
crypto_sha1_update(sha1, input, length); /* Input */
crypto_sha1_update(sha1, salt, 48); /* Salt (48 bytes) */
crypto_sha1_update(sha1, salt1, 32); /* Salt1 (32 bytes) */
crypto_sha1_update(sha1, salt2, 32); /* Salt2 (32 bytes) */
crypto_sha1_final(sha1, sha1_digest);
/* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1_Digest) */
md5 = crypto_md5_init();
crypto_md5_update(md5, salt, 48); /* Salt (48 bytes) */
crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */
crypto_md5_final(md5, output);
}
static void security_premaster_hash(const char* input, int length, const BYTE* premaster_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output)
{
/* PremasterHash(Input) = SaltedHash(PremasterSecret, Input, ClientRandom, ServerRandom) */
security_salted_hash(premaster_secret, (BYTE*)input, length, client_random, server_random, output);
}
void security_master_secret(const BYTE* premaster_secret, const BYTE* client_random,
const BYTE* server_random, BYTE* output)
{
/* MasterSecret = PremasterHash('A') + PremasterHash('BB') + PremasterHash('CCC') */
security_premaster_hash("A", 1, premaster_secret, client_random, server_random, &output[0]);
security_premaster_hash("BB", 2, premaster_secret, client_random, server_random, &output[16]);
security_premaster_hash("CCC", 3, premaster_secret, client_random, server_random, &output[32]);
}
static void security_master_hash(const char* input, int length, const BYTE* master_secret,
const BYTE* client_random, const BYTE* server_random, BYTE* output)
{
/* MasterHash(Input) = SaltedHash(MasterSecret, Input, ServerRandom, ClientRandom) */
security_salted_hash(master_secret, (const BYTE*)input, length, server_random, client_random, output);
}
void security_session_key_blob(const BYTE* master_secret, const BYTE* client_random,
const BYTE* server_random, BYTE* output)
{
/* MasterHash = MasterHash('A') + MasterHash('BB') + MasterHash('CCC') */
security_master_hash("A", 1, master_secret, client_random, server_random, &output[0]);
security_master_hash("BB", 2, master_secret, client_random, server_random, &output[16]);
security_master_hash("CCC", 3, master_secret, client_random, server_random, &output[32]);
}
void security_mac_salt_key(const BYTE* session_key_blob, const BYTE* client_random,
const BYTE* server_random, BYTE* output)
{
/* MacSaltKey = First128Bits(SessionKeyBlob) */
memcpy(output, session_key_blob, 16);
}
void security_md5_16_32_32(const BYTE* in0, const BYTE* in1, const BYTE* in2, BYTE* output)
{
CryptoMd5 md5;
md5 = crypto_md5_init();
crypto_md5_update(md5, in0, 16);
crypto_md5_update(md5, in1, 32);
crypto_md5_update(md5, in2, 32);
crypto_md5_final(md5, output);
}
void security_licensing_encryption_key(const BYTE* session_key_blob, const BYTE* client_random,
const BYTE* server_random, BYTE* output)
{
/* LicensingEncryptionKey = MD5(Second128Bits(SessionKeyBlob) + ClientRandom + ServerRandom)) */
security_md5_16_32_32(&session_key_blob[16], client_random, server_random, output);
}
void security_UINT32_le(BYTE* output, UINT32 value)
{
output[0] = (value) & 0xFF;
output[1] = (value >> 8) & 0xFF;
output[2] = (value >> 16) & 0xFF;
output[3] = (value >> 24) & 0xFF;
}
void security_mac_data(const BYTE* mac_salt_key, const BYTE* data, UINT32 length,
BYTE* output)
{
CryptoMd5 md5;
CryptoSha1 sha1;
BYTE length_le[4];
BYTE sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH];
/* MacData = MD5(MacSaltKey + pad2 + SHA1(MacSaltKey + pad1 + length + data)) */
security_UINT32_le(length_le, length); /* length must be little-endian */
/* SHA1_Digest = SHA1(MacSaltKey + pad1 + length + data) */
sha1 = crypto_sha1_init();
crypto_sha1_update(sha1, mac_salt_key, 16); /* MacSaltKey */
crypto_sha1_update(sha1, pad1, sizeof(pad1)); /* pad1 */
crypto_sha1_update(sha1, length_le, sizeof(length_le)); /* length */
crypto_sha1_update(sha1, data, length); /* data */
crypto_sha1_final(sha1, sha1_digest);
/* MacData = MD5(MacSaltKey + pad2 + SHA1_Digest) */
md5 = crypto_md5_init();
crypto_md5_update(md5, mac_salt_key, 16); /* MacSaltKey */
crypto_md5_update(md5, pad2, sizeof(pad2)); /* pad2 */
crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */
crypto_md5_final(md5, output);
}
void security_mac_signature(rdpRdp *rdp, const BYTE* data, UINT32 length, BYTE* output)
{
CryptoMd5 md5;
CryptoSha1 sha1;
BYTE length_le[4];
BYTE md5_digest[CRYPTO_MD5_DIGEST_LENGTH];
BYTE sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH];
security_UINT32_le(length_le, length); /* length must be little-endian */
/* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */
sha1 = crypto_sha1_init();
crypto_sha1_update(sha1, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */
crypto_sha1_update(sha1, pad1, sizeof(pad1)); /* pad1 */
crypto_sha1_update(sha1, length_le, sizeof(length_le)); /* length */
crypto_sha1_update(sha1, data, length); /* data */
crypto_sha1_final(sha1, sha1_digest);
/* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */
md5 = crypto_md5_init();
crypto_md5_update(md5, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */
crypto_md5_update(md5, pad2, sizeof(pad2)); /* pad2 */
crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */
crypto_md5_final(md5, md5_digest);
memcpy(output, md5_digest, 8);
}
void security_salted_mac_signature(rdpRdp *rdp, const BYTE* data, UINT32 length,
BOOL encryption, BYTE* output)
{
CryptoMd5 md5;
CryptoSha1 sha1;
BYTE length_le[4];
BYTE use_count_le[4];
BYTE md5_digest[CRYPTO_MD5_DIGEST_LENGTH];
BYTE sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH];
security_UINT32_le(length_le, length); /* length must be little-endian */
if (encryption)
{
security_UINT32_le(use_count_le, rdp->encrypt_checksum_use_count);
}
else
{
/*
* We calculate checksum on plain text, so we must have already
* decrypt it, which means decrypt_checksum_use_count is off by one.
*/
security_UINT32_le(use_count_le, rdp->decrypt_checksum_use_count - 1);
}
/* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */
sha1 = crypto_sha1_init();
crypto_sha1_update(sha1, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */
crypto_sha1_update(sha1, pad1, sizeof(pad1)); /* pad1 */
crypto_sha1_update(sha1, length_le, sizeof(length_le)); /* length */
crypto_sha1_update(sha1, data, length); /* data */
crypto_sha1_update(sha1, use_count_le, sizeof(use_count_le)); /* encryptionCount */
crypto_sha1_final(sha1, sha1_digest);
/* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */
md5 = crypto_md5_init();
crypto_md5_update(md5, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */
crypto_md5_update(md5, pad2, sizeof(pad2)); /* pad2 */
crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */
crypto_md5_final(md5, md5_digest);
memcpy(output, md5_digest, 8);
}
static void security_A(BYTE* master_secret, const BYTE* client_random, BYTE* server_random,
BYTE* output)
{
security_premaster_hash("A", 1, master_secret, client_random, server_random, &output[0]);
security_premaster_hash("BB", 2, master_secret, client_random, server_random, &output[16]);
security_premaster_hash("CCC", 3, master_secret, client_random, server_random, &output[32]);
}
static void security_X(BYTE* master_secret, const BYTE* client_random, BYTE* server_random,
BYTE* output)
{
security_premaster_hash("X", 1, master_secret, client_random, server_random, &output[0]);
security_premaster_hash("YY", 2, master_secret, client_random, server_random, &output[16]);
security_premaster_hash("ZZZ", 3, master_secret, client_random, server_random, &output[32]);
}
static void fips_expand_key_bits(BYTE* in, BYTE* out)
{
BYTE buf[21], c;
int i, b, p, r;
/* reverse every byte in the key */
for (i = 0; i < 21; i++)
buf[i] = fips_reverse_table[in[i]];
/* insert a zero-bit after every 7th bit */
for (i = 0, b = 0; i < 24; i++, b += 7)
{
p = b / 8;
r = b % 8;
if (r == 0)
{
out[i] = buf[p] & 0xfe;
}
else
{
/* c is accumulator */
c = buf[p] << r;
c |= buf[p + 1] >> (8 - r);
out[i] = c & 0xfe;
}
}
/* reverse every byte */
/* alter lsb so the byte has odd parity */
for (i = 0; i < 24; i++)
out[i] = fips_oddparity_table[fips_reverse_table[out[i]]];
}
BOOL security_establish_keys(const BYTE* client_random, rdpRdp* rdp)
{
BYTE pre_master_secret[48];
BYTE master_secret[48];
BYTE session_key_blob[48];
BYTE* server_random;
BYTE salt40[] = { 0xD1, 0x26, 0x9E };
rdpSettings* settings;
settings = rdp->settings;
server_random = settings->ServerRandom;
if (settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
{
CryptoSha1 sha1;
BYTE client_encrypt_key_t[CRYPTO_SHA1_DIGEST_LENGTH + 1];
BYTE client_decrypt_key_t[CRYPTO_SHA1_DIGEST_LENGTH + 1];
printf("FIPS Compliant encryption level.\n");
/* disable fastpath input; it doesnt handle FIPS encryption yet */
rdp->settings->FastPathInput = FALSE;
sha1 = crypto_sha1_init();
crypto_sha1_update(sha1, client_random + 16, 16);
crypto_sha1_update(sha1, server_random + 16, 16);
crypto_sha1_final(sha1, client_encrypt_key_t);
client_encrypt_key_t[20] = client_encrypt_key_t[0];
fips_expand_key_bits(client_encrypt_key_t, rdp->fips_encrypt_key);
sha1 = crypto_sha1_init();
crypto_sha1_update(sha1, client_random, 16);
crypto_sha1_update(sha1, server_random, 16);
crypto_sha1_final(sha1, client_decrypt_key_t);
client_decrypt_key_t[20] = client_decrypt_key_t[0];
fips_expand_key_bits(client_decrypt_key_t, rdp->fips_decrypt_key);
sha1 = crypto_sha1_init();
crypto_sha1_update(sha1, client_decrypt_key_t, 20);
crypto_sha1_update(sha1, client_encrypt_key_t, 20);
crypto_sha1_final(sha1, rdp->fips_sign_key);
}
memcpy(pre_master_secret, client_random, 24);
memcpy(pre_master_secret + 24, server_random, 24);
security_A(pre_master_secret, client_random, server_random, master_secret);
security_X(master_secret, client_random, server_random, session_key_blob);
memcpy(rdp->sign_key, session_key_blob, 16);
if (rdp->settings->ServerMode)
{
security_md5_16_32_32(&session_key_blob[16], client_random,
server_random, rdp->encrypt_key);
security_md5_16_32_32(&session_key_blob[32], client_random,
server_random, rdp->decrypt_key);
}
else
{
security_md5_16_32_32(&session_key_blob[16], client_random,
server_random, rdp->decrypt_key);
security_md5_16_32_32(&session_key_blob[32], client_random,
server_random, rdp->encrypt_key);
}
if (settings->EncryptionMethods == 1) /* 40 and 56 bit */
{
memcpy(rdp->sign_key, salt40, 3); /* TODO 56 bit */
memcpy(rdp->decrypt_key, salt40, 3); /* TODO 56 bit */
memcpy(rdp->encrypt_key, salt40, 3); /* TODO 56 bit */
rdp->rc4_key_len = 8;
}
else if (settings->EncryptionMethods == 2) /* 128 bit */
{
rdp->rc4_key_len = 16;
}
memcpy(rdp->decrypt_update_key, rdp->decrypt_key, 16);
memcpy(rdp->encrypt_update_key, rdp->encrypt_key, 16);
rdp->decrypt_use_count = 0;
rdp->decrypt_checksum_use_count = 0;
rdp->encrypt_use_count =0;
rdp->encrypt_checksum_use_count =0;
return TRUE;
}
BOOL security_key_update(BYTE* key, BYTE* update_key, int key_len)
{
BYTE sha1h[CRYPTO_SHA1_DIGEST_LENGTH];
CryptoMd5 md5;
CryptoSha1 sha1;
CryptoRc4 rc4;
BYTE salt40[] = { 0xD1, 0x26, 0x9E };
sha1 = crypto_sha1_init();
crypto_sha1_update(sha1, update_key, key_len);
crypto_sha1_update(sha1, pad1, sizeof(pad1));
crypto_sha1_update(sha1, key, key_len);
crypto_sha1_final(sha1, sha1h);
md5 = crypto_md5_init();
crypto_md5_update(md5, update_key, key_len);
crypto_md5_update(md5, pad2, sizeof(pad2));
crypto_md5_update(md5, sha1h, sizeof(sha1h));
crypto_md5_final(md5, key);
rc4 = crypto_rc4_init(key, key_len);
crypto_rc4(rc4, key_len, key, key);
crypto_rc4_free(rc4);
if (key_len == 8)
memcpy(key, salt40, 3); /* TODO 56 bit */
return TRUE;
}
BOOL security_encrypt(BYTE* data, int length, rdpRdp* rdp)
{
if (rdp->encrypt_use_count >= 4096)
{
security_key_update(rdp->encrypt_key, rdp->encrypt_update_key, rdp->rc4_key_len);
crypto_rc4_free(rdp->rc4_encrypt_key);
rdp->rc4_encrypt_key = crypto_rc4_init(rdp->encrypt_key, rdp->rc4_key_len);
rdp->encrypt_use_count = 0;
}
crypto_rc4(rdp->rc4_encrypt_key, length, data, data);
rdp->encrypt_use_count++;
rdp->encrypt_checksum_use_count++;
return TRUE;
}
BOOL security_decrypt(BYTE* data, int length, rdpRdp* rdp)
{
if (rdp->decrypt_use_count >= 4096)
{
security_key_update(rdp->decrypt_key, rdp->decrypt_update_key, rdp->rc4_key_len);
crypto_rc4_free(rdp->rc4_decrypt_key);
rdp->rc4_decrypt_key = crypto_rc4_init(rdp->decrypt_key, rdp->rc4_key_len);
rdp->decrypt_use_count = 0;
}
crypto_rc4(rdp->rc4_decrypt_key, length, data, data);
rdp->decrypt_use_count += 1;
rdp->decrypt_checksum_use_count++;
return TRUE;
}
void security_hmac_signature(const BYTE* data, int length, BYTE* output, rdpRdp* rdp)
{
BYTE buf[20];
BYTE use_count_le[4];
security_UINT32_le(use_count_le, rdp->encrypt_use_count);
crypto_hmac_sha1_init(rdp->fips_hmac, rdp->fips_sign_key, 20);
crypto_hmac_update(rdp->fips_hmac, data, length);
crypto_hmac_update(rdp->fips_hmac, use_count_le, 4);
crypto_hmac_final(rdp->fips_hmac, buf, 20);
memmove(output, buf, 8);
}
BOOL security_fips_encrypt(BYTE* data, int length, rdpRdp* rdp)
{
crypto_des3_encrypt(rdp->fips_encrypt, length, data, data);
rdp->encrypt_use_count++;
return TRUE;
}
BOOL security_fips_decrypt(BYTE* data, int length, rdpRdp* rdp)
{
crypto_des3_decrypt(rdp->fips_decrypt, length, data, data);
return TRUE;
}
BOOL security_fips_check_signature(const BYTE* data, int length, const BYTE* sig, rdpRdp* rdp)
{
BYTE buf[20];
BYTE use_count_le[4];
security_UINT32_le(use_count_le, rdp->decrypt_use_count);
crypto_hmac_sha1_init(rdp->fips_hmac, rdp->fips_sign_key, 20);
crypto_hmac_update(rdp->fips_hmac, data, length);
crypto_hmac_update(rdp->fips_hmac, use_count_le, 4);
crypto_hmac_final(rdp->fips_hmac, buf, 20);
rdp->decrypt_use_count++;
if (memcmp(sig, buf, 8))
return FALSE;
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_5714_1 |
crossvul-cpp_data_bad_1180_0 | /*
* utils for libavcodec
* Copyright (c) 2001 Fabrice Bellard
* Copyright (c) 2002-2004 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
*/
/**
* @file
* utils.
*/
#include "config.h"
#include "libavutil/attributes.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/channel_layout.h"
#include "libavutil/crc.h"
#include "libavutil/frame.h"
#include "libavutil/hwcontext.h"
#include "libavutil/internal.h"
#include "libavutil/mathematics.h"
#include "libavutil/mem_internal.h"
#include "libavutil/pixdesc.h"
#include "libavutil/imgutils.h"
#include "libavutil/samplefmt.h"
#include "libavutil/dict.h"
#include "libavutil/thread.h"
#include "avcodec.h"
#include "decode.h"
#include "hwaccel.h"
#include "libavutil/opt.h"
#include "mpegvideo.h"
#include "thread.h"
#include "frame_thread_encoder.h"
#include "internal.h"
#include "raw.h"
#include "bytestream.h"
#include "version.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdatomic.h>
#include <limits.h>
#include <float.h>
#if CONFIG_ICONV
# include <iconv.h>
#endif
#include "libavutil/ffversion.h"
const char av_codec_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
static AVMutex codec_mutex = AV_MUTEX_INITIALIZER;
void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
{
uint8_t **p = ptr;
if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
av_freep(p);
*size = 0;
return;
}
if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1))
memset(*p + min_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
}
void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size)
{
uint8_t **p = ptr;
if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
av_freep(p);
*size = 0;
return;
}
if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1))
memset(*p, 0, min_size + AV_INPUT_BUFFER_PADDING_SIZE);
}
int av_codec_is_encoder(const AVCodec *codec)
{
return codec && (codec->encode_sub || codec->encode2 ||codec->send_frame);
}
int av_codec_is_decoder(const AVCodec *codec)
{
return codec && (codec->decode || codec->receive_frame);
}
int ff_set_dimensions(AVCodecContext *s, int width, int height)
{
int ret = av_image_check_size2(width, height, s->max_pixels, AV_PIX_FMT_NONE, 0, s);
if (ret < 0)
width = height = 0;
s->coded_width = width;
s->coded_height = height;
s->width = AV_CEIL_RSHIFT(width, s->lowres);
s->height = AV_CEIL_RSHIFT(height, s->lowres);
return ret;
}
int ff_set_sar(AVCodecContext *avctx, AVRational sar)
{
int ret = av_image_check_sar(avctx->width, avctx->height, sar);
if (ret < 0) {
av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n",
sar.num, sar.den);
avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
return ret;
} else {
avctx->sample_aspect_ratio = sar;
}
return 0;
}
int ff_side_data_update_matrix_encoding(AVFrame *frame,
enum AVMatrixEncoding matrix_encoding)
{
AVFrameSideData *side_data;
enum AVMatrixEncoding *data;
side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_MATRIXENCODING);
if (!side_data)
side_data = av_frame_new_side_data(frame, AV_FRAME_DATA_MATRIXENCODING,
sizeof(enum AVMatrixEncoding));
if (!side_data)
return AVERROR(ENOMEM);
data = (enum AVMatrixEncoding*)side_data->data;
*data = matrix_encoding;
return 0;
}
void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
int linesize_align[AV_NUM_DATA_POINTERS])
{
int i;
int w_align = 1;
int h_align = 1;
AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt);
if (desc) {
w_align = 1 << desc->log2_chroma_w;
h_align = 1 << desc->log2_chroma_h;
}
switch (s->pix_fmt) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUYV422:
case AV_PIX_FMT_YVYU422:
case AV_PIX_FMT_UYVY422:
case AV_PIX_FMT_YUV422P:
case AV_PIX_FMT_YUV440P:
case AV_PIX_FMT_YUV444P:
case AV_PIX_FMT_GBRP:
case AV_PIX_FMT_GBRAP:
case AV_PIX_FMT_GRAY8:
case AV_PIX_FMT_GRAY16BE:
case AV_PIX_FMT_GRAY16LE:
case AV_PIX_FMT_YUVJ420P:
case AV_PIX_FMT_YUVJ422P:
case AV_PIX_FMT_YUVJ440P:
case AV_PIX_FMT_YUVJ444P:
case AV_PIX_FMT_YUVA420P:
case AV_PIX_FMT_YUVA422P:
case AV_PIX_FMT_YUVA444P:
case AV_PIX_FMT_YUV420P9LE:
case AV_PIX_FMT_YUV420P9BE:
case AV_PIX_FMT_YUV420P10LE:
case AV_PIX_FMT_YUV420P10BE:
case AV_PIX_FMT_YUV420P12LE:
case AV_PIX_FMT_YUV420P12BE:
case AV_PIX_FMT_YUV420P14LE:
case AV_PIX_FMT_YUV420P14BE:
case AV_PIX_FMT_YUV420P16LE:
case AV_PIX_FMT_YUV420P16BE:
case AV_PIX_FMT_YUVA420P9LE:
case AV_PIX_FMT_YUVA420P9BE:
case AV_PIX_FMT_YUVA420P10LE:
case AV_PIX_FMT_YUVA420P10BE:
case AV_PIX_FMT_YUVA420P16LE:
case AV_PIX_FMT_YUVA420P16BE:
case AV_PIX_FMT_YUV422P9LE:
case AV_PIX_FMT_YUV422P9BE:
case AV_PIX_FMT_YUV422P10LE:
case AV_PIX_FMT_YUV422P10BE:
case AV_PIX_FMT_YUV422P12LE:
case AV_PIX_FMT_YUV422P12BE:
case AV_PIX_FMT_YUV422P14LE:
case AV_PIX_FMT_YUV422P14BE:
case AV_PIX_FMT_YUV422P16LE:
case AV_PIX_FMT_YUV422P16BE:
case AV_PIX_FMT_YUVA422P9LE:
case AV_PIX_FMT_YUVA422P9BE:
case AV_PIX_FMT_YUVA422P10LE:
case AV_PIX_FMT_YUVA422P10BE:
case AV_PIX_FMT_YUVA422P12LE:
case AV_PIX_FMT_YUVA422P12BE:
case AV_PIX_FMT_YUVA422P16LE:
case AV_PIX_FMT_YUVA422P16BE:
case AV_PIX_FMT_YUV440P10LE:
case AV_PIX_FMT_YUV440P10BE:
case AV_PIX_FMT_YUV440P12LE:
case AV_PIX_FMT_YUV440P12BE:
case AV_PIX_FMT_YUV444P9LE:
case AV_PIX_FMT_YUV444P9BE:
case AV_PIX_FMT_YUV444P10LE:
case AV_PIX_FMT_YUV444P10BE:
case AV_PIX_FMT_YUV444P12LE:
case AV_PIX_FMT_YUV444P12BE:
case AV_PIX_FMT_YUV444P14LE:
case AV_PIX_FMT_YUV444P14BE:
case AV_PIX_FMT_YUV444P16LE:
case AV_PIX_FMT_YUV444P16BE:
case AV_PIX_FMT_YUVA444P9LE:
case AV_PIX_FMT_YUVA444P9BE:
case AV_PIX_FMT_YUVA444P10LE:
case AV_PIX_FMT_YUVA444P10BE:
case AV_PIX_FMT_YUVA444P12LE:
case AV_PIX_FMT_YUVA444P12BE:
case AV_PIX_FMT_YUVA444P16LE:
case AV_PIX_FMT_YUVA444P16BE:
case AV_PIX_FMT_GBRP9LE:
case AV_PIX_FMT_GBRP9BE:
case AV_PIX_FMT_GBRP10LE:
case AV_PIX_FMT_GBRP10BE:
case AV_PIX_FMT_GBRP12LE:
case AV_PIX_FMT_GBRP12BE:
case AV_PIX_FMT_GBRP14LE:
case AV_PIX_FMT_GBRP14BE:
case AV_PIX_FMT_GBRP16LE:
case AV_PIX_FMT_GBRP16BE:
case AV_PIX_FMT_GBRAP12LE:
case AV_PIX_FMT_GBRAP12BE:
case AV_PIX_FMT_GBRAP16LE:
case AV_PIX_FMT_GBRAP16BE:
w_align = 16; //FIXME assume 16 pixel per macroblock
h_align = 16 * 2; // interlaced needs 2 macroblocks height
break;
case AV_PIX_FMT_YUV411P:
case AV_PIX_FMT_YUVJ411P:
case AV_PIX_FMT_UYYVYY411:
w_align = 32;
h_align = 16 * 2;
break;
case AV_PIX_FMT_YUV410P:
if (s->codec_id == AV_CODEC_ID_SVQ1) {
w_align = 64;
h_align = 64;
}
break;
case AV_PIX_FMT_RGB555:
if (s->codec_id == AV_CODEC_ID_RPZA) {
w_align = 4;
h_align = 4;
}
if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
w_align = 8;
h_align = 8;
}
break;
case AV_PIX_FMT_PAL8:
case AV_PIX_FMT_BGR8:
case AV_PIX_FMT_RGB8:
if (s->codec_id == AV_CODEC_ID_SMC ||
s->codec_id == AV_CODEC_ID_CINEPAK) {
w_align = 4;
h_align = 4;
}
if (s->codec_id == AV_CODEC_ID_JV ||
s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
w_align = 8;
h_align = 8;
}
break;
case AV_PIX_FMT_BGR24:
if ((s->codec_id == AV_CODEC_ID_MSZH) ||
(s->codec_id == AV_CODEC_ID_ZLIB)) {
w_align = 4;
h_align = 4;
}
break;
case AV_PIX_FMT_RGB24:
if (s->codec_id == AV_CODEC_ID_CINEPAK) {
w_align = 4;
h_align = 4;
}
break;
default:
break;
}
if (s->codec_id == AV_CODEC_ID_IFF_ILBM) {
w_align = FFMAX(w_align, 8);
}
*width = FFALIGN(*width, w_align);
*height = FFALIGN(*height, h_align);
if (s->codec_id == AV_CODEC_ID_H264 || s->lowres ||
s->codec_id == AV_CODEC_ID_VP5 || s->codec_id == AV_CODEC_ID_VP6 ||
s->codec_id == AV_CODEC_ID_VP6F || s->codec_id == AV_CODEC_ID_VP6A
) {
// some of the optimized chroma MC reads one line too much
// which is also done in mpeg decoders with lowres > 0
*height += 2;
// H.264 uses edge emulation for out of frame motion vectors, for this
// it requires a temporary area large enough to hold a 21x21 block,
// increasing witdth ensure that the temporary area is large enough,
// the next rounded up width is 32
*width = FFMAX(*width, 32);
}
for (i = 0; i < 4; i++)
linesize_align[i] = STRIDE_ALIGN;
}
void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
int chroma_shift = desc->log2_chroma_w;
int linesize_align[AV_NUM_DATA_POINTERS];
int align;
avcodec_align_dimensions2(s, width, height, linesize_align);
align = FFMAX(linesize_align[0], linesize_align[3]);
linesize_align[1] <<= chroma_shift;
linesize_align[2] <<= chroma_shift;
align = FFMAX3(align, linesize_align[1], linesize_align[2]);
*width = FFALIGN(*width, align);
}
int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos)
{
if (pos <= AVCHROMA_LOC_UNSPECIFIED || pos >= AVCHROMA_LOC_NB)
return AVERROR(EINVAL);
pos--;
*xpos = (pos&1) * 128;
*ypos = ((pos>>1)^(pos<4)) * 128;
return 0;
}
enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos)
{
int pos, xout, yout;
for (pos = AVCHROMA_LOC_UNSPECIFIED + 1; pos < AVCHROMA_LOC_NB; pos++) {
if (avcodec_enum_to_chroma_pos(&xout, &yout, pos) == 0 && xout == xpos && yout == ypos)
return pos;
}
return AVCHROMA_LOC_UNSPECIFIED;
}
int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
enum AVSampleFormat sample_fmt, const uint8_t *buf,
int buf_size, int align)
{
int ch, planar, needed_size, ret = 0;
needed_size = av_samples_get_buffer_size(NULL, nb_channels,
frame->nb_samples, sample_fmt,
align);
if (buf_size < needed_size)
return AVERROR(EINVAL);
planar = av_sample_fmt_is_planar(sample_fmt);
if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
if (!(frame->extended_data = av_mallocz_array(nb_channels,
sizeof(*frame->extended_data))))
return AVERROR(ENOMEM);
} else {
frame->extended_data = frame->data;
}
if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
(uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples,
sample_fmt, align)) < 0) {
if (frame->extended_data != frame->data)
av_freep(&frame->extended_data);
return ret;
}
if (frame->extended_data != frame->data) {
for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
frame->data[ch] = frame->extended_data[ch];
}
return ret;
}
void ff_color_frame(AVFrame *frame, const int c[4])
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
int p, y, x;
av_assert0(desc->flags & AV_PIX_FMT_FLAG_PLANAR);
for (p = 0; p<desc->nb_components; p++) {
uint8_t *dst = frame->data[p];
int is_chroma = p == 1 || p == 2;
int bytes = is_chroma ? AV_CEIL_RSHIFT(frame->width, desc->log2_chroma_w) : frame->width;
int height = is_chroma ? AV_CEIL_RSHIFT(frame->height, desc->log2_chroma_h) : frame->height;
for (y = 0; y < height; y++) {
if (desc->comp[0].depth >= 9) {
for (x = 0; x<bytes; x++)
((uint16_t*)dst)[x] = c[p];
}else
memset(dst, c[p], bytes);
dst += frame->linesize[p];
}
}
}
int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
{
int i;
for (i = 0; i < count; i++) {
int r = func(c, (char *)arg + i * size);
if (ret)
ret[i] = r;
}
emms_c();
return 0;
}
int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
{
int i;
for (i = 0; i < count; i++) {
int r = func(c, arg, i, 0);
if (ret)
ret[i] = r;
}
emms_c();
return 0;
}
enum AVPixelFormat avpriv_find_pix_fmt(const PixelFormatTag *tags,
unsigned int fourcc)
{
while (tags->pix_fmt >= 0) {
if (tags->fourcc == fourcc)
return tags->pix_fmt;
tags++;
}
return AV_PIX_FMT_NONE;
}
#if FF_API_CODEC_GET_SET
MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase)
MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor)
MAKE_ACCESSORS(AVCodecContext, codec, int, lowres)
MAKE_ACCESSORS(AVCodecContext, codec, int, seek_preroll)
MAKE_ACCESSORS(AVCodecContext, codec, uint16_t*, chroma_intra_matrix)
unsigned av_codec_get_codec_properties(const AVCodecContext *codec)
{
return codec->properties;
}
int av_codec_get_max_lowres(const AVCodec *codec)
{
return codec->max_lowres;
}
#endif
int avpriv_codec_get_cap_skip_frame_fill_param(const AVCodec *codec){
return !!(codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM);
}
static int64_t get_bit_rate(AVCodecContext *ctx)
{
int64_t bit_rate;
int bits_per_sample;
switch (ctx->codec_type) {
case AVMEDIA_TYPE_VIDEO:
case AVMEDIA_TYPE_DATA:
case AVMEDIA_TYPE_SUBTITLE:
case AVMEDIA_TYPE_ATTACHMENT:
bit_rate = ctx->bit_rate;
break;
case AVMEDIA_TYPE_AUDIO:
bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
bit_rate = bits_per_sample ? ctx->sample_rate * (int64_t)ctx->channels * bits_per_sample : ctx->bit_rate;
break;
default:
bit_rate = 0;
break;
}
return bit_rate;
}
static void ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec)
{
if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init)
ff_mutex_lock(&codec_mutex);
}
static void ff_unlock_avcodec(const AVCodec *codec)
{
if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init)
ff_mutex_unlock(&codec_mutex);
}
int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
{
int ret = 0;
ff_unlock_avcodec(codec);
ret = avcodec_open2(avctx, codec, options);
ff_lock_avcodec(avctx, codec);
return ret;
}
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
{
int ret = 0;
int codec_init_ok = 0;
AVDictionary *tmp = NULL;
const AVPixFmtDescriptor *pixdesc;
if (avcodec_is_open(avctx))
return 0;
if ((!codec && !avctx->codec)) {
av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
return AVERROR(EINVAL);
}
if ((codec && avctx->codec && codec != avctx->codec)) {
av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
"but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
return AVERROR(EINVAL);
}
if (!codec)
codec = avctx->codec;
if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
return AVERROR(EINVAL);
if (options)
av_dict_copy(&tmp, *options, 0);
ff_lock_avcodec(avctx, codec);
avctx->internal = av_mallocz(sizeof(*avctx->internal));
if (!avctx->internal) {
ret = AVERROR(ENOMEM);
goto end;
}
avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
if (!avctx->internal->pool) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->to_free = av_frame_alloc();
if (!avctx->internal->to_free) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->compat_decode_frame = av_frame_alloc();
if (!avctx->internal->compat_decode_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->buffer_frame = av_frame_alloc();
if (!avctx->internal->buffer_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->buffer_pkt = av_packet_alloc();
if (!avctx->internal->buffer_pkt) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->ds.in_pkt = av_packet_alloc();
if (!avctx->internal->ds.in_pkt) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->last_pkt_props = av_packet_alloc();
if (!avctx->internal->last_pkt_props) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->skip_samples_multiplier = 1;
if (codec->priv_data_size > 0) {
if (!avctx->priv_data) {
avctx->priv_data = av_mallocz(codec->priv_data_size);
if (!avctx->priv_data) {
ret = AVERROR(ENOMEM);
goto end;
}
if (codec->priv_class) {
*(const AVClass **)avctx->priv_data = codec->priv_class;
av_opt_set_defaults(avctx->priv_data);
}
}
if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
goto free_and_end;
} else {
avctx->priv_data = NULL;
}
if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
goto free_and_end;
if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) {
av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist);
ret = AVERROR(EINVAL);
goto free_and_end;
}
// only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions
if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height &&
(avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) {
if (avctx->coded_width && avctx->coded_height)
ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
else if (avctx->width && avctx->height)
ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
if (ret < 0)
goto free_and_end;
}
if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
&& ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0
|| av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) {
av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
ff_set_dimensions(avctx, 0, 0);
}
if (avctx->width > 0 && avctx->height > 0) {
if (av_image_check_sar(avctx->width, avctx->height,
avctx->sample_aspect_ratio) < 0) {
av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
avctx->sample_aspect_ratio.num,
avctx->sample_aspect_ratio.den);
avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
}
}
/* if the decoder init function was already called previously,
* free the already allocated subtitle_header before overwriting it */
if (av_codec_is_decoder(codec))
av_freep(&avctx->subtitle_header);
if (avctx->channels > FF_SANE_NB_CHANNELS) {
av_log(avctx, AV_LOG_ERROR, "Too many channels: %d\n", avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->codec = codec;
if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
avctx->codec_id == AV_CODEC_ID_NONE) {
avctx->codec_type = codec->type;
avctx->codec_id = codec->id;
}
if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
&& avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->frame_number = 0;
avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) &&
avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
AVCodec *codec2;
av_log(avctx, AV_LOG_ERROR,
"The %s '%s' is experimental but experimental codecs are not enabled, "
"add '-strict %d' if you want to use it.\n",
codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL))
av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
codec_string, codec2->name);
ret = AVERROR_EXPERIMENTAL;
goto free_and_end;
}
if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
(!avctx->time_base.num || !avctx->time_base.den)) {
avctx->time_base.num = 1;
avctx->time_base.den = avctx->sample_rate;
}
if (!HAVE_THREADS)
av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) {
ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem
ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
ff_lock_avcodec(avctx, codec);
if (ret < 0)
goto free_and_end;
}
if (av_codec_is_decoder(avctx->codec)) {
ret = ff_decode_bsfs_init(avctx);
if (ret < 0)
goto free_and_end;
}
if (HAVE_THREADS
&& !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {
ret = ff_thread_init(avctx);
if (ret < 0) {
goto free_and_end;
}
}
if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS))
avctx->thread_count = 1;
if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
avctx->codec->max_lowres);
avctx->lowres = avctx->codec->max_lowres;
}
if (av_codec_is_encoder(avctx->codec)) {
int i;
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
avctx->coded_frame = av_frame_alloc();
if (!avctx->coded_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) {
av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->sample_fmts) {
for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
break;
if (avctx->channels == 1 &&
av_get_planar_sample_fmt(avctx->sample_fmt) ==
av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
avctx->sample_fmt = avctx->codec->sample_fmts[i];
break;
}
}
if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
(char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if (avctx->codec->pix_fmts) {
for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
break;
if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
&& !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
&& avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
(char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
avctx->color_range = AVCOL_RANGE_JPEG;
}
if (avctx->codec->supported_samplerates) {
for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
break;
if (avctx->codec->supported_samplerates[i] == 0) {
av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
avctx->sample_rate);
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if (avctx->sample_rate < 0) {
av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
avctx->sample_rate);
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->channel_layouts) {
if (!avctx->channel_layout) {
av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
} else {
for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
if (avctx->channel_layout == avctx->codec->channel_layouts[i])
break;
if (avctx->codec->channel_layouts[i] == 0) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
}
if (avctx->channel_layout && avctx->channels) {
int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
if (channels != avctx->channels) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_ERROR,
"Channel layout '%s' with %d channels does not match number of specified channels %d\n",
buf, channels, avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
} else if (avctx->channel_layout) {
avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
}
if (avctx->channels < 0) {
av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n",
avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt);
if ( avctx->bits_per_raw_sample < 0
|| (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) {
av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n",
avctx->bits_per_raw_sample, pixdesc->comp[0].depth);
avctx->bits_per_raw_sample = pixdesc->comp[0].depth;
}
if (avctx->width <= 0 || avctx->height <= 0) {
av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
&& avctx->bit_rate>0 && avctx->bit_rate<1000) {
av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate);
}
if (!avctx->rc_initial_buffer_occupancy)
avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4;
if (avctx->ticks_per_frame && avctx->time_base.num &&
avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
av_log(avctx, AV_LOG_ERROR,
"ticks_per_frame %d too large for the timebase %d/%d.",
avctx->ticks_per_frame,
avctx->time_base.num,
avctx->time_base.den);
goto free_and_end;
}
if (avctx->hw_frames_ctx) {
AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
if (frames_ctx->format != avctx->pix_fmt) {
av_log(avctx, AV_LOG_ERROR,
"Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE &&
avctx->sw_pix_fmt != frames_ctx->sw_format) {
av_log(avctx, AV_LOG_ERROR,
"Mismatching AVCodecContext.sw_pix_fmt (%s) "
"and AVHWFramesContext.sw_format (%s)\n",
av_get_pix_fmt_name(avctx->sw_pix_fmt),
av_get_pix_fmt_name(frames_ctx->sw_format));
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->sw_pix_fmt = frames_ctx->sw_format;
}
}
avctx->pts_correction_num_faulty_pts =
avctx->pts_correction_num_faulty_dts = 0;
avctx->pts_correction_last_pts =
avctx->pts_correction_last_dts = INT64_MIN;
if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
&& avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
av_log(avctx, AV_LOG_WARNING,
"gray decoding requested but not enabled at configuration time\n");
if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)
|| avctx->internal->frame_thread_encoder)) {
ret = avctx->codec->init(avctx);
if (ret < 0) {
goto free_and_end;
}
codec_init_ok = 1;
}
ret=0;
if (av_codec_is_decoder(avctx->codec)) {
if (!avctx->bit_rate)
avctx->bit_rate = get_bit_rate(avctx);
/* validate channel layout from the decoder */
if (avctx->channel_layout) {
int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
if (!avctx->channels)
avctx->channels = channels;
else if (channels != avctx->channels) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_WARNING,
"Channel layout '%s' with %d channels does not match specified number of channels %d: "
"ignoring specified channel layout\n",
buf, channels, avctx->channels);
avctx->channel_layout = 0;
}
}
if (avctx->channels && avctx->channels < 0 ||
avctx->channels > FF_SANE_NB_CHANNELS) {
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->bits_per_coded_sample < 0) {
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->sub_charenc) {
if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
"supported with subtitles codecs\n");
ret = AVERROR(EINVAL);
goto free_and_end;
} else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
"subtitles character encoding will be ignored\n",
avctx->codec_descriptor->name);
avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
} else {
/* input character encoding is set for a text based subtitle
* codec at this point */
if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
#if CONFIG_ICONV
iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
if (cd == (iconv_t)-1) {
ret = AVERROR(errno);
av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
"with input character encoding \"%s\"\n", avctx->sub_charenc);
goto free_and_end;
}
iconv_close(cd);
#else
av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
"conversion needs a libavcodec built with iconv support "
"for this codec\n");
ret = AVERROR(ENOSYS);
goto free_and_end;
#endif
}
}
}
#if FF_API_AVCTX_TIMEBASE
if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
#endif
}
if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) {
av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class);
}
end:
ff_unlock_avcodec(codec);
if (options) {
av_dict_free(options);
*options = tmp;
}
return ret;
free_and_end:
if (avctx->codec &&
(codec_init_ok ||
(avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP)))
avctx->codec->close(avctx);
if (codec->priv_class && codec->priv_data_size)
av_opt_free(avctx->priv_data);
av_opt_free(avctx);
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
av_frame_free(&avctx->coded_frame);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
av_dict_free(&tmp);
av_freep(&avctx->priv_data);
if (avctx->internal) {
av_frame_free(&avctx->internal->to_free);
av_frame_free(&avctx->internal->compat_decode_frame);
av_frame_free(&avctx->internal->buffer_frame);
av_packet_free(&avctx->internal->buffer_pkt);
av_packet_free(&avctx->internal->last_pkt_props);
av_packet_free(&avctx->internal->ds.in_pkt);
ff_decode_bsfs_uninit(avctx);
av_freep(&avctx->internal->pool);
}
av_freep(&avctx->internal);
avctx->codec = NULL;
goto end;
}
void avsubtitle_free(AVSubtitle *sub)
{
int i;
for (i = 0; i < sub->num_rects; i++) {
av_freep(&sub->rects[i]->data[0]);
av_freep(&sub->rects[i]->data[1]);
av_freep(&sub->rects[i]->data[2]);
av_freep(&sub->rects[i]->data[3]);
av_freep(&sub->rects[i]->text);
av_freep(&sub->rects[i]->ass);
av_freep(&sub->rects[i]);
}
av_freep(&sub->rects);
memset(sub, 0, sizeof(*sub));
}
av_cold int avcodec_close(AVCodecContext *avctx)
{
int i;
if (!avctx)
return 0;
if (avcodec_is_open(avctx)) {
FramePool *pool = avctx->internal->pool;
if (CONFIG_FRAME_THREAD_ENCODER &&
avctx->internal->frame_thread_encoder && avctx->thread_count > 1) {
ff_frame_thread_encoder_free(avctx);
}
if (HAVE_THREADS && avctx->internal->thread_ctx)
ff_thread_free(avctx);
if (avctx->codec && avctx->codec->close)
avctx->codec->close(avctx);
avctx->internal->byte_buffer_size = 0;
av_freep(&avctx->internal->byte_buffer);
av_frame_free(&avctx->internal->to_free);
av_frame_free(&avctx->internal->compat_decode_frame);
av_frame_free(&avctx->internal->buffer_frame);
av_packet_free(&avctx->internal->buffer_pkt);
av_packet_free(&avctx->internal->last_pkt_props);
av_packet_free(&avctx->internal->ds.in_pkt);
for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
av_buffer_pool_uninit(&pool->pools[i]);
av_freep(&avctx->internal->pool);
if (avctx->hwaccel && avctx->hwaccel->uninit)
avctx->hwaccel->uninit(avctx);
av_freep(&avctx->internal->hwaccel_priv_data);
ff_decode_bsfs_uninit(avctx);
av_freep(&avctx->internal);
}
for (i = 0; i < avctx->nb_coded_side_data; i++)
av_freep(&avctx->coded_side_data[i].data);
av_freep(&avctx->coded_side_data);
avctx->nb_coded_side_data = 0;
av_buffer_unref(&avctx->hw_frames_ctx);
av_buffer_unref(&avctx->hw_device_ctx);
if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
av_opt_free(avctx->priv_data);
av_opt_free(avctx);
av_freep(&avctx->priv_data);
if (av_codec_is_encoder(avctx->codec)) {
av_freep(&avctx->extradata);
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
av_frame_free(&avctx->coded_frame);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
}
avctx->codec = NULL;
avctx->active_thread_type = 0;
return 0;
}
const char *avcodec_get_name(enum AVCodecID id)
{
const AVCodecDescriptor *cd;
AVCodec *codec;
if (id == AV_CODEC_ID_NONE)
return "none";
cd = avcodec_descriptor_get(id);
if (cd)
return cd->name;
av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
codec = avcodec_find_decoder(id);
if (codec)
return codec->name;
codec = avcodec_find_encoder(id);
if (codec)
return codec->name;
return "unknown_codec";
}
size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
{
int i, len, ret = 0;
#define TAG_PRINT(x) \
(((x) >= '0' && (x) <= '9') || \
((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') || \
((x) == '.' || (x) == ' ' || (x) == '-' || (x) == '_'))
for (i = 0; i < 4; i++) {
len = snprintf(buf, buf_size,
TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
buf += len;
buf_size = buf_size > len ? buf_size - len : 0;
ret += len;
codec_tag >>= 8;
}
return ret;
}
void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
{
const char *codec_type;
const char *codec_name;
const char *profile = NULL;
int64_t bitrate;
int new_line = 0;
AVRational display_aspect_ratio;
const char *separator = enc->dump_separator ? (const char *)enc->dump_separator : ", ";
if (!buf || buf_size <= 0)
return;
codec_type = av_get_media_type_string(enc->codec_type);
codec_name = avcodec_get_name(enc->codec_id);
profile = avcodec_profile_name(enc->codec_id, enc->profile);
snprintf(buf, buf_size, "%s: %s", codec_type ? codec_type : "unknown",
codec_name);
buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
if (enc->codec && strcmp(enc->codec->name, codec_name))
snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", enc->codec->name);
if (profile)
snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
if ( enc->codec_type == AVMEDIA_TYPE_VIDEO
&& av_log_get_level() >= AV_LOG_VERBOSE
&& enc->refs)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %d reference frame%s",
enc->refs, enc->refs > 1 ? "s" : "");
if (enc->codec_tag)
snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s / 0x%04X)",
av_fourcc2str(enc->codec_tag), enc->codec_tag);
switch (enc->codec_type) {
case AVMEDIA_TYPE_VIDEO:
{
char detail[256] = "(";
av_strlcat(buf, separator, buf_size);
snprintf(buf + strlen(buf), buf_size - strlen(buf),
"%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" :
av_get_pix_fmt_name(enc->pix_fmt));
if (enc->bits_per_raw_sample && enc->pix_fmt != AV_PIX_FMT_NONE &&
enc->bits_per_raw_sample < av_pix_fmt_desc_get(enc->pix_fmt)->comp[0].depth)
av_strlcatf(detail, sizeof(detail), "%d bpc, ", enc->bits_per_raw_sample);
if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
av_strlcatf(detail, sizeof(detail), "%s, ",
av_color_range_name(enc->color_range));
if (enc->colorspace != AVCOL_SPC_UNSPECIFIED ||
enc->color_primaries != AVCOL_PRI_UNSPECIFIED ||
enc->color_trc != AVCOL_TRC_UNSPECIFIED) {
if (enc->colorspace != (int)enc->color_primaries ||
enc->colorspace != (int)enc->color_trc) {
new_line = 1;
av_strlcatf(detail, sizeof(detail), "%s/%s/%s, ",
av_color_space_name(enc->colorspace),
av_color_primaries_name(enc->color_primaries),
av_color_transfer_name(enc->color_trc));
} else
av_strlcatf(detail, sizeof(detail), "%s, ",
av_get_colorspace_name(enc->colorspace));
}
if (enc->field_order != AV_FIELD_UNKNOWN) {
const char *field_order = "progressive";
if (enc->field_order == AV_FIELD_TT)
field_order = "top first";
else if (enc->field_order == AV_FIELD_BB)
field_order = "bottom first";
else if (enc->field_order == AV_FIELD_TB)
field_order = "top coded first (swapped)";
else if (enc->field_order == AV_FIELD_BT)
field_order = "bottom coded first (swapped)";
av_strlcatf(detail, sizeof(detail), "%s, ", field_order);
}
if (av_log_get_level() >= AV_LOG_VERBOSE &&
enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
av_strlcatf(detail, sizeof(detail), "%s, ",
av_chroma_location_name(enc->chroma_sample_location));
if (strlen(detail) > 1) {
detail[strlen(detail) - 2] = 0;
av_strlcatf(buf, buf_size, "%s)", detail);
}
}
if (enc->width) {
av_strlcat(buf, new_line ? separator : ", ", buf_size);
snprintf(buf + strlen(buf), buf_size - strlen(buf),
"%dx%d",
enc->width, enc->height);
if (av_log_get_level() >= AV_LOG_VERBOSE &&
(enc->width != enc->coded_width ||
enc->height != enc->coded_height))
snprintf(buf + strlen(buf), buf_size - strlen(buf),
" (%dx%d)", enc->coded_width, enc->coded_height);
if (enc->sample_aspect_ratio.num) {
av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
enc->width * (int64_t)enc->sample_aspect_ratio.num,
enc->height * (int64_t)enc->sample_aspect_ratio.den,
1024 * 1024);
snprintf(buf + strlen(buf), buf_size - strlen(buf),
" [SAR %d:%d DAR %d:%d]",
enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
display_aspect_ratio.num, display_aspect_ratio.den);
}
if (av_log_get_level() >= AV_LOG_DEBUG) {
int g = av_gcd(enc->time_base.num, enc->time_base.den);
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %d/%d",
enc->time_base.num / g, enc->time_base.den / g);
}
}
if (encode) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", q=%d-%d", enc->qmin, enc->qmax);
} else {
if (enc->properties & FF_CODEC_PROPERTY_CLOSED_CAPTIONS)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", Closed Captions");
if (enc->properties & FF_CODEC_PROPERTY_LOSSLESS)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", lossless");
}
break;
case AVMEDIA_TYPE_AUDIO:
av_strlcat(buf, separator, buf_size);
if (enc->sample_rate) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
"%d Hz, ", enc->sample_rate);
}
av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %s", av_get_sample_fmt_name(enc->sample_fmt));
}
if ( enc->bits_per_raw_sample > 0
&& enc->bits_per_raw_sample != av_get_bytes_per_sample(enc->sample_fmt) * 8)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
" (%d bit)", enc->bits_per_raw_sample);
if (av_log_get_level() >= AV_LOG_VERBOSE) {
if (enc->initial_padding)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", delay %d", enc->initial_padding);
if (enc->trailing_padding)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", padding %d", enc->trailing_padding);
}
break;
case AVMEDIA_TYPE_DATA:
if (av_log_get_level() >= AV_LOG_DEBUG) {
int g = av_gcd(enc->time_base.num, enc->time_base.den);
if (g)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %d/%d",
enc->time_base.num / g, enc->time_base.den / g);
}
break;
case AVMEDIA_TYPE_SUBTITLE:
if (enc->width)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %dx%d", enc->width, enc->height);
break;
default:
return;
}
if (encode) {
if (enc->flags & AV_CODEC_FLAG_PASS1)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", pass 1");
if (enc->flags & AV_CODEC_FLAG_PASS2)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", pass 2");
}
bitrate = get_bit_rate(enc);
if (bitrate != 0) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %"PRId64" kb/s", bitrate / 1000);
} else if (enc->rc_max_rate > 0) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", max. %"PRId64" kb/s", enc->rc_max_rate / 1000);
}
}
const char *av_get_profile_name(const AVCodec *codec, int profile)
{
const AVProfile *p;
if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
return NULL;
for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
if (p->profile == profile)
return p->name;
return NULL;
}
const char *avcodec_profile_name(enum AVCodecID codec_id, int profile)
{
const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
const AVProfile *p;
if (profile == FF_PROFILE_UNKNOWN || !desc || !desc->profiles)
return NULL;
for (p = desc->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
if (p->profile == profile)
return p->name;
return NULL;
}
unsigned avcodec_version(void)
{
av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563);
av_assert0(AV_CODEC_ID_ADPCM_G722==69660);
av_assert0(AV_CODEC_ID_SRT==94216);
av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
return LIBAVCODEC_VERSION_INT;
}
const char *avcodec_configuration(void)
{
return FFMPEG_CONFIGURATION;
}
const char *avcodec_license(void)
{
#define LICENSE_PREFIX "libavcodec license: "
return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
}
int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
{
switch (codec_id) {
case AV_CODEC_ID_8SVX_EXP:
case AV_CODEC_ID_8SVX_FIB:
case AV_CODEC_ID_ADPCM_CT:
case AV_CODEC_ID_ADPCM_IMA_APC:
case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
case AV_CODEC_ID_ADPCM_IMA_OKI:
case AV_CODEC_ID_ADPCM_IMA_WS:
case AV_CODEC_ID_ADPCM_G722:
case AV_CODEC_ID_ADPCM_YAMAHA:
case AV_CODEC_ID_ADPCM_AICA:
return 4;
case AV_CODEC_ID_DSD_LSBF:
case AV_CODEC_ID_DSD_MSBF:
case AV_CODEC_ID_DSD_LSBF_PLANAR:
case AV_CODEC_ID_DSD_MSBF_PLANAR:
case AV_CODEC_ID_PCM_ALAW:
case AV_CODEC_ID_PCM_MULAW:
case AV_CODEC_ID_PCM_VIDC:
case AV_CODEC_ID_PCM_S8:
case AV_CODEC_ID_PCM_S8_PLANAR:
case AV_CODEC_ID_PCM_U8:
case AV_CODEC_ID_PCM_ZORK:
case AV_CODEC_ID_SDX2_DPCM:
return 8;
case AV_CODEC_ID_PCM_S16BE:
case AV_CODEC_ID_PCM_S16BE_PLANAR:
case AV_CODEC_ID_PCM_S16LE:
case AV_CODEC_ID_PCM_S16LE_PLANAR:
case AV_CODEC_ID_PCM_U16BE:
case AV_CODEC_ID_PCM_U16LE:
return 16;
case AV_CODEC_ID_PCM_S24DAUD:
case AV_CODEC_ID_PCM_S24BE:
case AV_CODEC_ID_PCM_S24LE:
case AV_CODEC_ID_PCM_S24LE_PLANAR:
case AV_CODEC_ID_PCM_U24BE:
case AV_CODEC_ID_PCM_U24LE:
return 24;
case AV_CODEC_ID_PCM_S32BE:
case AV_CODEC_ID_PCM_S32LE:
case AV_CODEC_ID_PCM_S32LE_PLANAR:
case AV_CODEC_ID_PCM_U32BE:
case AV_CODEC_ID_PCM_U32LE:
case AV_CODEC_ID_PCM_F32BE:
case AV_CODEC_ID_PCM_F32LE:
case AV_CODEC_ID_PCM_F24LE:
case AV_CODEC_ID_PCM_F16LE:
return 32;
case AV_CODEC_ID_PCM_F64BE:
case AV_CODEC_ID_PCM_F64LE:
case AV_CODEC_ID_PCM_S64BE:
case AV_CODEC_ID_PCM_S64LE:
return 64;
default:
return 0;
}
}
enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
{
static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = {
[AV_SAMPLE_FMT_U8 ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 },
[AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
[AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
[AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
[AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
[AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 },
[AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
[AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
[AV_SAMPLE_FMT_S64P] = { AV_CODEC_ID_PCM_S64LE, AV_CODEC_ID_PCM_S64BE },
[AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
[AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
};
if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
return AV_CODEC_ID_NONE;
if (be < 0 || be > 1)
be = AV_NE(1, 0);
return map[fmt][be];
}
int av_get_bits_per_sample(enum AVCodecID codec_id)
{
switch (codec_id) {
case AV_CODEC_ID_ADPCM_SBPRO_2:
return 2;
case AV_CODEC_ID_ADPCM_SBPRO_3:
return 3;
case AV_CODEC_ID_ADPCM_SBPRO_4:
case AV_CODEC_ID_ADPCM_IMA_WAV:
case AV_CODEC_ID_ADPCM_IMA_QT:
case AV_CODEC_ID_ADPCM_SWF:
case AV_CODEC_ID_ADPCM_MS:
return 4;
default:
return av_get_exact_bits_per_sample(codec_id);
}
}
static int get_audio_frame_duration(enum AVCodecID id, int sr, int ch, int ba,
uint32_t tag, int bits_per_coded_sample, int64_t bitrate,
uint8_t * extradata, int frame_size, int frame_bytes)
{
int bps = av_get_exact_bits_per_sample(id);
int framecount = (ba > 0 && frame_bytes / ba > 0) ? frame_bytes / ba : 1;
/* codecs with an exact constant bits per sample */
if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
return (frame_bytes * 8LL) / (bps * ch);
bps = bits_per_coded_sample;
/* codecs with a fixed packet duration */
switch (id) {
case AV_CODEC_ID_ADPCM_ADX: return 32;
case AV_CODEC_ID_ADPCM_IMA_QT: return 64;
case AV_CODEC_ID_ADPCM_EA_XAS: return 128;
case AV_CODEC_ID_AMR_NB:
case AV_CODEC_ID_EVRC:
case AV_CODEC_ID_GSM:
case AV_CODEC_ID_QCELP:
case AV_CODEC_ID_RA_288: return 160;
case AV_CODEC_ID_AMR_WB:
case AV_CODEC_ID_GSM_MS: return 320;
case AV_CODEC_ID_MP1: return 384;
case AV_CODEC_ID_ATRAC1: return 512;
case AV_CODEC_ID_ATRAC9:
case AV_CODEC_ID_ATRAC3: return 1024 * framecount;
case AV_CODEC_ID_ATRAC3P: return 2048;
case AV_CODEC_ID_MP2:
case AV_CODEC_ID_MUSEPACK7: return 1152;
case AV_CODEC_ID_AC3: return 1536;
}
if (sr > 0) {
/* calc from sample rate */
if (id == AV_CODEC_ID_TTA)
return 256 * sr / 245;
else if (id == AV_CODEC_ID_DST)
return 588 * sr / 44100;
if (ch > 0) {
/* calc from sample rate and channels */
if (id == AV_CODEC_ID_BINKAUDIO_DCT)
return (480 << (sr / 22050)) / ch;
}
if (id == AV_CODEC_ID_MP3)
return sr <= 24000 ? 576 : 1152;
}
if (ba > 0) {
/* calc from block_align */
if (id == AV_CODEC_ID_SIPR) {
switch (ba) {
case 20: return 160;
case 19: return 144;
case 29: return 288;
case 37: return 480;
}
} else if (id == AV_CODEC_ID_ILBC) {
switch (ba) {
case 38: return 160;
case 50: return 240;
}
}
}
if (frame_bytes > 0) {
/* calc from frame_bytes only */
if (id == AV_CODEC_ID_TRUESPEECH)
return 240 * (frame_bytes / 32);
if (id == AV_CODEC_ID_NELLYMOSER)
return 256 * (frame_bytes / 64);
if (id == AV_CODEC_ID_RA_144)
return 160 * (frame_bytes / 20);
if (bps > 0) {
/* calc from frame_bytes and bits_per_coded_sample */
if (id == AV_CODEC_ID_ADPCM_G726 || id == AV_CODEC_ID_ADPCM_G726LE)
return frame_bytes * 8 / bps;
}
if (ch > 0 && ch < INT_MAX/16) {
/* calc from frame_bytes and channels */
switch (id) {
case AV_CODEC_ID_ADPCM_AFC:
return frame_bytes / (9 * ch) * 16;
case AV_CODEC_ID_ADPCM_PSX:
case AV_CODEC_ID_ADPCM_DTK:
return frame_bytes / (16 * ch) * 28;
case AV_CODEC_ID_ADPCM_4XM:
case AV_CODEC_ID_ADPCM_IMA_DAT4:
case AV_CODEC_ID_ADPCM_IMA_ISS:
return (frame_bytes - 4 * ch) * 2 / ch;
case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
return (frame_bytes - 4) * 2 / ch;
case AV_CODEC_ID_ADPCM_IMA_AMV:
return (frame_bytes - 8) * 2 / ch;
case AV_CODEC_ID_ADPCM_THP:
case AV_CODEC_ID_ADPCM_THP_LE:
if (extradata)
return frame_bytes * 14 / (8 * ch);
break;
case AV_CODEC_ID_ADPCM_XA:
return (frame_bytes / 128) * 224 / ch;
case AV_CODEC_ID_INTERPLAY_DPCM:
return (frame_bytes - 6 - ch) / ch;
case AV_CODEC_ID_ROQ_DPCM:
return (frame_bytes - 8) / ch;
case AV_CODEC_ID_XAN_DPCM:
return (frame_bytes - 2 * ch) / ch;
case AV_CODEC_ID_MACE3:
return 3 * frame_bytes / ch;
case AV_CODEC_ID_MACE6:
return 6 * frame_bytes / ch;
case AV_CODEC_ID_PCM_LXF:
return 2 * (frame_bytes / (5 * ch));
case AV_CODEC_ID_IAC:
case AV_CODEC_ID_IMC:
return 4 * frame_bytes / ch;
}
if (tag) {
/* calc from frame_bytes, channels, and codec_tag */
if (id == AV_CODEC_ID_SOL_DPCM) {
if (tag == 3)
return frame_bytes / ch;
else
return frame_bytes * 2 / ch;
}
}
if (ba > 0) {
/* calc from frame_bytes, channels, and block_align */
int blocks = frame_bytes / ba;
switch (id) {
case AV_CODEC_ID_ADPCM_IMA_WAV:
if (bps < 2 || bps > 5)
return 0;
return blocks * (1 + (ba - 4 * ch) / (bps * ch) * 8);
case AV_CODEC_ID_ADPCM_IMA_DK3:
return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
case AV_CODEC_ID_ADPCM_IMA_DK4:
return blocks * (1 + (ba - 4 * ch) * 2 / ch);
case AV_CODEC_ID_ADPCM_IMA_RAD:
return blocks * ((ba - 4 * ch) * 2 / ch);
case AV_CODEC_ID_ADPCM_MS:
return blocks * (2 + (ba - 7 * ch) * 2 / ch);
case AV_CODEC_ID_ADPCM_MTAF:
return blocks * (ba - 16) * 2 / ch;
}
}
if (bps > 0) {
/* calc from frame_bytes, channels, and bits_per_coded_sample */
switch (id) {
case AV_CODEC_ID_PCM_DVD:
if(bps<4 || frame_bytes<3)
return 0;
return 2 * ((frame_bytes - 3) / ((bps * 2 / 8) * ch));
case AV_CODEC_ID_PCM_BLURAY:
if(bps<4 || frame_bytes<4)
return 0;
return (frame_bytes - 4) / ((FFALIGN(ch, 2) * bps) / 8);
case AV_CODEC_ID_S302M:
return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
}
}
}
}
/* Fall back on using frame_size */
if (frame_size > 1 && frame_bytes)
return frame_size;
//For WMA we currently have no other means to calculate duration thus we
//do it here by assuming CBR, which is true for all known cases.
if (bitrate > 0 && frame_bytes > 0 && sr > 0 && ba > 1) {
if (id == AV_CODEC_ID_WMAV1 || id == AV_CODEC_ID_WMAV2)
return (frame_bytes * 8LL * sr) / bitrate;
}
return 0;
}
int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
{
return get_audio_frame_duration(avctx->codec_id, avctx->sample_rate,
avctx->channels, avctx->block_align,
avctx->codec_tag, avctx->bits_per_coded_sample,
avctx->bit_rate, avctx->extradata, avctx->frame_size,
frame_bytes);
}
int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes)
{
return get_audio_frame_duration(par->codec_id, par->sample_rate,
par->channels, par->block_align,
par->codec_tag, par->bits_per_coded_sample,
par->bit_rate, par->extradata, par->frame_size,
frame_bytes);
}
#if !HAVE_THREADS
int ff_thread_init(AVCodecContext *s)
{
return -1;
}
#endif
unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
{
unsigned int n = 0;
while (v >= 0xff) {
*s++ = 0xff;
v -= 0xff;
n++;
}
*s = v;
n++;
return n;
}
int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
{
int i;
for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
return i;
}
const AVCodecHWConfig *avcodec_get_hw_config(const AVCodec *codec, int index)
{
int i;
if (!codec->hw_configs || index < 0)
return NULL;
for (i = 0; i <= index; i++)
if (!codec->hw_configs[i])
return NULL;
return &codec->hw_configs[index]->public;
}
#if FF_API_USER_VISIBLE_AVHWACCEL
AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel)
{
return NULL;
}
void av_register_hwaccel(AVHWAccel *hwaccel)
{
}
#endif
#if FF_API_LOCKMGR
int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
{
return 0;
}
#endif
unsigned int avpriv_toupper4(unsigned int x)
{
return av_toupper(x & 0xFF) +
(av_toupper((x >> 8) & 0xFF) << 8) +
(av_toupper((x >> 16) & 0xFF) << 16) +
((unsigned)av_toupper((x >> 24) & 0xFF) << 24);
}
int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
{
int ret;
dst->owner[0] = src->owner[0];
dst->owner[1] = src->owner[1];
ret = av_frame_ref(dst->f, src->f);
if (ret < 0)
return ret;
av_assert0(!dst->progress);
if (src->progress &&
!(dst->progress = av_buffer_ref(src->progress))) {
ff_thread_release_buffer(dst->owner[0], dst);
return AVERROR(ENOMEM);
}
return 0;
}
#if !HAVE_THREADS
enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
{
return ff_get_format(avctx, fmt);
}
int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
{
f->owner[0] = f->owner[1] = avctx;
return ff_get_buffer(avctx, f->f, flags);
}
void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
{
if (f->f)
av_frame_unref(f->f);
}
void ff_thread_finish_setup(AVCodecContext *avctx)
{
}
void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
{
}
void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
{
}
int ff_thread_can_start_frame(AVCodecContext *avctx)
{
return 1;
}
int ff_alloc_entries(AVCodecContext *avctx, int count)
{
return 0;
}
void ff_reset_entries(AVCodecContext *avctx)
{
}
void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift)
{
}
void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n)
{
}
#endif
int avcodec_is_open(AVCodecContext *s)
{
return !!s->internal;
}
int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf)
{
int ret;
char *str;
ret = av_bprint_finalize(buf, &str);
if (ret < 0)
return ret;
if (!av_bprint_is_complete(buf)) {
av_free(str);
return AVERROR(ENOMEM);
}
avctx->extradata = str;
/* Note: the string is NUL terminated (so extradata can be read as a
* string), but the ending character is not accounted in the size (in
* binary formats you are likely not supposed to mux that character). When
* extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
* zeros. */
avctx->extradata_size = buf->len;
return 0;
}
const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p,
const uint8_t *end,
uint32_t *av_restrict state)
{
int i;
av_assert0(p <= end);
if (p >= end)
return end;
for (i = 0; i < 3; i++) {
uint32_t tmp = *state << 8;
*state = tmp + *(p++);
if (tmp == 0x100 || p == end)
return p;
}
while (p < end) {
if (p[-1] > 1 ) p += 3;
else if (p[-2] ) p += 2;
else if (p[-3]|(p[-1]-1)) p++;
else {
p++;
break;
}
}
p = FFMIN(p, end) - 4;
*state = AV_RB32(p);
return p + 4;
}
AVCPBProperties *av_cpb_properties_alloc(size_t *size)
{
AVCPBProperties *props = av_mallocz(sizeof(AVCPBProperties));
if (!props)
return NULL;
if (size)
*size = sizeof(*props);
props->vbv_delay = UINT64_MAX;
return props;
}
AVCPBProperties *ff_add_cpb_side_data(AVCodecContext *avctx)
{
AVPacketSideData *tmp;
AVCPBProperties *props;
size_t size;
props = av_cpb_properties_alloc(&size);
if (!props)
return NULL;
tmp = av_realloc_array(avctx->coded_side_data, avctx->nb_coded_side_data + 1, sizeof(*tmp));
if (!tmp) {
av_freep(&props);
return NULL;
}
avctx->coded_side_data = tmp;
avctx->nb_coded_side_data++;
avctx->coded_side_data[avctx->nb_coded_side_data - 1].type = AV_PKT_DATA_CPB_PROPERTIES;
avctx->coded_side_data[avctx->nb_coded_side_data - 1].data = (uint8_t*)props;
avctx->coded_side_data[avctx->nb_coded_side_data - 1].size = size;
return props;
}
static void codec_parameters_reset(AVCodecParameters *par)
{
av_freep(&par->extradata);
memset(par, 0, sizeof(*par));
par->codec_type = AVMEDIA_TYPE_UNKNOWN;
par->codec_id = AV_CODEC_ID_NONE;
par->format = -1;
par->field_order = AV_FIELD_UNKNOWN;
par->color_range = AVCOL_RANGE_UNSPECIFIED;
par->color_primaries = AVCOL_PRI_UNSPECIFIED;
par->color_trc = AVCOL_TRC_UNSPECIFIED;
par->color_space = AVCOL_SPC_UNSPECIFIED;
par->chroma_location = AVCHROMA_LOC_UNSPECIFIED;
par->sample_aspect_ratio = (AVRational){ 0, 1 };
par->profile = FF_PROFILE_UNKNOWN;
par->level = FF_LEVEL_UNKNOWN;
}
AVCodecParameters *avcodec_parameters_alloc(void)
{
AVCodecParameters *par = av_mallocz(sizeof(*par));
if (!par)
return NULL;
codec_parameters_reset(par);
return par;
}
void avcodec_parameters_free(AVCodecParameters **ppar)
{
AVCodecParameters *par = *ppar;
if (!par)
return;
codec_parameters_reset(par);
av_freep(ppar);
}
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
{
codec_parameters_reset(dst);
memcpy(dst, src, sizeof(*dst));
dst->extradata = NULL;
dst->extradata_size = 0;
if (src->extradata) {
dst->extradata = av_mallocz(src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!dst->extradata)
return AVERROR(ENOMEM);
memcpy(dst->extradata, src->extradata, src->extradata_size);
dst->extradata_size = src->extradata_size;
}
return 0;
}
int avcodec_parameters_from_context(AVCodecParameters *par,
const AVCodecContext *codec)
{
codec_parameters_reset(par);
par->codec_type = codec->codec_type;
par->codec_id = codec->codec_id;
par->codec_tag = codec->codec_tag;
par->bit_rate = codec->bit_rate;
par->bits_per_coded_sample = codec->bits_per_coded_sample;
par->bits_per_raw_sample = codec->bits_per_raw_sample;
par->profile = codec->profile;
par->level = codec->level;
switch (par->codec_type) {
case AVMEDIA_TYPE_VIDEO:
par->format = codec->pix_fmt;
par->width = codec->width;
par->height = codec->height;
par->field_order = codec->field_order;
par->color_range = codec->color_range;
par->color_primaries = codec->color_primaries;
par->color_trc = codec->color_trc;
par->color_space = codec->colorspace;
par->chroma_location = codec->chroma_sample_location;
par->sample_aspect_ratio = codec->sample_aspect_ratio;
par->video_delay = codec->has_b_frames;
break;
case AVMEDIA_TYPE_AUDIO:
par->format = codec->sample_fmt;
par->channel_layout = codec->channel_layout;
par->channels = codec->channels;
par->sample_rate = codec->sample_rate;
par->block_align = codec->block_align;
par->frame_size = codec->frame_size;
par->initial_padding = codec->initial_padding;
par->trailing_padding = codec->trailing_padding;
par->seek_preroll = codec->seek_preroll;
break;
case AVMEDIA_TYPE_SUBTITLE:
par->width = codec->width;
par->height = codec->height;
break;
}
if (codec->extradata) {
par->extradata = av_mallocz(codec->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!par->extradata)
return AVERROR(ENOMEM);
memcpy(par->extradata, codec->extradata, codec->extradata_size);
par->extradata_size = codec->extradata_size;
}
return 0;
}
int avcodec_parameters_to_context(AVCodecContext *codec,
const AVCodecParameters *par)
{
codec->codec_type = par->codec_type;
codec->codec_id = par->codec_id;
codec->codec_tag = par->codec_tag;
codec->bit_rate = par->bit_rate;
codec->bits_per_coded_sample = par->bits_per_coded_sample;
codec->bits_per_raw_sample = par->bits_per_raw_sample;
codec->profile = par->profile;
codec->level = par->level;
switch (par->codec_type) {
case AVMEDIA_TYPE_VIDEO:
codec->pix_fmt = par->format;
codec->width = par->width;
codec->height = par->height;
codec->field_order = par->field_order;
codec->color_range = par->color_range;
codec->color_primaries = par->color_primaries;
codec->color_trc = par->color_trc;
codec->colorspace = par->color_space;
codec->chroma_sample_location = par->chroma_location;
codec->sample_aspect_ratio = par->sample_aspect_ratio;
codec->has_b_frames = par->video_delay;
break;
case AVMEDIA_TYPE_AUDIO:
codec->sample_fmt = par->format;
codec->channel_layout = par->channel_layout;
codec->channels = par->channels;
codec->sample_rate = par->sample_rate;
codec->block_align = par->block_align;
codec->frame_size = par->frame_size;
codec->delay =
codec->initial_padding = par->initial_padding;
codec->trailing_padding = par->trailing_padding;
codec->seek_preroll = par->seek_preroll;
break;
case AVMEDIA_TYPE_SUBTITLE:
codec->width = par->width;
codec->height = par->height;
break;
}
if (par->extradata) {
av_freep(&codec->extradata);
codec->extradata = av_mallocz(par->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!codec->extradata)
return AVERROR(ENOMEM);
memcpy(codec->extradata, par->extradata, par->extradata_size);
codec->extradata_size = par->extradata_size;
}
return 0;
}
int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len,
void **data, size_t *sei_size)
{
AVFrameSideData *side_data = NULL;
uint8_t *sei_data;
if (frame)
side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
if (!side_data) {
*data = NULL;
return 0;
}
*sei_size = side_data->size + 11;
*data = av_mallocz(*sei_size + prefix_len);
if (!*data)
return AVERROR(ENOMEM);
sei_data = (uint8_t*)*data + prefix_len;
// country code
sei_data[0] = 181;
sei_data[1] = 0;
sei_data[2] = 49;
/**
* 'GA94' is standard in North America for ATSC, but hard coding
* this style may not be the right thing to do -- other formats
* do exist. This information is not available in the side_data
* so we are going with this right now.
*/
AV_WL32(sei_data + 3, MKTAG('G', 'A', '9', '4'));
sei_data[7] = 3;
sei_data[8] = ((side_data->size/3) & 0x1f) | 0x40;
sei_data[9] = 0;
memcpy(sei_data + 10, side_data->data, side_data->size);
sei_data[side_data->size+10] = 255;
return 0;
}
int64_t ff_guess_coded_bitrate(AVCodecContext *avctx)
{
AVRational framerate = avctx->framerate;
int bits_per_coded_sample = avctx->bits_per_coded_sample;
int64_t bitrate;
if (!(framerate.num && framerate.den))
framerate = av_inv_q(avctx->time_base);
if (!(framerate.num && framerate.den))
return 0;
if (!bits_per_coded_sample) {
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
bits_per_coded_sample = av_get_bits_per_pixel(desc);
}
bitrate = (int64_t)bits_per_coded_sample * avctx->width * avctx->height *
framerate.num / framerate.den;
return bitrate;
}
int ff_int_from_list_or_default(void *ctx, const char * val_name, int val,
const int * array_valid_values, int default_value)
{
int i = 0, ref_val;
while (1) {
ref_val = array_valid_values[i];
if (ref_val == INT_MAX)
break;
if (val == ref_val)
return val;
i++;
}
/* val is not a valid value */
av_log(ctx, AV_LOG_DEBUG,
"%s %d are not supported. Set to default value : %d\n", val_name, val, default_value);
return default_value;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_1180_0 |
crossvul-cpp_data_bad_4042_1 | /*******************************************************************************
*
* Copyright (c) 2000-2003 Intel Corporation
* All rights reserved.
* Copyright (c) 2012 France Telecom 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 name of Intel Corporation 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 INTEL 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.
*
******************************************************************************/
/************************************************************************
* Purpose: This file defines the functions for services. It defines
* functions for adding and removing services to and from the service table,
* adding and accessing subscription and other attributes pertaining to the
* service
************************************************************************/
#include "service_table.h"
#include "config.h"
#ifdef INCLUDE_DEVICE_APIS
#if EXCLUDE_GENA == 0
/************************************************************************
* Function : copy_subscription
*
* Parameters :
* subscription *in ; Source subscription
* subscription *out ; Destination subscription
*
* Description : Makes a copy of the subscription
*
* Return : int ;
* HTTP_SUCCESS - On success
*
* Note :
************************************************************************/
int copy_subscription(subscription *in, subscription *out)
{
int return_code = HTTP_SUCCESS;
memcpy(out->sid, in->sid, SID_SIZE);
out->sid[SID_SIZE] = 0;
out->ToSendEventKey = in->ToSendEventKey;
out->expireTime = in->expireTime;
out->active = in->active;
return_code = copy_URL_list(&in->DeliveryURLs, &out->DeliveryURLs);
if (return_code != HTTP_SUCCESS) {
return return_code;
}
ListInit(&out->outgoing, 0, 0);
out->next = NULL;
return HTTP_SUCCESS;
}
/************************************************************************
* Function : RemoveSubscriptionSID
*
* Parameters :
* Upnp_SID sid ; subscription ID
* service_info * service ; service object providing the
*list of subscriptions
*
* Description : Remove the subscription represented by the
* const Upnp_SID sid parameter from the service table and update
* the service table.
*
* Return : void ;
*
* Note :
************************************************************************/
void RemoveSubscriptionSID(Upnp_SID sid, service_info *service)
{
subscription *finger = service->subscriptionList;
subscription *previous = NULL;
while (finger) {
if (!strcmp(sid, finger->sid)) {
if (previous) {
previous->next = finger->next;
} else {
service->subscriptionList = finger->next;
}
finger->next = NULL;
freeSubscriptionList(finger);
finger = NULL;
service->TotalSubscriptions--;
} else {
previous = finger;
finger = finger->next;
}
}
}
subscription *GetSubscriptionSID(const Upnp_SID sid, service_info *service)
{
subscription *next = service->subscriptionList;
subscription *previous = NULL;
subscription *found = NULL;
time_t current_time;
while (next && !found) {
if (!strcmp(next->sid, sid))
found = next;
else {
previous = next;
next = next->next;
}
}
if (found) {
/* get the current_time */
time(¤t_time);
if (found->expireTime && found->expireTime < current_time) {
if (previous) {
previous->next = found->next;
} else {
service->subscriptionList = found->next;
}
found->next = NULL;
freeSubscriptionList(found);
found = NULL;
service->TotalSubscriptions--;
}
}
return found;
}
subscription *GetNextSubscription(service_info *service, subscription *current)
{
time_t current_time;
subscription *next = NULL;
subscription *previous = NULL;
int notDone = 1;
/* get the current_time */
time(¤t_time);
while (notDone && current) {
previous = current;
current = current->next;
if (!current) {
notDone = 0;
next = current;
} else if (current->expireTime &&
current->expireTime < current_time) {
previous->next = current->next;
current->next = NULL;
freeSubscriptionList(current);
current = previous;
service->TotalSubscriptions--;
} else if (current->active) {
notDone = 0;
next = current;
}
}
return next;
}
subscription *GetFirstSubscription(service_info *service)
{
subscription temp;
subscription *next = NULL;
temp.next = service->subscriptionList;
next = GetNextSubscription(service, &temp);
service->subscriptionList = temp.next;
/* service->subscriptionList = next; */
return next;
}
void freeSubscription(subscription *sub)
{
if (sub) {
free_URL_list(&sub->DeliveryURLs);
freeSubscriptionQueuedEvents(sub);
}
}
/************************************************************************
* Function : freeSubscriptionList
*
* Parameters :
* subscription * head ; head of the subscription list
*
* Description : Free's memory allocated for all the subscriptions
* in the service table.
*
* Return : void ;
*
* Note :
************************************************************************/
void freeSubscriptionList(subscription *head)
{
subscription *next = NULL;
while (head) {
next = head->next;
freeSubscription(head);
free(head);
head = next;
}
}
/*******************************************************************************
* Function : FindServiceId
*
* Parameters :
* service_table *table; service table
* const char *serviceId; string representing the service id to be found
* among those in the
* table const char *UDN; string representing the UDN to be found among those
* in the table
*
* Description: Traverses through the service table and returns a pointer to the
* service node that matches a known service id and a known UDN.
*
* Return:
* service_info *: pointer to the matching service_info node.
******************************************************************************/
service_info *FindServiceId(
service_table *table, const char *serviceId, const char *UDN)
{
service_info *finger = NULL;
if (table) {
finger = table->serviceList;
while (finger) {
if (!strcmp(serviceId, finger->serviceId) &&
!strcmp(UDN, finger->UDN)) {
return finger;
}
finger = finger->next;
}
}
return NULL;
}
/************************************************************************
* Function : FindServiceEventURLPath
*
* Parameters :
* service_table *table ; service table
* char * eventURLPath ; event URL path used to find a service
* from the table
*
* Description : Traverses the service table and finds the node whose
* event URL Path matches a know value
*
* Return : service_info * - pointer to the service list node from the
* service table whose event URL matches a known event URL;
*
* Note :
************************************************************************/
service_info *FindServiceEventURLPath(
service_table *table, const char *eventURLPath)
{
service_info *finger = NULL;
uri_type parsed_url;
uri_type parsed_url_in;
if (table &&
parse_uri(eventURLPath, strlen(eventURLPath), &parsed_url_in) ==
HTTP_SUCCESS) {
finger = table->serviceList;
while (finger) {
if (finger->eventURL) {
if (parse_uri(finger->eventURL,
strlen(finger->eventURL),
&parsed_url) == HTTP_SUCCESS) {
if (!token_cmp(&parsed_url.pathquery,
&parsed_url_in.pathquery)) {
return finger;
}
}
}
finger = finger->next;
}
}
return NULL;
}
#endif /* EXCLUDE_GENA */
/***********************************************************************
* Function: FindServiceControlURLPath
*
* Parameters:
* service_table *table; service table
* char *controlURLPath; control URL path used to find a service from
* the table
*
* Description: Traverses the service table and finds the node whose
* control URL Path matches a know value
*
* Return: service_info *: pointer to the service list node from the
* service table whose control URL Path matches a known value.
**********************************************************************/
#if EXCLUDE_SOAP == 0
service_info *FindServiceControlURLPath(
service_table *table, const char *controlURLPath)
{
service_info *finger = NULL;
uri_type parsed_url;
uri_type parsed_url_in;
if (table && parse_uri(controlURLPath,
strlen(controlURLPath),
&parsed_url_in) == HTTP_SUCCESS) {
finger = table->serviceList;
while (finger) {
if (finger->controlURL) {
if (parse_uri(finger->controlURL,
strlen(finger->controlURL),
&parsed_url) == HTTP_SUCCESS) {
if (!token_cmp(&parsed_url.pathquery,
&parsed_url_in.pathquery)) {
return finger;
}
}
}
finger = finger->next;
}
}
return NULL;
}
#endif /* EXCLUDE_SOAP */
/***********************************************************************
* Function: printService
*
* Parameters:
* service_info *service; Service whose information is to be printed
* Upnp_LogLevel level; Debug level specified to the print function
* Dbg_Module module; Debug module specified to the print function
*
* Description: For debugging purposes prints information from the
* service passed into the function.
*
* Return: void
**********************************************************************/
#ifdef DEBUG
void printService(service_info *service, Upnp_LogLevel level, Dbg_Module module)
{
if (service) {
if (service->serviceType) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"serviceType: %s\n",
service->serviceType);
}
if (service->serviceId) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"serviceId: %s\n",
service->serviceId);
}
if (service->SCPDURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"SCPDURL: %s\n",
service->SCPDURL);
}
if (service->controlURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"controlURL: %s\n",
service->controlURL);
}
if (service->eventURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"eventURL: %s\n",
service->eventURL);
}
if (service->UDN) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"UDN: %s\n\n",
service->UDN);
}
if (service->active) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"Service is active\n");
} else {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"Service is inactive\n");
}
}
}
#endif
/************************************************************************
* Function: printServiceList
*
* Parameters:
* service_info *service; Service whose information is to be printed
* Upnp_LogLevel level; Debug level specified to the print function
* Dbg_Module module; Debug module specified to the print function
*
* Description: For debugging purposes prints information of each
* service from the service table passed into the function.
*
* Return: void
************************************************************************/
#ifdef DEBUG
void printServiceList(
service_info *service, Upnp_LogLevel level, Dbg_Module module)
{
while (service) {
if (service->serviceType) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"serviceType: %s\n",
service->serviceType);
}
if (service->serviceId) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"serviceId: %s\n",
service->serviceId);
}
if (service->SCPDURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"SCPDURL: %s\n",
service->SCPDURL);
}
if (service->controlURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"controlURL: %s\n",
service->controlURL);
}
if (service->eventURL) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"eventURL: %s\n",
service->eventURL);
}
if (service->UDN) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"UDN: %s\n\n",
service->UDN);
}
if (service->active) {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"Service is active\n");
} else {
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"Service is inactive\n");
}
service = service->next;
}
}
#endif
/************************************************************************
* Function: printServiceTable
*
* Parameters:
* service_table *table; Service table to be printed
* Upnp_LogLevel level; Debug level specified to the print function
* Dbg_Module module; Debug module specified to the print function
*
* Description: For debugging purposes prints the URL base of the table
* and information of each service from the service table passed into
* the function.
*
* Return: void
************************************************************************/
#ifdef DEBUG
void printServiceTable(
service_table *table, Upnp_LogLevel level, Dbg_Module module)
{
UpnpPrintf(level,
module,
__FILE__,
__LINE__,
"URL_BASE: %s\n",
table->URLBase);
UpnpPrintf(level, module, __FILE__, __LINE__, "Services: \n");
printServiceList(table->serviceList, level, module);
}
#endif
#if EXCLUDE_GENA == 0
/************************************************************************
* Function : freeService
*
* Parameters :
* service_info *in ; service information that is to be freed
*
* Description : Free's memory allocated for the various components
* of the service entry in the service table.
*
* Return : void ;
*
* Note :
************************************************************************/
void freeService(service_info *in)
{
if (in) {
if (in->serviceType)
ixmlFreeDOMString(in->serviceType);
if (in->serviceId)
ixmlFreeDOMString(in->serviceId);
if (in->SCPDURL)
free(in->SCPDURL);
if (in->controlURL)
free(in->controlURL);
if (in->eventURL)
free(in->eventURL);
if (in->UDN)
ixmlFreeDOMString(in->UDN);
if (in->subscriptionList)
freeSubscriptionList(in->subscriptionList);
in->TotalSubscriptions = 0;
free(in);
}
}
/************************************************************************
* Function : freeServiceList
*
* Parameters :
* service_info * head ; Head of the service list to be freed
*
* Description : Free's memory allocated for the various components
* of each service entry in the service table.
*
* Return : void ;
*
* Note :
************************************************************************/
void freeServiceList(service_info *head)
{
service_info *next = NULL;
while (head) {
if (head->serviceType)
ixmlFreeDOMString(head->serviceType);
if (head->serviceId)
ixmlFreeDOMString(head->serviceId);
if (head->SCPDURL)
free(head->SCPDURL);
if (head->controlURL)
free(head->controlURL);
if (head->eventURL)
free(head->eventURL);
if (head->UDN)
ixmlFreeDOMString(head->UDN);
if (head->subscriptionList)
freeSubscriptionList(head->subscriptionList);
head->TotalSubscriptions = 0;
next = head->next;
free(head);
head = next;
}
}
/************************************************************************
* Function : freeServiceTable
*
* Parameters :
* service_table * table ; Service table whose memory needs to be
* freed
*
* Description : Free's dynamic memory in table.
* (does not free table, only memory within the structure)
*
* Return : void ;
*
* Note :
************************************************************************/
void freeServiceTable(service_table *table)
{
ixmlFreeDOMString(table->URLBase);
freeServiceList(table->serviceList);
table->serviceList = NULL;
table->endServiceList = NULL;
}
/*******************************************************************************
* Function: getElementValue
*
* Parameters:
* IXML_Node *node; Input node which provides the list of child nodes
*
* Description: Returns the clone of the element value
*
* Return: DOMString
*
* Note: value must be freed with DOMString_free
******************************************************************************/
DOMString getElementValue(IXML_Node *node)
{
IXML_Node *child = (IXML_Node *)ixmlNode_getFirstChild(node);
const DOMString temp = NULL;
if (child && ixmlNode_getNodeType(child) == eTEXT_NODE) {
temp = ixmlNode_getNodeValue(child);
return ixmlCloneDOMString(temp);
} else {
return NULL;
}
}
/*******************************************************************************
* Function: getSubElement
*
* Parameters:
* const char *element_name; sub element name to be searched for
* IXML_Node *node; Input node which provides the list of child nodes
* IXML_Node **out; Ouput node to which the matched child node is
* returned.
*
* Description: Traverses through a list of XML nodes to find the node with the
* known element name.
*
* Return: int
* 1 - On Success
* 0 - On Failure
******************************************************************************/
int getSubElement(const char *element_name, IXML_Node *node, IXML_Node **out)
{
const DOMString NodeName = NULL;
int found = 0;
IXML_Node *child = (IXML_Node *)ixmlNode_getFirstChild(node);
(*out) = NULL;
while (child && !found) {
switch (ixmlNode_getNodeType(child)) {
case eELEMENT_NODE:
NodeName = ixmlNode_getNodeName(child);
if (!strcmp(NodeName, element_name)) {
(*out) = child;
found = 1;
return found;
}
break;
default:
break;
}
child = (IXML_Node *)ixmlNode_getNextSibling(child);
}
return found;
}
/*******************************************************************************
* Function: getServiceList
*
* Parameters:
* IXML_Node *node; XML node information
* service_info **end; service added is returned to the output parameter
* char *URLBase; provides Base URL to resolve relative URL
*
* Description: Returns pointer to service info after getting the sub-elements
* of the service info.
*
* Return: service_info *: pointer to the service info node
******************************************************************************/
service_info *getServiceList(IXML_Node *node, service_info **end, char *URLBase)
{
IXML_Node *serviceList = NULL;
IXML_Node *current_service = NULL;
IXML_Node *UDN = NULL;
IXML_Node *serviceType = NULL;
IXML_Node *serviceId = NULL;
IXML_Node *SCPDURL = NULL;
IXML_Node *controlURL = NULL;
IXML_Node *eventURL = NULL;
DOMString tempDOMString = NULL;
service_info *head = NULL;
service_info *current = NULL;
service_info *previous = NULL;
IXML_NodeList *serviceNodeList = NULL;
long unsigned int NumOfServices = 0lu;
long unsigned int i = 0lu;
int fail = 0;
if (getSubElement("UDN", node, &UDN) &&
getSubElement("serviceList", node, &serviceList)) {
serviceNodeList = ixmlElement_getElementsByTagName(
(IXML_Element *)serviceList, "service");
if (serviceNodeList) {
NumOfServices = ixmlNodeList_length(serviceNodeList);
for (i = 0lu; i < NumOfServices; i++) {
current_service =
ixmlNodeList_item(serviceNodeList, i);
fail = 0;
if (current) {
current->next =
malloc(sizeof(service_info));
previous = current;
current = current->next;
} else {
head = malloc(sizeof(service_info));
current = head;
}
if (!current) {
freeServiceList(head);
ixmlNodeList_free(serviceNodeList);
return NULL;
}
current->next = NULL;
current->controlURL = NULL;
current->eventURL = NULL;
current->serviceType = NULL;
current->serviceId = NULL;
current->SCPDURL = NULL;
current->active = 1;
current->subscriptionList = NULL;
current->TotalSubscriptions = 0;
if (!(current->UDN = getElementValue(UDN)))
fail = 1;
if (!getSubElement("serviceType",
current_service,
&serviceType) ||
!(current->serviceType =
getElementValue(
serviceType)))
fail = 1;
if (!getSubElement("serviceId",
current_service,
&serviceId) ||
!(current->serviceId = getElementValue(
serviceId)))
fail = 1;
if (!getSubElement("SCPDURL",
current_service,
&SCPDURL) ||
!(tempDOMString = getElementValue(
SCPDURL)) ||
!(current->SCPDURL = resolve_rel_url(
URLBase, tempDOMString)))
fail = 1;
ixmlFreeDOMString(tempDOMString);
tempDOMString = NULL;
if (!(getSubElement("controlURL",
current_service,
&controlURL)) ||
!(tempDOMString = getElementValue(
controlURL)) ||
!(current->controlURL = resolve_rel_url(
URLBase, tempDOMString))) {
UpnpPrintf(UPNP_INFO,
GENA,
__FILE__,
__LINE__,
"BAD OR MISSING CONTROL URL");
UpnpPrintf(UPNP_INFO,
GENA,
__FILE__,
__LINE__,
"CONTROL URL SET TO NULL IN "
"SERVICE INFO");
current->controlURL = NULL;
fail = 0;
}
ixmlFreeDOMString(tempDOMString);
tempDOMString = NULL;
if (!getSubElement("eventSubURL",
current_service,
&eventURL) ||
!(tempDOMString = getElementValue(
eventURL)) ||
!(current->eventURL = resolve_rel_url(
URLBase, tempDOMString))) {
UpnpPrintf(UPNP_INFO,
GENA,
__FILE__,
__LINE__,
"BAD OR MISSING EVENT URL");
UpnpPrintf(UPNP_INFO,
GENA,
__FILE__,
__LINE__,
"EVENT URL SET TO NULL IN "
"SERVICE INFO");
current->eventURL = NULL;
fail = 0;
}
ixmlFreeDOMString(tempDOMString);
tempDOMString = NULL;
if (fail) {
freeServiceList(current);
if (previous)
previous->next = NULL;
else
head = NULL;
current = previous;
}
}
ixmlNodeList_free(serviceNodeList);
}
(*end) = current;
return head;
} else {
(*end) = NULL;
return NULL;
}
}
/*******************************************************************************
* Function: getAllServiceList
*
* Parameters:
* IXML_Node *node; XML node information
* char *URLBase; provides Base URL to resolve relative URL
* service_info **out_end; service added is returned to the output parameter
*
* Description: Returns pointer to service info after getting the sub-elements
* of the service info.
*
* Return: service_info *
******************************************************************************/
service_info *getAllServiceList(
IXML_Node *node, char *URLBase, service_info **out_end)
{
service_info *head = NULL;
service_info *end = NULL;
service_info *next_end = NULL;
IXML_NodeList *deviceList = NULL;
IXML_Node *currentDevice = NULL;
long unsigned int NumOfDevices = 0lu;
long unsigned int i = 0lu;
(*out_end) = NULL;
deviceList = ixmlElement_getElementsByTagName(
(IXML_Element *)node, "device");
if (deviceList) {
NumOfDevices = ixmlNodeList_length(deviceList);
for (i = 0lu; i < NumOfDevices; i++) {
currentDevice = ixmlNodeList_item(deviceList, i);
if (head) {
end->next = getServiceList(
currentDevice, &next_end, URLBase);
if (next_end)
end = next_end;
} else {
head = getServiceList(
currentDevice, &end, URLBase);
}
}
ixmlNodeList_free(deviceList);
}
(*out_end) = end;
return head;
}
/*******************************************************************************
* Function: removeServiceTable
*
* Parameters:
* IXML_Node *node ; XML node information
* service_table *in; service table from which services will be removed
*
* Description: This function assumes that services for a particular root device
* are placed linearly in the service table, and in the order in which they
* are found in the description document all services for this root device
* are removed from the list
*
* Return: int
******************************************************************************/
int removeServiceTable(IXML_Node *node, service_table *in)
{
IXML_Node *root = NULL;
IXML_Node *currentUDN = NULL;
DOMString UDN = NULL;
IXML_NodeList *deviceList = NULL;
service_info *current_service = NULL;
service_info *start_search = NULL;
service_info *prev_service = NULL;
long unsigned int NumOfDevices = 0lu;
long unsigned int i = 0lu;
if (getSubElement("root", node, &root)) {
start_search = in->serviceList;
deviceList = ixmlElement_getElementsByTagName(
(IXML_Element *)root, "device");
if (deviceList) {
NumOfDevices = ixmlNodeList_length(deviceList);
for (i = 0lu; i < NumOfDevices; i++) {
if ((start_search) &&
((getSubElement(
"UDN", node, ¤tUDN)) &&
(UDN = getElementValue(
currentUDN)))) {
current_service = start_search;
/* Services are put in the service table
* in the order in which they appear in
* the description document, therefore
* we go through the list only once to
* remove a particular root device */
while ((current_service) &&
(strcmp(current_service->UDN,
UDN))) {
current_service =
current_service->next;
if (current_service != NULL)
prev_service =
current_service
->next;
}
while ((current_service) &&
(!strcmp(current_service->UDN,
UDN))) {
if (prev_service) {
prev_service->next =
current_service
->next;
} else {
in->serviceList =
current_service
->next;
}
if (current_service ==
in->endServiceList)
in->endServiceList =
prev_service;
start_search =
current_service->next;
freeService(current_service);
current_service = start_search;
}
ixmlFreeDOMString(UDN);
UDN = NULL;
}
}
ixmlNodeList_free(deviceList);
}
}
return 1;
}
/*******************************************************************************
* Function: addServiceTable
*
* Parameters :
* IXML_Node *node; XML node information
* service_table *in; service table that will be initialized with
* services
* const char *DefaultURLBase; Default base URL on which the URL will be
* returned to the service list.
*
* Description: Add Service to the table.
*
* Return: int
******************************************************************************/
int addServiceTable(
IXML_Node *node, service_table *in, const char *DefaultURLBase)
{
IXML_Node *root = NULL;
IXML_Node *URLBase = NULL;
service_info *tempEnd = NULL;
if (in->URLBase) {
free(in->URLBase);
in->URLBase = NULL;
}
if (getSubElement("root", node, &root)) {
if (getSubElement("URLBase", root, &URLBase)) {
in->URLBase = getElementValue(URLBase);
} else {
if (DefaultURLBase) {
in->URLBase =
ixmlCloneDOMString(DefaultURLBase);
} else {
in->URLBase = ixmlCloneDOMString("");
}
}
if ((in->endServiceList->next = getAllServiceList(
root, in->URLBase, &tempEnd))) {
in->endServiceList = tempEnd;
return 1;
}
}
return 0;
}
/************************************************************************
* Function : getServiceTable
*
* Parameters :
* IXML_Node *node ; XML node information
* service_table *out ; output parameter which will contain the
* service list and URL
* const char *DefaultURLBase ; Default base URL on which the URL
* will be returned.
*
* Description : Retrieve service from the table
*
* Return : int ;
*
* Note :
************************************************************************/
int getServiceTable(
IXML_Node *node, service_table *out, const char *DefaultURLBase)
{
IXML_Node *root = NULL;
IXML_Node *URLBase = NULL;
if (getSubElement("root", node, &root)) {
if (getSubElement("URLBase", root, &URLBase)) {
out->URLBase = getElementValue(URLBase);
} else {
if (DefaultURLBase) {
out->URLBase =
ixmlCloneDOMString(DefaultURLBase);
} else {
out->URLBase = ixmlCloneDOMString("");
}
}
out->serviceList = getAllServiceList(
root, out->URLBase, &out->endServiceList);
if (out->serviceList) {
return 1;
}
}
return 0;
}
#endif /* EXCLUDE_GENA */
#endif /* INCLUDE_DEVICE_APIS */
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_4042_1 |
crossvul-cpp_data_bad_902_0 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (C) 2011 Instituto Nokia de Tecnologia
*
* Authors:
* Lauro Ramos Venancio <lauro.venancio@openbossa.org>
* Aloisio Almeida Jr <aloisio.almeida@openbossa.org>
*
* Vendor commands implementation based on net/wireless/nl80211.c
* which is:
*
* Copyright 2006-2010 Johannes Berg <johannes@sipsolutions.net>
* Copyright 2013-2014 Intel Mobile Communications GmbH
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": %s: " fmt, __func__
#include <net/genetlink.h>
#include <linux/nfc.h>
#include <linux/slab.h>
#include "nfc.h"
#include "llcp.h"
static const struct genl_multicast_group nfc_genl_mcgrps[] = {
{ .name = NFC_GENL_MCAST_EVENT_NAME, },
};
static struct genl_family nfc_genl_family;
static const struct nla_policy nfc_genl_policy[NFC_ATTR_MAX + 1] = {
[NFC_ATTR_DEVICE_INDEX] = { .type = NLA_U32 },
[NFC_ATTR_DEVICE_NAME] = { .type = NLA_STRING,
.len = NFC_DEVICE_NAME_MAXSIZE },
[NFC_ATTR_PROTOCOLS] = { .type = NLA_U32 },
[NFC_ATTR_COMM_MODE] = { .type = NLA_U8 },
[NFC_ATTR_RF_MODE] = { .type = NLA_U8 },
[NFC_ATTR_DEVICE_POWERED] = { .type = NLA_U8 },
[NFC_ATTR_IM_PROTOCOLS] = { .type = NLA_U32 },
[NFC_ATTR_TM_PROTOCOLS] = { .type = NLA_U32 },
[NFC_ATTR_LLC_PARAM_LTO] = { .type = NLA_U8 },
[NFC_ATTR_LLC_PARAM_RW] = { .type = NLA_U8 },
[NFC_ATTR_LLC_PARAM_MIUX] = { .type = NLA_U16 },
[NFC_ATTR_LLC_SDP] = { .type = NLA_NESTED },
[NFC_ATTR_FIRMWARE_NAME] = { .type = NLA_STRING,
.len = NFC_FIRMWARE_NAME_MAXSIZE },
[NFC_ATTR_SE_APDU] = { .type = NLA_BINARY },
[NFC_ATTR_VENDOR_DATA] = { .type = NLA_BINARY },
};
static const struct nla_policy nfc_sdp_genl_policy[NFC_SDP_ATTR_MAX + 1] = {
[NFC_SDP_ATTR_URI] = { .type = NLA_STRING,
.len = U8_MAX - 4 },
[NFC_SDP_ATTR_SAP] = { .type = NLA_U8 },
};
static int nfc_genl_send_target(struct sk_buff *msg, struct nfc_target *target,
struct netlink_callback *cb, int flags)
{
void *hdr;
hdr = genlmsg_put(msg, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
&nfc_genl_family, flags, NFC_CMD_GET_TARGET);
if (!hdr)
return -EMSGSIZE;
genl_dump_check_consistent(cb, hdr);
if (nla_put_u32(msg, NFC_ATTR_TARGET_INDEX, target->idx) ||
nla_put_u32(msg, NFC_ATTR_PROTOCOLS, target->supported_protocols) ||
nla_put_u16(msg, NFC_ATTR_TARGET_SENS_RES, target->sens_res) ||
nla_put_u8(msg, NFC_ATTR_TARGET_SEL_RES, target->sel_res))
goto nla_put_failure;
if (target->nfcid1_len > 0 &&
nla_put(msg, NFC_ATTR_TARGET_NFCID1, target->nfcid1_len,
target->nfcid1))
goto nla_put_failure;
if (target->sensb_res_len > 0 &&
nla_put(msg, NFC_ATTR_TARGET_SENSB_RES, target->sensb_res_len,
target->sensb_res))
goto nla_put_failure;
if (target->sensf_res_len > 0 &&
nla_put(msg, NFC_ATTR_TARGET_SENSF_RES, target->sensf_res_len,
target->sensf_res))
goto nla_put_failure;
if (target->is_iso15693) {
if (nla_put_u8(msg, NFC_ATTR_TARGET_ISO15693_DSFID,
target->iso15693_dsfid) ||
nla_put(msg, NFC_ATTR_TARGET_ISO15693_UID,
sizeof(target->iso15693_uid), target->iso15693_uid))
goto nla_put_failure;
}
genlmsg_end(msg, hdr);
return 0;
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static struct nfc_dev *__get_device_from_cb(struct netlink_callback *cb)
{
struct nlattr **attrbuf = genl_family_attrbuf(&nfc_genl_family);
struct nfc_dev *dev;
int rc;
u32 idx;
rc = nlmsg_parse_deprecated(cb->nlh,
GENL_HDRLEN + nfc_genl_family.hdrsize,
attrbuf, nfc_genl_family.maxattr,
nfc_genl_policy, NULL);
if (rc < 0)
return ERR_PTR(rc);
if (!attrbuf[NFC_ATTR_DEVICE_INDEX])
return ERR_PTR(-EINVAL);
idx = nla_get_u32(attrbuf[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return ERR_PTR(-ENODEV);
return dev;
}
static int nfc_genl_dump_targets(struct sk_buff *skb,
struct netlink_callback *cb)
{
int i = cb->args[0];
struct nfc_dev *dev = (struct nfc_dev *) cb->args[1];
int rc;
if (!dev) {
dev = __get_device_from_cb(cb);
if (IS_ERR(dev))
return PTR_ERR(dev);
cb->args[1] = (long) dev;
}
device_lock(&dev->dev);
cb->seq = dev->targets_generation;
while (i < dev->n_targets) {
rc = nfc_genl_send_target(skb, &dev->targets[i], cb,
NLM_F_MULTI);
if (rc < 0)
break;
i++;
}
device_unlock(&dev->dev);
cb->args[0] = i;
return skb->len;
}
static int nfc_genl_dump_targets_done(struct netlink_callback *cb)
{
struct nfc_dev *dev = (struct nfc_dev *) cb->args[1];
if (dev)
nfc_put_device(dev);
return 0;
}
int nfc_genl_targets_found(struct nfc_dev *dev)
{
struct sk_buff *msg;
void *hdr;
dev->genl_data.poll_req_portid = 0;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_TARGETS_FOUND);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_ATOMIC);
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
int nfc_genl_target_lost(struct nfc_dev *dev, u32 target_idx)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_TARGET_LOST);
if (!hdr)
goto free_msg;
if (nla_put_string(msg, NFC_ATTR_DEVICE_NAME, nfc_device_name(dev)) ||
nla_put_u32(msg, NFC_ATTR_TARGET_INDEX, target_idx))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
int nfc_genl_tm_activated(struct nfc_dev *dev, u32 protocol)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_TM_ACTIVATED);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx))
goto nla_put_failure;
if (nla_put_u32(msg, NFC_ATTR_TM_PROTOCOLS, protocol))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
int nfc_genl_tm_deactivated(struct nfc_dev *dev)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_TM_DEACTIVATED);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
static int nfc_genl_setup_device_added(struct nfc_dev *dev, struct sk_buff *msg)
{
if (nla_put_string(msg, NFC_ATTR_DEVICE_NAME, nfc_device_name(dev)) ||
nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx) ||
nla_put_u32(msg, NFC_ATTR_PROTOCOLS, dev->supported_protocols) ||
nla_put_u8(msg, NFC_ATTR_DEVICE_POWERED, dev->dev_up) ||
nla_put_u8(msg, NFC_ATTR_RF_MODE, dev->rf_mode))
return -1;
return 0;
}
int nfc_genl_device_added(struct nfc_dev *dev)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_DEVICE_ADDED);
if (!hdr)
goto free_msg;
if (nfc_genl_setup_device_added(dev, msg))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
int nfc_genl_device_removed(struct nfc_dev *dev)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_DEVICE_REMOVED);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
int nfc_genl_llc_send_sdres(struct nfc_dev *dev, struct hlist_head *sdres_list)
{
struct sk_buff *msg;
struct nlattr *sdp_attr, *uri_attr;
struct nfc_llcp_sdp_tlv *sdres;
struct hlist_node *n;
void *hdr;
int rc = -EMSGSIZE;
int i;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_LLC_SDRES);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx))
goto nla_put_failure;
sdp_attr = nla_nest_start_noflag(msg, NFC_ATTR_LLC_SDP);
if (sdp_attr == NULL) {
rc = -ENOMEM;
goto nla_put_failure;
}
i = 1;
hlist_for_each_entry_safe(sdres, n, sdres_list, node) {
pr_debug("uri: %s, sap: %d\n", sdres->uri, sdres->sap);
uri_attr = nla_nest_start_noflag(msg, i++);
if (uri_attr == NULL) {
rc = -ENOMEM;
goto nla_put_failure;
}
if (nla_put_u8(msg, NFC_SDP_ATTR_SAP, sdres->sap))
goto nla_put_failure;
if (nla_put_string(msg, NFC_SDP_ATTR_URI, sdres->uri))
goto nla_put_failure;
nla_nest_end(msg, uri_attr);
hlist_del(&sdres->node);
nfc_llcp_free_sdp_tlv(sdres);
}
nla_nest_end(msg, sdp_attr);
genlmsg_end(msg, hdr);
return genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_ATOMIC);
nla_put_failure:
free_msg:
nlmsg_free(msg);
nfc_llcp_free_sdp_tlv_list(sdres_list);
return rc;
}
int nfc_genl_se_added(struct nfc_dev *dev, u32 se_idx, u16 type)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_SE_ADDED);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx) ||
nla_put_u32(msg, NFC_ATTR_SE_INDEX, se_idx) ||
nla_put_u8(msg, NFC_ATTR_SE_TYPE, type))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
int nfc_genl_se_removed(struct nfc_dev *dev, u32 se_idx)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_SE_REMOVED);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx) ||
nla_put_u32(msg, NFC_ATTR_SE_INDEX, se_idx))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
int nfc_genl_se_transaction(struct nfc_dev *dev, u8 se_idx,
struct nfc_evt_transaction *evt_transaction)
{
struct nfc_se *se;
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_SE_TRANSACTION);
if (!hdr)
goto free_msg;
se = nfc_find_se(dev, se_idx);
if (!se)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx) ||
nla_put_u32(msg, NFC_ATTR_SE_INDEX, se_idx) ||
nla_put_u8(msg, NFC_ATTR_SE_TYPE, se->type) ||
nla_put(msg, NFC_ATTR_SE_AID, evt_transaction->aid_len,
evt_transaction->aid) ||
nla_put(msg, NFC_ATTR_SE_PARAMS, evt_transaction->params_len,
evt_transaction->params))
goto nla_put_failure;
/* evt_transaction is no more used */
devm_kfree(&dev->dev, evt_transaction);
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
/* evt_transaction is no more used */
devm_kfree(&dev->dev, evt_transaction);
nlmsg_free(msg);
return -EMSGSIZE;
}
int nfc_genl_se_connectivity(struct nfc_dev *dev, u8 se_idx)
{
struct nfc_se *se;
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_EVENT_SE_CONNECTIVITY);
if (!hdr)
goto free_msg;
se = nfc_find_se(dev, se_idx);
if (!se)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx) ||
nla_put_u32(msg, NFC_ATTR_SE_INDEX, se_idx) ||
nla_put_u8(msg, NFC_ATTR_SE_TYPE, se->type))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
static int nfc_genl_send_device(struct sk_buff *msg, struct nfc_dev *dev,
u32 portid, u32 seq,
struct netlink_callback *cb,
int flags)
{
void *hdr;
hdr = genlmsg_put(msg, portid, seq, &nfc_genl_family, flags,
NFC_CMD_GET_DEVICE);
if (!hdr)
return -EMSGSIZE;
if (cb)
genl_dump_check_consistent(cb, hdr);
if (nfc_genl_setup_device_added(dev, msg))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return 0;
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nfc_genl_dump_devices(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct class_dev_iter *iter = (struct class_dev_iter *) cb->args[0];
struct nfc_dev *dev = (struct nfc_dev *) cb->args[1];
bool first_call = false;
if (!iter) {
first_call = true;
iter = kmalloc(sizeof(struct class_dev_iter), GFP_KERNEL);
if (!iter)
return -ENOMEM;
cb->args[0] = (long) iter;
}
mutex_lock(&nfc_devlist_mutex);
cb->seq = nfc_devlist_generation;
if (first_call) {
nfc_device_iter_init(iter);
dev = nfc_device_iter_next(iter);
}
while (dev) {
int rc;
rc = nfc_genl_send_device(skb, dev, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, cb, NLM_F_MULTI);
if (rc < 0)
break;
dev = nfc_device_iter_next(iter);
}
mutex_unlock(&nfc_devlist_mutex);
cb->args[1] = (long) dev;
return skb->len;
}
static int nfc_genl_dump_devices_done(struct netlink_callback *cb)
{
struct class_dev_iter *iter = (struct class_dev_iter *) cb->args[0];
nfc_device_iter_exit(iter);
kfree(iter);
return 0;
}
int nfc_genl_dep_link_up_event(struct nfc_dev *dev, u32 target_idx,
u8 comm_mode, u8 rf_mode)
{
struct sk_buff *msg;
void *hdr;
pr_debug("DEP link is up\n");
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0, NFC_CMD_DEP_LINK_UP);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx))
goto nla_put_failure;
if (rf_mode == NFC_RF_INITIATOR &&
nla_put_u32(msg, NFC_ATTR_TARGET_INDEX, target_idx))
goto nla_put_failure;
if (nla_put_u8(msg, NFC_ATTR_COMM_MODE, comm_mode) ||
nla_put_u8(msg, NFC_ATTR_RF_MODE, rf_mode))
goto nla_put_failure;
genlmsg_end(msg, hdr);
dev->dep_link_up = true;
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_ATOMIC);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
int nfc_genl_dep_link_down_event(struct nfc_dev *dev)
{
struct sk_buff *msg;
void *hdr;
pr_debug("DEP link is down\n");
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_CMD_DEP_LINK_DOWN);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_ATOMIC);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
static int nfc_genl_get_device(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
struct nfc_dev *dev;
u32 idx;
int rc = -ENOBUFS;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg) {
rc = -ENOMEM;
goto out_putdev;
}
rc = nfc_genl_send_device(msg, dev, info->snd_portid, info->snd_seq,
NULL, 0);
if (rc < 0)
goto out_free;
nfc_put_device(dev);
return genlmsg_reply(msg, info);
out_free:
nlmsg_free(msg);
out_putdev:
nfc_put_device(dev);
return rc;
}
static int nfc_genl_dev_up(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc;
u32 idx;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
rc = nfc_dev_up(dev);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_dev_down(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc;
u32 idx;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
rc = nfc_dev_down(dev);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_start_poll(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc;
u32 idx;
u32 im_protocols = 0, tm_protocols = 0;
pr_debug("Poll start\n");
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
((!info->attrs[NFC_ATTR_IM_PROTOCOLS] &&
!info->attrs[NFC_ATTR_PROTOCOLS]) &&
!info->attrs[NFC_ATTR_TM_PROTOCOLS]))
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
if (info->attrs[NFC_ATTR_TM_PROTOCOLS])
tm_protocols = nla_get_u32(info->attrs[NFC_ATTR_TM_PROTOCOLS]);
if (info->attrs[NFC_ATTR_IM_PROTOCOLS])
im_protocols = nla_get_u32(info->attrs[NFC_ATTR_IM_PROTOCOLS]);
else if (info->attrs[NFC_ATTR_PROTOCOLS])
im_protocols = nla_get_u32(info->attrs[NFC_ATTR_PROTOCOLS]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
mutex_lock(&dev->genl_data.genl_data_mutex);
rc = nfc_start_poll(dev, im_protocols, tm_protocols);
if (!rc)
dev->genl_data.poll_req_portid = info->snd_portid;
mutex_unlock(&dev->genl_data.genl_data_mutex);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_stop_poll(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc;
u32 idx;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
device_lock(&dev->dev);
if (!dev->polling) {
device_unlock(&dev->dev);
return -EINVAL;
}
device_unlock(&dev->dev);
mutex_lock(&dev->genl_data.genl_data_mutex);
if (dev->genl_data.poll_req_portid != info->snd_portid) {
rc = -EBUSY;
goto out;
}
rc = nfc_stop_poll(dev);
dev->genl_data.poll_req_portid = 0;
out:
mutex_unlock(&dev->genl_data.genl_data_mutex);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_activate_target(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
u32 device_idx, target_idx, protocol;
int rc;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
!info->attrs[NFC_ATTR_TARGET_INDEX] ||
!info->attrs[NFC_ATTR_PROTOCOLS])
return -EINVAL;
device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(device_idx);
if (!dev)
return -ENODEV;
target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);
protocol = nla_get_u32(info->attrs[NFC_ATTR_PROTOCOLS]);
nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP);
rc = nfc_activate_target(dev, target_idx, protocol);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_deactivate_target(struct sk_buff *skb,
struct genl_info *info)
{
struct nfc_dev *dev;
u32 device_idx, target_idx;
int rc;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(device_idx);
if (!dev)
return -ENODEV;
target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);
rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_dep_link_up(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc, tgt_idx;
u32 idx;
u8 comm;
pr_debug("DEP link up\n");
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
!info->attrs[NFC_ATTR_COMM_MODE])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
if (!info->attrs[NFC_ATTR_TARGET_INDEX])
tgt_idx = NFC_TARGET_IDX_ANY;
else
tgt_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);
comm = nla_get_u8(info->attrs[NFC_ATTR_COMM_MODE]);
if (comm != NFC_COMM_ACTIVE && comm != NFC_COMM_PASSIVE)
return -EINVAL;
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
rc = nfc_dep_link_up(dev, tgt_idx, comm);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_dep_link_down(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc;
u32 idx;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
rc = nfc_dep_link_down(dev);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_send_params(struct sk_buff *msg,
struct nfc_llcp_local *local,
u32 portid, u32 seq)
{
void *hdr;
hdr = genlmsg_put(msg, portid, seq, &nfc_genl_family, 0,
NFC_CMD_LLC_GET_PARAMS);
if (!hdr)
return -EMSGSIZE;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, local->dev->idx) ||
nla_put_u8(msg, NFC_ATTR_LLC_PARAM_LTO, local->lto) ||
nla_put_u8(msg, NFC_ATTR_LLC_PARAM_RW, local->rw) ||
nla_put_u16(msg, NFC_ATTR_LLC_PARAM_MIUX, be16_to_cpu(local->miux)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return 0;
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nfc_genl_llc_get_params(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
struct nfc_llcp_local *local;
int rc = 0;
struct sk_buff *msg = NULL;
u32 idx;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
device_lock(&dev->dev);
local = nfc_llcp_find_local(dev);
if (!local) {
rc = -ENODEV;
goto exit;
}
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg) {
rc = -ENOMEM;
goto exit;
}
rc = nfc_genl_send_params(msg, local, info->snd_portid, info->snd_seq);
exit:
device_unlock(&dev->dev);
nfc_put_device(dev);
if (rc < 0) {
if (msg)
nlmsg_free(msg);
return rc;
}
return genlmsg_reply(msg, info);
}
static int nfc_genl_llc_set_params(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
struct nfc_llcp_local *local;
u8 rw = 0;
u16 miux = 0;
u32 idx;
int rc = 0;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
(!info->attrs[NFC_ATTR_LLC_PARAM_LTO] &&
!info->attrs[NFC_ATTR_LLC_PARAM_RW] &&
!info->attrs[NFC_ATTR_LLC_PARAM_MIUX]))
return -EINVAL;
if (info->attrs[NFC_ATTR_LLC_PARAM_RW]) {
rw = nla_get_u8(info->attrs[NFC_ATTR_LLC_PARAM_RW]);
if (rw > LLCP_MAX_RW)
return -EINVAL;
}
if (info->attrs[NFC_ATTR_LLC_PARAM_MIUX]) {
miux = nla_get_u16(info->attrs[NFC_ATTR_LLC_PARAM_MIUX]);
if (miux > LLCP_MAX_MIUX)
return -EINVAL;
}
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
device_lock(&dev->dev);
local = nfc_llcp_find_local(dev);
if (!local) {
nfc_put_device(dev);
rc = -ENODEV;
goto exit;
}
if (info->attrs[NFC_ATTR_LLC_PARAM_LTO]) {
if (dev->dep_link_up) {
rc = -EINPROGRESS;
goto exit;
}
local->lto = nla_get_u8(info->attrs[NFC_ATTR_LLC_PARAM_LTO]);
}
if (info->attrs[NFC_ATTR_LLC_PARAM_RW])
local->rw = rw;
if (info->attrs[NFC_ATTR_LLC_PARAM_MIUX])
local->miux = cpu_to_be16(miux);
exit:
device_unlock(&dev->dev);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_llc_sdreq(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
struct nfc_llcp_local *local;
struct nlattr *attr, *sdp_attrs[NFC_SDP_ATTR_MAX+1];
u32 idx;
u8 tid;
char *uri;
int rc = 0, rem;
size_t uri_len, tlvs_len;
struct hlist_head sdreq_list;
struct nfc_llcp_sdp_tlv *sdreq;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
!info->attrs[NFC_ATTR_LLC_SDP])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
device_lock(&dev->dev);
if (dev->dep_link_up == false) {
rc = -ENOLINK;
goto exit;
}
local = nfc_llcp_find_local(dev);
if (!local) {
nfc_put_device(dev);
rc = -ENODEV;
goto exit;
}
INIT_HLIST_HEAD(&sdreq_list);
tlvs_len = 0;
nla_for_each_nested(attr, info->attrs[NFC_ATTR_LLC_SDP], rem) {
rc = nla_parse_nested_deprecated(sdp_attrs, NFC_SDP_ATTR_MAX,
attr, nfc_sdp_genl_policy,
info->extack);
if (rc != 0) {
rc = -EINVAL;
goto exit;
}
if (!sdp_attrs[NFC_SDP_ATTR_URI])
continue;
uri_len = nla_len(sdp_attrs[NFC_SDP_ATTR_URI]);
if (uri_len == 0)
continue;
uri = nla_data(sdp_attrs[NFC_SDP_ATTR_URI]);
if (uri == NULL || *uri == 0)
continue;
tid = local->sdreq_next_tid++;
sdreq = nfc_llcp_build_sdreq_tlv(tid, uri, uri_len);
if (sdreq == NULL) {
rc = -ENOMEM;
goto exit;
}
tlvs_len += sdreq->tlv_len;
hlist_add_head(&sdreq->node, &sdreq_list);
}
if (hlist_empty(&sdreq_list)) {
rc = -EINVAL;
goto exit;
}
rc = nfc_llcp_send_snl_sdreq(local, &sdreq_list, tlvs_len);
exit:
device_unlock(&dev->dev);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_fw_download(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc;
u32 idx;
char firmware_name[NFC_FIRMWARE_NAME_MAXSIZE + 1];
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
nla_strlcpy(firmware_name, info->attrs[NFC_ATTR_FIRMWARE_NAME],
sizeof(firmware_name));
rc = nfc_fw_download(dev, firmware_name);
nfc_put_device(dev);
return rc;
}
int nfc_genl_fw_download_done(struct nfc_dev *dev, const char *firmware_name,
u32 result)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_CMD_FW_DOWNLOAD);
if (!hdr)
goto free_msg;
if (nla_put_string(msg, NFC_ATTR_FIRMWARE_NAME, firmware_name) ||
nla_put_u32(msg, NFC_ATTR_FIRMWARE_DOWNLOAD_STATUS, result) ||
nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EMSGSIZE;
}
static int nfc_genl_enable_se(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc;
u32 idx, se_idx;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
!info->attrs[NFC_ATTR_SE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
se_idx = nla_get_u32(info->attrs[NFC_ATTR_SE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
rc = nfc_enable_se(dev, se_idx);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_disable_se(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
int rc;
u32 idx, se_idx;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
!info->attrs[NFC_ATTR_SE_INDEX])
return -EINVAL;
idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
se_idx = nla_get_u32(info->attrs[NFC_ATTR_SE_INDEX]);
dev = nfc_get_device(idx);
if (!dev)
return -ENODEV;
rc = nfc_disable_se(dev, se_idx);
nfc_put_device(dev);
return rc;
}
static int nfc_genl_send_se(struct sk_buff *msg, struct nfc_dev *dev,
u32 portid, u32 seq,
struct netlink_callback *cb,
int flags)
{
void *hdr;
struct nfc_se *se, *n;
list_for_each_entry_safe(se, n, &dev->secure_elements, list) {
hdr = genlmsg_put(msg, portid, seq, &nfc_genl_family, flags,
NFC_CMD_GET_SE);
if (!hdr)
goto nla_put_failure;
if (cb)
genl_dump_check_consistent(cb, hdr);
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, dev->idx) ||
nla_put_u32(msg, NFC_ATTR_SE_INDEX, se->idx) ||
nla_put_u8(msg, NFC_ATTR_SE_TYPE, se->type))
goto nla_put_failure;
genlmsg_end(msg, hdr);
}
return 0;
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nfc_genl_dump_ses(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct class_dev_iter *iter = (struct class_dev_iter *) cb->args[0];
struct nfc_dev *dev = (struct nfc_dev *) cb->args[1];
bool first_call = false;
if (!iter) {
first_call = true;
iter = kmalloc(sizeof(struct class_dev_iter), GFP_KERNEL);
if (!iter)
return -ENOMEM;
cb->args[0] = (long) iter;
}
mutex_lock(&nfc_devlist_mutex);
cb->seq = nfc_devlist_generation;
if (first_call) {
nfc_device_iter_init(iter);
dev = nfc_device_iter_next(iter);
}
while (dev) {
int rc;
rc = nfc_genl_send_se(skb, dev, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, cb, NLM_F_MULTI);
if (rc < 0)
break;
dev = nfc_device_iter_next(iter);
}
mutex_unlock(&nfc_devlist_mutex);
cb->args[1] = (long) dev;
return skb->len;
}
static int nfc_genl_dump_ses_done(struct netlink_callback *cb)
{
struct class_dev_iter *iter = (struct class_dev_iter *) cb->args[0];
nfc_device_iter_exit(iter);
kfree(iter);
return 0;
}
static int nfc_se_io(struct nfc_dev *dev, u32 se_idx,
u8 *apdu, size_t apdu_length,
se_io_cb_t cb, void *cb_context)
{
struct nfc_se *se;
int rc;
pr_debug("%s se index %d\n", dev_name(&dev->dev), se_idx);
device_lock(&dev->dev);
if (!device_is_registered(&dev->dev)) {
rc = -ENODEV;
goto error;
}
if (!dev->dev_up) {
rc = -ENODEV;
goto error;
}
if (!dev->ops->se_io) {
rc = -EOPNOTSUPP;
goto error;
}
se = nfc_find_se(dev, se_idx);
if (!se) {
rc = -EINVAL;
goto error;
}
if (se->state != NFC_SE_ENABLED) {
rc = -ENODEV;
goto error;
}
rc = dev->ops->se_io(dev, se_idx, apdu,
apdu_length, cb, cb_context);
error:
device_unlock(&dev->dev);
return rc;
}
struct se_io_ctx {
u32 dev_idx;
u32 se_idx;
};
static void se_io_cb(void *context, u8 *apdu, size_t apdu_len, int err)
{
struct se_io_ctx *ctx = context;
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg) {
kfree(ctx);
return;
}
hdr = genlmsg_put(msg, 0, 0, &nfc_genl_family, 0,
NFC_CMD_SE_IO);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NFC_ATTR_DEVICE_INDEX, ctx->dev_idx) ||
nla_put_u32(msg, NFC_ATTR_SE_INDEX, ctx->se_idx) ||
nla_put(msg, NFC_ATTR_SE_APDU, apdu_len, apdu))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast(&nfc_genl_family, msg, 0, 0, GFP_KERNEL);
kfree(ctx);
return;
nla_put_failure:
free_msg:
nlmsg_free(msg);
kfree(ctx);
return;
}
static int nfc_genl_se_io(struct sk_buff *skb, struct genl_info *info)
{
struct nfc_dev *dev;
struct se_io_ctx *ctx;
u32 dev_idx, se_idx;
u8 *apdu;
size_t apdu_len;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
!info->attrs[NFC_ATTR_SE_INDEX] ||
!info->attrs[NFC_ATTR_SE_APDU])
return -EINVAL;
dev_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
se_idx = nla_get_u32(info->attrs[NFC_ATTR_SE_INDEX]);
dev = nfc_get_device(dev_idx);
if (!dev)
return -ENODEV;
if (!dev->ops || !dev->ops->se_io)
return -ENOTSUPP;
apdu_len = nla_len(info->attrs[NFC_ATTR_SE_APDU]);
if (apdu_len == 0)
return -EINVAL;
apdu = nla_data(info->attrs[NFC_ATTR_SE_APDU]);
if (!apdu)
return -EINVAL;
ctx = kzalloc(sizeof(struct se_io_ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->dev_idx = dev_idx;
ctx->se_idx = se_idx;
return nfc_se_io(dev, se_idx, apdu, apdu_len, se_io_cb, ctx);
}
static int nfc_genl_vendor_cmd(struct sk_buff *skb,
struct genl_info *info)
{
struct nfc_dev *dev;
struct nfc_vendor_cmd *cmd;
u32 dev_idx, vid, subcmd;
u8 *data;
size_t data_len;
int i, err;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
!info->attrs[NFC_ATTR_VENDOR_ID] ||
!info->attrs[NFC_ATTR_VENDOR_SUBCMD])
return -EINVAL;
dev_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
vid = nla_get_u32(info->attrs[NFC_ATTR_VENDOR_ID]);
subcmd = nla_get_u32(info->attrs[NFC_ATTR_VENDOR_SUBCMD]);
dev = nfc_get_device(dev_idx);
if (!dev || !dev->vendor_cmds || !dev->n_vendor_cmds)
return -ENODEV;
if (info->attrs[NFC_ATTR_VENDOR_DATA]) {
data = nla_data(info->attrs[NFC_ATTR_VENDOR_DATA]);
data_len = nla_len(info->attrs[NFC_ATTR_VENDOR_DATA]);
if (data_len == 0)
return -EINVAL;
} else {
data = NULL;
data_len = 0;
}
for (i = 0; i < dev->n_vendor_cmds; i++) {
cmd = &dev->vendor_cmds[i];
if (cmd->vendor_id != vid || cmd->subcmd != subcmd)
continue;
dev->cur_cmd_info = info;
err = cmd->doit(dev, data, data_len);
dev->cur_cmd_info = NULL;
return err;
}
return -EOPNOTSUPP;
}
/* message building helper */
static inline void *nfc_hdr_put(struct sk_buff *skb, u32 portid, u32 seq,
int flags, u8 cmd)
{
/* since there is no private header just add the generic one */
return genlmsg_put(skb, portid, seq, &nfc_genl_family, flags, cmd);
}
static struct sk_buff *
__nfc_alloc_vendor_cmd_skb(struct nfc_dev *dev, int approxlen,
u32 portid, u32 seq,
enum nfc_attrs attr,
u32 oui, u32 subcmd, gfp_t gfp)
{
struct sk_buff *skb;
void *hdr;
skb = nlmsg_new(approxlen + 100, gfp);
if (!skb)
return NULL;
hdr = nfc_hdr_put(skb, portid, seq, 0, NFC_CMD_VENDOR);
if (!hdr) {
kfree_skb(skb);
return NULL;
}
if (nla_put_u32(skb, NFC_ATTR_DEVICE_INDEX, dev->idx))
goto nla_put_failure;
if (nla_put_u32(skb, NFC_ATTR_VENDOR_ID, oui))
goto nla_put_failure;
if (nla_put_u32(skb, NFC_ATTR_VENDOR_SUBCMD, subcmd))
goto nla_put_failure;
((void **)skb->cb)[0] = dev;
((void **)skb->cb)[1] = hdr;
return skb;
nla_put_failure:
kfree_skb(skb);
return NULL;
}
struct sk_buff *__nfc_alloc_vendor_cmd_reply_skb(struct nfc_dev *dev,
enum nfc_attrs attr,
u32 oui, u32 subcmd,
int approxlen)
{
if (WARN_ON(!dev->cur_cmd_info))
return NULL;
return __nfc_alloc_vendor_cmd_skb(dev, approxlen,
dev->cur_cmd_info->snd_portid,
dev->cur_cmd_info->snd_seq, attr,
oui, subcmd, GFP_KERNEL);
}
EXPORT_SYMBOL(__nfc_alloc_vendor_cmd_reply_skb);
int nfc_vendor_cmd_reply(struct sk_buff *skb)
{
struct nfc_dev *dev = ((void **)skb->cb)[0];
void *hdr = ((void **)skb->cb)[1];
/* clear CB data for netlink core to own from now on */
memset(skb->cb, 0, sizeof(skb->cb));
if (WARN_ON(!dev->cur_cmd_info)) {
kfree_skb(skb);
return -EINVAL;
}
genlmsg_end(skb, hdr);
return genlmsg_reply(skb, dev->cur_cmd_info);
}
EXPORT_SYMBOL(nfc_vendor_cmd_reply);
static const struct genl_ops nfc_genl_ops[] = {
{
.cmd = NFC_CMD_GET_DEVICE,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_get_device,
.dumpit = nfc_genl_dump_devices,
.done = nfc_genl_dump_devices_done,
},
{
.cmd = NFC_CMD_DEV_UP,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_dev_up,
},
{
.cmd = NFC_CMD_DEV_DOWN,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_dev_down,
},
{
.cmd = NFC_CMD_START_POLL,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_start_poll,
},
{
.cmd = NFC_CMD_STOP_POLL,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_stop_poll,
},
{
.cmd = NFC_CMD_DEP_LINK_UP,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_dep_link_up,
},
{
.cmd = NFC_CMD_DEP_LINK_DOWN,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_dep_link_down,
},
{
.cmd = NFC_CMD_GET_TARGET,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.dumpit = nfc_genl_dump_targets,
.done = nfc_genl_dump_targets_done,
},
{
.cmd = NFC_CMD_LLC_GET_PARAMS,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_llc_get_params,
},
{
.cmd = NFC_CMD_LLC_SET_PARAMS,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_llc_set_params,
},
{
.cmd = NFC_CMD_LLC_SDREQ,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_llc_sdreq,
},
{
.cmd = NFC_CMD_FW_DOWNLOAD,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_fw_download,
},
{
.cmd = NFC_CMD_ENABLE_SE,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_enable_se,
},
{
.cmd = NFC_CMD_DISABLE_SE,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_disable_se,
},
{
.cmd = NFC_CMD_GET_SE,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.dumpit = nfc_genl_dump_ses,
.done = nfc_genl_dump_ses_done,
},
{
.cmd = NFC_CMD_SE_IO,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_se_io,
},
{
.cmd = NFC_CMD_ACTIVATE_TARGET,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_activate_target,
},
{
.cmd = NFC_CMD_VENDOR,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_vendor_cmd,
},
{
.cmd = NFC_CMD_DEACTIVATE_TARGET,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = nfc_genl_deactivate_target,
},
};
static struct genl_family nfc_genl_family __ro_after_init = {
.hdrsize = 0,
.name = NFC_GENL_NAME,
.version = NFC_GENL_VERSION,
.maxattr = NFC_ATTR_MAX,
.policy = nfc_genl_policy,
.module = THIS_MODULE,
.ops = nfc_genl_ops,
.n_ops = ARRAY_SIZE(nfc_genl_ops),
.mcgrps = nfc_genl_mcgrps,
.n_mcgrps = ARRAY_SIZE(nfc_genl_mcgrps),
};
struct urelease_work {
struct work_struct w;
u32 portid;
};
static void nfc_urelease_event_work(struct work_struct *work)
{
struct urelease_work *w = container_of(work, struct urelease_work, w);
struct class_dev_iter iter;
struct nfc_dev *dev;
pr_debug("portid %d\n", w->portid);
mutex_lock(&nfc_devlist_mutex);
nfc_device_iter_init(&iter);
dev = nfc_device_iter_next(&iter);
while (dev) {
mutex_lock(&dev->genl_data.genl_data_mutex);
if (dev->genl_data.poll_req_portid == w->portid) {
nfc_stop_poll(dev);
dev->genl_data.poll_req_portid = 0;
}
mutex_unlock(&dev->genl_data.genl_data_mutex);
dev = nfc_device_iter_next(&iter);
}
nfc_device_iter_exit(&iter);
mutex_unlock(&nfc_devlist_mutex);
kfree(w);
}
static int nfc_genl_rcv_nl_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct netlink_notify *n = ptr;
struct urelease_work *w;
if (event != NETLINK_URELEASE || n->protocol != NETLINK_GENERIC)
goto out;
pr_debug("NETLINK_URELEASE event from id %d\n", n->portid);
w = kmalloc(sizeof(*w), GFP_ATOMIC);
if (w) {
INIT_WORK((struct work_struct *) w, nfc_urelease_event_work);
w->portid = n->portid;
schedule_work((struct work_struct *) w);
}
out:
return NOTIFY_DONE;
}
void nfc_genl_data_init(struct nfc_genl_data *genl_data)
{
genl_data->poll_req_portid = 0;
mutex_init(&genl_data->genl_data_mutex);
}
void nfc_genl_data_exit(struct nfc_genl_data *genl_data)
{
mutex_destroy(&genl_data->genl_data_mutex);
}
static struct notifier_block nl_notifier = {
.notifier_call = nfc_genl_rcv_nl_event,
};
/**
* nfc_genl_init() - Initialize netlink interface
*
* This initialization function registers the nfc netlink family.
*/
int __init nfc_genl_init(void)
{
int rc;
rc = genl_register_family(&nfc_genl_family);
if (rc)
return rc;
netlink_register_notifier(&nl_notifier);
return 0;
}
/**
* nfc_genl_exit() - Deinitialize netlink interface
*
* This exit function unregisters the nfc netlink family.
*/
void nfc_genl_exit(void)
{
netlink_unregister_notifier(&nl_notifier);
genl_unregister_family(&nfc_genl_family);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_902_0 |
crossvul-cpp_data_bad_317_0 | /************************************************************
* Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of Silicon Graphics not be
* used in advertising or publicity pertaining to distribution
* of the software without specific prior written permission.
* Silicon Graphics makes no representation about the suitability
* of this software for any purpose. It is provided "as is"
* without any express or implied warranty.
*
* SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS BE LIABLE FOR 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.
*
********************************************************/
/*
* Copyright © 2012 Intel Corporation
* Copyright © 2012 Ran Benita <ran234@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Author: Daniel Stone <daniel@fooishbar.org>
* Ran Benita <ran234@gmail.com>
*/
#include "xkbcomp-priv.h"
#include "ast-build.h"
#include "include.h"
ParseCommon *
AppendStmt(ParseCommon *to, ParseCommon *append)
{
ParseCommon *iter;
if (!to)
return append;
for (iter = to; iter->next; iter = iter->next);
iter->next = append;
return to;
}
static ExprDef *
ExprCreate(enum expr_op_type op, enum expr_value_type type, size_t size)
{
ExprDef *expr = malloc(size);
if (!expr)
return NULL;
expr->common.type = STMT_EXPR;
expr->common.next = NULL;
expr->expr.op = op;
expr->expr.value_type = type;
return expr;
}
#define EXPR_CREATE(type_, name_, op_, value_type_) \
ExprDef *name_ = ExprCreate(op_, value_type_, sizeof(type_)); \
if (!name_) \
return NULL;
ExprDef *
ExprCreateString(xkb_atom_t str)
{
EXPR_CREATE(ExprString, expr, EXPR_VALUE, EXPR_TYPE_STRING);
expr->string.str = str;
return expr;
}
ExprDef *
ExprCreateInteger(int ival)
{
EXPR_CREATE(ExprInteger, expr, EXPR_VALUE, EXPR_TYPE_INT);
expr->integer.ival = ival;
return expr;
}
ExprDef *
ExprCreateBoolean(bool set)
{
EXPR_CREATE(ExprBoolean, expr, EXPR_VALUE, EXPR_TYPE_BOOLEAN);
expr->boolean.set = set;
return expr;
}
ExprDef *
ExprCreateKeyName(xkb_atom_t key_name)
{
EXPR_CREATE(ExprKeyName, expr, EXPR_VALUE, EXPR_TYPE_KEYNAME);
expr->key_name.key_name = key_name;
return expr;
}
ExprDef *
ExprCreateIdent(xkb_atom_t ident)
{
EXPR_CREATE(ExprIdent, expr, EXPR_IDENT, EXPR_TYPE_UNKNOWN);
expr->ident.ident = ident;
return expr;
}
ExprDef *
ExprCreateUnary(enum expr_op_type op, enum expr_value_type type,
ExprDef *child)
{
EXPR_CREATE(ExprUnary, expr, op, type);
expr->unary.child = child;
return expr;
}
ExprDef *
ExprCreateBinary(enum expr_op_type op, ExprDef *left, ExprDef *right)
{
EXPR_CREATE(ExprBinary, expr, op, EXPR_TYPE_UNKNOWN);
if (op == EXPR_ASSIGN || left->expr.value_type == EXPR_TYPE_UNKNOWN)
expr->expr.value_type = right->expr.value_type;
else if (left->expr.value_type == right->expr.value_type ||
right->expr.value_type == EXPR_TYPE_UNKNOWN)
expr->expr.value_type = left->expr.value_type;
expr->binary.left = left;
expr->binary.right = right;
return expr;
}
ExprDef *
ExprCreateFieldRef(xkb_atom_t element, xkb_atom_t field)
{
EXPR_CREATE(ExprFieldRef, expr, EXPR_FIELD_REF, EXPR_TYPE_UNKNOWN);
expr->field_ref.element = element;
expr->field_ref.field = field;
return expr;
}
ExprDef *
ExprCreateArrayRef(xkb_atom_t element, xkb_atom_t field, ExprDef *entry)
{
EXPR_CREATE(ExprArrayRef, expr, EXPR_ARRAY_REF, EXPR_TYPE_UNKNOWN);
expr->array_ref.element = element;
expr->array_ref.field = field;
expr->array_ref.entry = entry;
return expr;
}
ExprDef *
ExprCreateAction(xkb_atom_t name, ExprDef *args)
{
EXPR_CREATE(ExprAction, expr, EXPR_ACTION_DECL, EXPR_TYPE_UNKNOWN);
expr->action.name = name;
expr->action.args = args;
return expr;
}
ExprDef *
ExprCreateKeysymList(xkb_keysym_t sym)
{
EXPR_CREATE(ExprKeysymList, expr, EXPR_KEYSYM_LIST, EXPR_TYPE_SYMBOLS);
darray_init(expr->keysym_list.syms);
darray_init(expr->keysym_list.symsMapIndex);
darray_init(expr->keysym_list.symsNumEntries);
darray_append(expr->keysym_list.syms, sym);
darray_append(expr->keysym_list.symsMapIndex, 0);
darray_append(expr->keysym_list.symsNumEntries, 1);
return expr;
}
ExprDef *
ExprCreateMultiKeysymList(ExprDef *expr)
{
unsigned nLevels = darray_size(expr->keysym_list.symsMapIndex);
darray_resize(expr->keysym_list.symsMapIndex, 1);
darray_resize(expr->keysym_list.symsNumEntries, 1);
darray_item(expr->keysym_list.symsMapIndex, 0) = 0;
darray_item(expr->keysym_list.symsNumEntries, 0) = nLevels;
return expr;
}
ExprDef *
ExprAppendKeysymList(ExprDef *expr, xkb_keysym_t sym)
{
unsigned nSyms = darray_size(expr->keysym_list.syms);
darray_append(expr->keysym_list.symsMapIndex, nSyms);
darray_append(expr->keysym_list.symsNumEntries, 1);
darray_append(expr->keysym_list.syms, sym);
return expr;
}
ExprDef *
ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)
{
unsigned nSyms = darray_size(expr->keysym_list.syms);
unsigned numEntries = darray_size(append->keysym_list.syms);
darray_append(expr->keysym_list.symsMapIndex, nSyms);
darray_append(expr->keysym_list.symsNumEntries, numEntries);
darray_concat(expr->keysym_list.syms, append->keysym_list.syms);
FreeStmt((ParseCommon *) &append);
return expr;
}
KeycodeDef *
KeycodeCreate(xkb_atom_t name, int64_t value)
{
KeycodeDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_KEYCODE;
def->common.next = NULL;
def->name = name;
def->value = value;
return def;
}
KeyAliasDef *
KeyAliasCreate(xkb_atom_t alias, xkb_atom_t real)
{
KeyAliasDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_ALIAS;
def->common.next = NULL;
def->alias = alias;
def->real = real;
return def;
}
VModDef *
VModCreate(xkb_atom_t name, ExprDef *value)
{
VModDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_VMOD;
def->common.next = NULL;
def->name = name;
def->value = value;
return def;
}
VarDef *
VarCreate(ExprDef *name, ExprDef *value)
{
VarDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_VAR;
def->common.next = NULL;
def->name = name;
def->value = value;
return def;
}
VarDef *
BoolVarCreate(xkb_atom_t ident, bool set)
{
ExprDef *name, *value;
VarDef *def;
if (!(name = ExprCreateIdent(ident))) {
return NULL;
}
if (!(value = ExprCreateBoolean(set))) {
FreeStmt((ParseCommon *) name);
return NULL;
}
if (!(def = VarCreate(name, value))) {
FreeStmt((ParseCommon *) name);
FreeStmt((ParseCommon *) value);
return NULL;
}
return def;
}
InterpDef *
InterpCreate(xkb_keysym_t sym, ExprDef *match)
{
InterpDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_INTERP;
def->common.next = NULL;
def->sym = sym;
def->match = match;
def->def = NULL;
return def;
}
KeyTypeDef *
KeyTypeCreate(xkb_atom_t name, VarDef *body)
{
KeyTypeDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_TYPE;
def->common.next = NULL;
def->merge = MERGE_DEFAULT;
def->name = name;
def->body = body;
return def;
}
SymbolsDef *
SymbolsCreate(xkb_atom_t keyName, VarDef *symbols)
{
SymbolsDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_SYMBOLS;
def->common.next = NULL;
def->merge = MERGE_DEFAULT;
def->keyName = keyName;
def->symbols = symbols;
return def;
}
GroupCompatDef *
GroupCompatCreate(unsigned group, ExprDef *val)
{
GroupCompatDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_GROUP_COMPAT;
def->common.next = NULL;
def->merge = MERGE_DEFAULT;
def->group = group;
def->def = val;
return def;
}
ModMapDef *
ModMapCreate(xkb_atom_t modifier, ExprDef *keys)
{
ModMapDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_MODMAP;
def->common.next = NULL;
def->merge = MERGE_DEFAULT;
def->modifier = modifier;
def->keys = keys;
return def;
}
LedMapDef *
LedMapCreate(xkb_atom_t name, VarDef *body)
{
LedMapDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_LED_MAP;
def->common.next = NULL;
def->merge = MERGE_DEFAULT;
def->name = name;
def->body = body;
return def;
}
LedNameDef *
LedNameCreate(unsigned ndx, ExprDef *name, bool virtual)
{
LedNameDef *def = malloc(sizeof(*def));
if (!def)
return NULL;
def->common.type = STMT_LED_NAME;
def->common.next = NULL;
def->merge = MERGE_DEFAULT;
def->ndx = ndx;
def->name = name;
def->virtual = virtual;
return def;
}
static void
FreeInclude(IncludeStmt *incl);
IncludeStmt *
IncludeCreate(struct xkb_context *ctx, char *str, enum merge_mode merge)
{
IncludeStmt *incl, *first;
char *file, *map, *stmt, *tmp, *extra_data;
char nextop;
incl = first = NULL;
file = map = NULL;
tmp = str;
stmt = strdup_safe(str);
while (tmp && *tmp)
{
if (!ParseIncludeMap(&tmp, &file, &map, &nextop, &extra_data))
goto err;
/*
* Given an RMLVO (here layout) like 'us,,fr', the rules parser
* will give out something like 'pc+us+:2+fr:3+inet(evdev)'.
* We should just skip the ':2' in this case and leave it to the
* appropriate section to deal with the empty group.
*/
if (isempty(file)) {
free(file);
free(map);
free(extra_data);
continue;
}
if (first == NULL) {
first = incl = malloc(sizeof(*first));
} else {
incl->next_incl = malloc(sizeof(*first));
incl = incl->next_incl;
}
if (!incl)
break;
incl->common.type = STMT_INCLUDE;
incl->common.next = NULL;
incl->merge = merge;
incl->stmt = NULL;
incl->file = file;
incl->map = map;
incl->modifier = extra_data;
incl->next_incl = NULL;
if (nextop == '|')
merge = MERGE_AUGMENT;
else
merge = MERGE_OVERRIDE;
}
if (first)
first->stmt = stmt;
else
free(stmt);
return first;
err:
log_err(ctx, "Illegal include statement \"%s\"; Ignored\n", stmt);
FreeInclude(first);
free(stmt);
return NULL;
}
XkbFile *
XkbFileCreate(enum xkb_file_type type, char *name, ParseCommon *defs,
enum xkb_map_flags flags)
{
XkbFile *file;
file = calloc(1, sizeof(*file));
if (!file)
return NULL;
XkbEscapeMapName(name);
file->file_type = type;
file->name = name ? name : strdup("(unnamed)");
file->defs = defs;
file->flags = flags;
return file;
}
XkbFile *
XkbFileFromComponents(struct xkb_context *ctx,
const struct xkb_component_names *kkctgs)
{
char *const components[] = {
kkctgs->keycodes, kkctgs->types,
kkctgs->compat, kkctgs->symbols,
};
enum xkb_file_type type;
IncludeStmt *include = NULL;
XkbFile *file = NULL;
ParseCommon *defs = NULL;
for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) {
include = IncludeCreate(ctx, components[type], MERGE_DEFAULT);
if (!include)
goto err;
file = XkbFileCreate(type, NULL, (ParseCommon *) include, 0);
if (!file) {
FreeInclude(include);
goto err;
}
defs = AppendStmt(defs, &file->common);
}
file = XkbFileCreate(FILE_TYPE_KEYMAP, NULL, defs, 0);
if (!file)
goto err;
return file;
err:
FreeXkbFile((XkbFile *) defs);
return NULL;
}
static void
FreeExpr(ExprDef *expr)
{
if (!expr)
return;
switch (expr->expr.op) {
case EXPR_ACTION_LIST:
case EXPR_NEGATE:
case EXPR_UNARY_PLUS:
case EXPR_NOT:
case EXPR_INVERT:
FreeStmt((ParseCommon *) expr->unary.child);
break;
case EXPR_DIVIDE:
case EXPR_ADD:
case EXPR_SUBTRACT:
case EXPR_MULTIPLY:
case EXPR_ASSIGN:
FreeStmt((ParseCommon *) expr->binary.left);
FreeStmt((ParseCommon *) expr->binary.right);
break;
case EXPR_ACTION_DECL:
FreeStmt((ParseCommon *) expr->action.args);
break;
case EXPR_ARRAY_REF:
FreeStmt((ParseCommon *) expr->array_ref.entry);
break;
case EXPR_KEYSYM_LIST:
darray_free(expr->keysym_list.syms);
darray_free(expr->keysym_list.symsMapIndex);
darray_free(expr->keysym_list.symsNumEntries);
break;
default:
break;
}
}
static void
FreeInclude(IncludeStmt *incl)
{
IncludeStmt *next;
while (incl)
{
next = incl->next_incl;
free(incl->file);
free(incl->map);
free(incl->modifier);
free(incl->stmt);
free(incl);
incl = next;
}
}
void
FreeStmt(ParseCommon *stmt)
{
ParseCommon *next;
while (stmt)
{
next = stmt->next;
switch (stmt->type) {
case STMT_INCLUDE:
FreeInclude((IncludeStmt *) stmt);
/* stmt is already free'd here. */
stmt = NULL;
break;
case STMT_EXPR:
FreeExpr((ExprDef *) stmt);
break;
case STMT_VAR:
FreeStmt((ParseCommon *) ((VarDef *) stmt)->name);
FreeStmt((ParseCommon *) ((VarDef *) stmt)->value);
break;
case STMT_TYPE:
FreeStmt((ParseCommon *) ((KeyTypeDef *) stmt)->body);
break;
case STMT_INTERP:
FreeStmt((ParseCommon *) ((InterpDef *) stmt)->match);
FreeStmt((ParseCommon *) ((InterpDef *) stmt)->def);
break;
case STMT_VMOD:
FreeStmt((ParseCommon *) ((VModDef *) stmt)->value);
break;
case STMT_SYMBOLS:
FreeStmt((ParseCommon *) ((SymbolsDef *) stmt)->symbols);
break;
case STMT_MODMAP:
FreeStmt((ParseCommon *) ((ModMapDef *) stmt)->keys);
break;
case STMT_GROUP_COMPAT:
FreeStmt((ParseCommon *) ((GroupCompatDef *) stmt)->def);
break;
case STMT_LED_MAP:
FreeStmt((ParseCommon *) ((LedMapDef *) stmt)->body);
break;
case STMT_LED_NAME:
FreeStmt((ParseCommon *) ((LedNameDef *) stmt)->name);
break;
default:
break;
}
free(stmt);
stmt = next;
}
}
void
FreeXkbFile(XkbFile *file)
{
XkbFile *next;
while (file)
{
next = (XkbFile *) file->common.next;
switch (file->file_type) {
case FILE_TYPE_KEYMAP:
FreeXkbFile((XkbFile *) file->defs);
break;
case FILE_TYPE_TYPES:
case FILE_TYPE_COMPAT:
case FILE_TYPE_SYMBOLS:
case FILE_TYPE_KEYCODES:
case FILE_TYPE_GEOMETRY:
FreeStmt(file->defs);
break;
default:
break;
}
free(file->name);
free(file);
file = next;
}
}
static const char *xkb_file_type_strings[_FILE_TYPE_NUM_ENTRIES] = {
[FILE_TYPE_KEYCODES] = "xkb_keycodes",
[FILE_TYPE_TYPES] = "xkb_types",
[FILE_TYPE_COMPAT] = "xkb_compatibility",
[FILE_TYPE_SYMBOLS] = "xkb_symbols",
[FILE_TYPE_GEOMETRY] = "xkb_geometry",
[FILE_TYPE_KEYMAP] = "xkb_keymap",
[FILE_TYPE_RULES] = "rules",
};
const char *
xkb_file_type_to_string(enum xkb_file_type type)
{
if (type > _FILE_TYPE_NUM_ENTRIES)
return "unknown";
return xkb_file_type_strings[type];
}
static const char *stmt_type_strings[_STMT_NUM_VALUES] = {
[STMT_UNKNOWN] = "unknown statement",
[STMT_INCLUDE] = "include statement",
[STMT_KEYCODE] = "key name definition",
[STMT_ALIAS] = "key alias definition",
[STMT_EXPR] = "expression",
[STMT_VAR] = "variable definition",
[STMT_TYPE] = "key type definition",
[STMT_INTERP] = "symbol interpretation definition",
[STMT_VMOD] = "virtual modifiers definition",
[STMT_SYMBOLS] = "key symbols definition",
[STMT_MODMAP] = "modifier map declaration",
[STMT_GROUP_COMPAT] = "group declaration",
[STMT_LED_MAP] = "indicator map declaration",
[STMT_LED_NAME] = "indicator name declaration",
};
const char *
stmt_type_to_string(enum stmt_type type)
{
if (type >= _STMT_NUM_VALUES)
return NULL;
return stmt_type_strings[type];
}
static const char *expr_op_type_strings[_EXPR_NUM_VALUES] = {
[EXPR_VALUE] = "literal",
[EXPR_IDENT] = "identifier",
[EXPR_ACTION_DECL] = "action declaration",
[EXPR_FIELD_REF] = "field reference",
[EXPR_ARRAY_REF] = "array reference",
[EXPR_KEYSYM_LIST] = "list of keysyms",
[EXPR_ACTION_LIST] = "list of actions",
[EXPR_ADD] = "addition",
[EXPR_SUBTRACT] = "subtraction",
[EXPR_MULTIPLY] = "multiplication",
[EXPR_DIVIDE] = "division",
[EXPR_ASSIGN] = "assignment",
[EXPR_NOT] = "logical negation",
[EXPR_NEGATE] = "arithmetic negation",
[EXPR_INVERT] = "bitwise inversion",
[EXPR_UNARY_PLUS] = "unary plus",
};
const char *
expr_op_type_to_string(enum expr_op_type type)
{
if (type >= _EXPR_NUM_VALUES)
return NULL;
return expr_op_type_strings[type];
}
static const char *expr_value_type_strings[_EXPR_TYPE_NUM_VALUES] = {
[EXPR_TYPE_UNKNOWN] = "unknown",
[EXPR_TYPE_BOOLEAN] = "boolean",
[EXPR_TYPE_INT] = "int",
[EXPR_TYPE_STRING] = "string",
[EXPR_TYPE_ACTION] = "action",
[EXPR_TYPE_KEYNAME] = "keyname",
[EXPR_TYPE_SYMBOLS] = "symbols",
};
const char *
expr_value_type_to_string(enum expr_value_type type)
{
if (type >= _EXPR_TYPE_NUM_VALUES)
return NULL;
return expr_value_type_strings[type];
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_317_0 |
crossvul-cpp_data_bad_5410_0 | /* Large capacity key type
*
* Copyright (C) 2013 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/init.h>
#include <linux/seq_file.h>
#include <linux/file.h>
#include <linux/shmem_fs.h>
#include <linux/err.h>
#include <linux/scatterlist.h>
#include <keys/user-type.h>
#include <keys/big_key-type.h>
#include <crypto/rng.h>
#include <crypto/skcipher.h>
/*
* Layout of key payload words.
*/
enum {
big_key_data,
big_key_path,
big_key_path_2nd_part,
big_key_len,
};
/*
* Crypto operation with big_key data
*/
enum big_key_op {
BIG_KEY_ENC,
BIG_KEY_DEC,
};
/*
* If the data is under this limit, there's no point creating a shm file to
* hold it as the permanently resident metadata for the shmem fs will be at
* least as large as the data.
*/
#define BIG_KEY_FILE_THRESHOLD (sizeof(struct inode) + sizeof(struct dentry))
/*
* Key size for big_key data encryption
*/
#define ENC_KEY_SIZE 16
/*
* big_key defined keys take an arbitrary string as the description and an
* arbitrary blob of data as the payload
*/
struct key_type key_type_big_key = {
.name = "big_key",
.preparse = big_key_preparse,
.free_preparse = big_key_free_preparse,
.instantiate = generic_key_instantiate,
.revoke = big_key_revoke,
.destroy = big_key_destroy,
.describe = big_key_describe,
.read = big_key_read,
};
/*
* Crypto names for big_key data encryption
*/
static const char big_key_rng_name[] = "stdrng";
static const char big_key_alg_name[] = "ecb(aes)";
/*
* Crypto algorithms for big_key data encryption
*/
static struct crypto_rng *big_key_rng;
static struct crypto_skcipher *big_key_skcipher;
/*
* Generate random key to encrypt big_key data
*/
static inline int big_key_gen_enckey(u8 *key)
{
return crypto_rng_get_bytes(big_key_rng, key, ENC_KEY_SIZE);
}
/*
* Encrypt/decrypt big_key data
*/
static int big_key_crypt(enum big_key_op op, u8 *data, size_t datalen, u8 *key)
{
int ret = -EINVAL;
struct scatterlist sgio;
SKCIPHER_REQUEST_ON_STACK(req, big_key_skcipher);
if (crypto_skcipher_setkey(big_key_skcipher, key, ENC_KEY_SIZE)) {
ret = -EAGAIN;
goto error;
}
skcipher_request_set_tfm(req, big_key_skcipher);
skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP,
NULL, NULL);
sg_init_one(&sgio, data, datalen);
skcipher_request_set_crypt(req, &sgio, &sgio, datalen, NULL);
if (op == BIG_KEY_ENC)
ret = crypto_skcipher_encrypt(req);
else
ret = crypto_skcipher_decrypt(req);
skcipher_request_zero(req);
error:
return ret;
}
/*
* Preparse a big key
*/
int big_key_preparse(struct key_preparsed_payload *prep)
{
struct path *path = (struct path *)&prep->payload.data[big_key_path];
struct file *file;
u8 *enckey;
u8 *data = NULL;
ssize_t written;
size_t datalen = prep->datalen;
int ret;
ret = -EINVAL;
if (datalen <= 0 || datalen > 1024 * 1024 || !prep->data)
goto error;
/* Set an arbitrary quota */
prep->quotalen = 16;
prep->payload.data[big_key_len] = (void *)(unsigned long)datalen;
if (datalen > BIG_KEY_FILE_THRESHOLD) {
/* Create a shmem file to store the data in. This will permit the data
* to be swapped out if needed.
*
* File content is stored encrypted with randomly generated key.
*/
size_t enclen = ALIGN(datalen, crypto_skcipher_blocksize(big_key_skcipher));
/* prepare aligned data to encrypt */
data = kmalloc(enclen, GFP_KERNEL);
if (!data)
return -ENOMEM;
memcpy(data, prep->data, datalen);
memset(data + datalen, 0x00, enclen - datalen);
/* generate random key */
enckey = kmalloc(ENC_KEY_SIZE, GFP_KERNEL);
if (!enckey) {
ret = -ENOMEM;
goto error;
}
ret = big_key_gen_enckey(enckey);
if (ret)
goto err_enckey;
/* encrypt aligned data */
ret = big_key_crypt(BIG_KEY_ENC, data, enclen, enckey);
if (ret)
goto err_enckey;
/* save aligned data to file */
file = shmem_kernel_file_setup("", enclen, 0);
if (IS_ERR(file)) {
ret = PTR_ERR(file);
goto err_enckey;
}
written = kernel_write(file, data, enclen, 0);
if (written != enclen) {
ret = written;
if (written >= 0)
ret = -ENOMEM;
goto err_fput;
}
/* Pin the mount and dentry to the key so that we can open it again
* later
*/
prep->payload.data[big_key_data] = enckey;
*path = file->f_path;
path_get(path);
fput(file);
kfree(data);
} else {
/* Just store the data in a buffer */
void *data = kmalloc(datalen, GFP_KERNEL);
if (!data)
return -ENOMEM;
prep->payload.data[big_key_data] = data;
memcpy(data, prep->data, prep->datalen);
}
return 0;
err_fput:
fput(file);
err_enckey:
kfree(enckey);
error:
kfree(data);
return ret;
}
/*
* Clear preparsement.
*/
void big_key_free_preparse(struct key_preparsed_payload *prep)
{
if (prep->datalen > BIG_KEY_FILE_THRESHOLD) {
struct path *path = (struct path *)&prep->payload.data[big_key_path];
path_put(path);
}
kfree(prep->payload.data[big_key_data]);
}
/*
* dispose of the links from a revoked keyring
* - called with the key sem write-locked
*/
void big_key_revoke(struct key *key)
{
struct path *path = (struct path *)&key->payload.data[big_key_path];
/* clear the quota */
key_payload_reserve(key, 0);
if (key_is_instantiated(key) &&
(size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD)
vfs_truncate(path, 0);
}
/*
* dispose of the data dangling from the corpse of a big_key key
*/
void big_key_destroy(struct key *key)
{
size_t datalen = (size_t)key->payload.data[big_key_len];
if (datalen > BIG_KEY_FILE_THRESHOLD) {
struct path *path = (struct path *)&key->payload.data[big_key_path];
path_put(path);
path->mnt = NULL;
path->dentry = NULL;
}
kfree(key->payload.data[big_key_data]);
key->payload.data[big_key_data] = NULL;
}
/*
* describe the big_key key
*/
void big_key_describe(const struct key *key, struct seq_file *m)
{
size_t datalen = (size_t)key->payload.data[big_key_len];
seq_puts(m, key->description);
if (key_is_instantiated(key))
seq_printf(m, ": %zu [%s]",
datalen,
datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff");
}
/*
* read the key data
* - the key's semaphore is read-locked
*/
long big_key_read(const struct key *key, char __user *buffer, size_t buflen)
{
size_t datalen = (size_t)key->payload.data[big_key_len];
long ret;
if (!buffer || buflen < datalen)
return datalen;
if (datalen > BIG_KEY_FILE_THRESHOLD) {
struct path *path = (struct path *)&key->payload.data[big_key_path];
struct file *file;
u8 *data;
u8 *enckey = (u8 *)key->payload.data[big_key_data];
size_t enclen = ALIGN(datalen, crypto_skcipher_blocksize(big_key_skcipher));
data = kmalloc(enclen, GFP_KERNEL);
if (!data)
return -ENOMEM;
file = dentry_open(path, O_RDONLY, current_cred());
if (IS_ERR(file)) {
ret = PTR_ERR(file);
goto error;
}
/* read file to kernel and decrypt */
ret = kernel_read(file, 0, data, enclen);
if (ret >= 0 && ret != enclen) {
ret = -EIO;
goto err_fput;
}
ret = big_key_crypt(BIG_KEY_DEC, data, enclen, enckey);
if (ret)
goto err_fput;
ret = datalen;
/* copy decrypted data to user */
if (copy_to_user(buffer, data, datalen) != 0)
ret = -EFAULT;
err_fput:
fput(file);
error:
kfree(data);
} else {
ret = datalen;
if (copy_to_user(buffer, key->payload.data[big_key_data],
datalen) != 0)
ret = -EFAULT;
}
return ret;
}
/*
* Register key type
*/
static int __init big_key_init(void)
{
return register_key_type(&key_type_big_key);
}
/*
* Initialize big_key crypto and RNG algorithms
*/
static int __init big_key_crypto_init(void)
{
int ret = -EINVAL;
/* init RNG */
big_key_rng = crypto_alloc_rng(big_key_rng_name, 0, 0);
if (IS_ERR(big_key_rng)) {
big_key_rng = NULL;
return -EFAULT;
}
/* seed RNG */
ret = crypto_rng_reset(big_key_rng, NULL, crypto_rng_seedsize(big_key_rng));
if (ret)
goto error;
/* init block cipher */
big_key_skcipher = crypto_alloc_skcipher(big_key_alg_name,
0, CRYPTO_ALG_ASYNC);
if (IS_ERR(big_key_skcipher)) {
big_key_skcipher = NULL;
ret = -EFAULT;
goto error;
}
return 0;
error:
crypto_free_rng(big_key_rng);
big_key_rng = NULL;
return ret;
}
device_initcall(big_key_init);
late_initcall(big_key_crypto_init);
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_5410_0 |
crossvul-cpp_data_good_914_0 | /**********************************************************************
regcomp.c - Oniguruma (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2019 K.Kosako <sndgk393 AT ybb DOT ne DOT jp>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "regparse.h"
#define OPS_INIT_SIZE 8
OnigCaseFoldType OnigDefaultCaseFoldFlag = ONIGENC_CASE_FOLD_MIN;
#if 0
typedef struct {
int n;
int alloc;
int* v;
} int_stack;
static int
make_int_stack(int_stack** rs, int init_size)
{
int_stack* s;
int* v;
*rs = 0;
s = xmalloc(sizeof(*s));
if (IS_NULL(s)) return ONIGERR_MEMORY;
v = (int* )xmalloc(sizeof(int) * init_size);
if (IS_NULL(v)) {
xfree(s);
return ONIGERR_MEMORY;
}
s->n = 0;
s->alloc = init_size;
s->v = v;
*rs = s;
return ONIG_NORMAL;
}
static void
free_int_stack(int_stack* s)
{
if (IS_NOT_NULL(s)) {
if (IS_NOT_NULL(s->v))
xfree(s->v);
xfree(s);
}
}
static int
int_stack_push(int_stack* s, int v)
{
if (s->n >= s->alloc) {
int new_size = s->alloc * 2;
int* nv = (int* )xrealloc(s->v, sizeof(int) * new_size);
if (IS_NULL(nv)) return ONIGERR_MEMORY;
s->alloc = new_size;
s->v = nv;
}
s->v[s->n] = v;
s->n++;
return ONIG_NORMAL;
}
static int
int_stack_pop(int_stack* s)
{
int v;
#ifdef ONIG_DEBUG
if (s->n <= 0) {
fprintf(stderr, "int_stack_pop: fail empty. %p\n", s);
return 0;
}
#endif
v = s->v[s->n];
s->n--;
return v;
}
#endif
static int
ops_init(regex_t* reg, int init_alloc_size)
{
Operation* p;
size_t size;
if (init_alloc_size > 0) {
size = sizeof(Operation) * init_alloc_size;
p = (Operation* )xrealloc(reg->ops, size);
CHECK_NULL_RETURN_MEMERR(p);
#ifdef USE_DIRECT_THREADED_CODE
{
enum OpCode* cp;
size = sizeof(enum OpCode) * init_alloc_size;
cp = (enum OpCode* )xrealloc(reg->ocs, size);
CHECK_NULL_RETURN_MEMERR(cp);
reg->ocs = cp;
}
#endif
}
else {
p = (Operation* )0;
#ifdef USE_DIRECT_THREADED_CODE
reg->ocs = (enum OpCode* )0;
#endif
}
reg->ops = p;
reg->ops_curr = 0; /* !!! not yet done ops_new() */
reg->ops_alloc = init_alloc_size;
reg->ops_used = 0;
return ONIG_NORMAL;
}
static int
ops_expand(regex_t* reg, int n)
{
#define MIN_OPS_EXPAND_SIZE 4
#ifdef USE_DIRECT_THREADED_CODE
enum OpCode* cp;
#endif
Operation* p;
size_t size;
if (n <= 0) n = MIN_OPS_EXPAND_SIZE;
n += reg->ops_alloc;
size = sizeof(Operation) * n;
p = (Operation* )xrealloc(reg->ops, size);
CHECK_NULL_RETURN_MEMERR(p);
#ifdef USE_DIRECT_THREADED_CODE
size = sizeof(enum OpCode) * n;
cp = (enum OpCode* )xrealloc(reg->ocs, size);
CHECK_NULL_RETURN_MEMERR(cp);
reg->ocs = cp;
#endif
reg->ops = p;
reg->ops_alloc = n;
if (reg->ops_used == 0)
reg->ops_curr = 0;
else
reg->ops_curr = reg->ops + (reg->ops_used - 1);
return ONIG_NORMAL;
}
static int
ops_new(regex_t* reg)
{
int r;
if (reg->ops_used >= reg->ops_alloc) {
r = ops_expand(reg, reg->ops_alloc);
if (r != ONIG_NORMAL) return r;
}
reg->ops_curr = reg->ops + reg->ops_used;
reg->ops_used++;
xmemset(reg->ops_curr, 0, sizeof(Operation));
return ONIG_NORMAL;
}
static int
is_in_string_pool(regex_t* reg, UChar* s)
{
return (s >= reg->string_pool && s < reg->string_pool_end);
}
static void
ops_free(regex_t* reg)
{
int i;
if (IS_NULL(reg->ops)) return ;
for (i = 0; i < (int )reg->ops_used; i++) {
enum OpCode opcode;
Operation* op;
op = reg->ops + i;
#ifdef USE_DIRECT_THREADED_CODE
opcode = *(reg->ocs + i);
#else
opcode = op->opcode;
#endif
switch (opcode) {
case OP_EXACTMBN:
if (! is_in_string_pool(reg, op->exact_len_n.s))
xfree(op->exact_len_n.s);
break;
case OP_EXACTN: case OP_EXACTMB2N: case OP_EXACTMB3N: case OP_EXACTN_IC:
if (! is_in_string_pool(reg, op->exact_n.s))
xfree(op->exact_n.s);
break;
case OP_EXACT1: case OP_EXACT2: case OP_EXACT3: case OP_EXACT4:
case OP_EXACT5: case OP_EXACTMB2N1: case OP_EXACTMB2N2:
case OP_EXACTMB2N3: case OP_EXACT1_IC:
break;
case OP_CCLASS_NOT: case OP_CCLASS:
xfree(op->cclass.bsp);
break;
case OP_CCLASS_MB_NOT: case OP_CCLASS_MB:
xfree(op->cclass_mb.mb);
break;
case OP_CCLASS_MIX_NOT: case OP_CCLASS_MIX:
xfree(op->cclass_mix.mb);
xfree(op->cclass_mix.bsp);
break;
case OP_BACKREF1: case OP_BACKREF2: case OP_BACKREF_N: case OP_BACKREF_N_IC:
break;
case OP_BACKREF_MULTI: case OP_BACKREF_MULTI_IC:
case OP_BACKREF_WITH_LEVEL:
case OP_BACKREF_WITH_LEVEL_IC:
case OP_BACKREF_CHECK:
case OP_BACKREF_CHECK_WITH_LEVEL:
if (op->backref_general.num != 1)
xfree(op->backref_general.ns);
break;
default:
break;
}
}
xfree(reg->ops);
#ifdef USE_DIRECT_THREADED_CODE
xfree(reg->ocs);
reg->ocs = 0;
#endif
reg->ops = 0;
reg->ops_curr = 0;
reg->ops_alloc = 0;
reg->ops_used = 0;
}
static int
ops_calc_size_of_string_pool(regex_t* reg)
{
int i;
int total;
if (IS_NULL(reg->ops)) return 0;
total = 0;
for (i = 0; i < (int )reg->ops_used; i++) {
enum OpCode opcode;
Operation* op;
op = reg->ops + i;
#ifdef USE_DIRECT_THREADED_CODE
opcode = *(reg->ocs + i);
#else
opcode = op->opcode;
#endif
switch (opcode) {
case OP_EXACTMBN:
total += op->exact_len_n.len * op->exact_len_n.n;
break;
case OP_EXACTN:
case OP_EXACTN_IC:
total += op->exact_n.n;
break;
case OP_EXACTMB2N:
total += op->exact_n.n * 2;
break;
case OP_EXACTMB3N:
total += op->exact_n.n * 3;
break;
default:
break;
}
}
return total;
}
static int
ops_make_string_pool(regex_t* reg)
{
int i;
int len;
int size;
UChar* pool;
UChar* curr;
size = ops_calc_size_of_string_pool(reg);
if (size <= 0) {
return 0;
}
curr = pool = (UChar* )xmalloc((size_t )size);
CHECK_NULL_RETURN_MEMERR(pool);
for (i = 0; i < (int )reg->ops_used; i++) {
enum OpCode opcode;
Operation* op;
op = reg->ops + i;
#ifdef USE_DIRECT_THREADED_CODE
opcode = *(reg->ocs + i);
#else
opcode = op->opcode;
#endif
switch (opcode) {
case OP_EXACTMBN:
len = op->exact_len_n.len * op->exact_len_n.n;
xmemcpy(curr, op->exact_len_n.s, len);
xfree(op->exact_len_n.s);
op->exact_len_n.s = curr;
curr += len;
break;
case OP_EXACTN:
case OP_EXACTN_IC:
len = op->exact_n.n;
copy:
xmemcpy(curr, op->exact_n.s, len);
xfree(op->exact_n.s);
op->exact_n.s = curr;
curr += len;
break;
case OP_EXACTMB2N:
len = op->exact_n.n * 2;
goto copy;
break;
case OP_EXACTMB3N:
len = op->exact_n.n * 3;
goto copy;
break;
default:
break;
}
}
reg->string_pool = pool;
reg->string_pool_end = pool + size;
return 0;
}
extern OnigCaseFoldType
onig_get_default_case_fold_flag(void)
{
return OnigDefaultCaseFoldFlag;
}
extern int
onig_set_default_case_fold_flag(OnigCaseFoldType case_fold_flag)
{
OnigDefaultCaseFoldFlag = case_fold_flag;
return 0;
}
static int
int_multiply_cmp(int x, int y, int v)
{
if (x == 0 || y == 0) return -1;
if (x < INT_MAX / y) {
int xy = x * y;
if (xy > v) return 1;
else {
if (xy == v) return 0;
else return -1;
}
}
else
return 1;
}
extern int
onig_positive_int_multiply(int x, int y)
{
if (x == 0 || y == 0) return 0;
if (x < INT_MAX / y)
return x * y;
else
return -1;
}
static void
swap_node(Node* a, Node* b)
{
Node c;
c = *a; *a = *b; *b = c;
if (NODE_TYPE(a) == NODE_STRING) {
StrNode* sn = STR_(a);
if (sn->capacity == 0) {
int len = (int )(sn->end - sn->s);
sn->s = sn->buf;
sn->end = sn->s + len;
}
}
if (NODE_TYPE(b) == NODE_STRING) {
StrNode* sn = STR_(b);
if (sn->capacity == 0) {
int len = (int )(sn->end - sn->s);
sn->s = sn->buf;
sn->end = sn->s + len;
}
}
}
static OnigLen
distance_add(OnigLen d1, OnigLen d2)
{
if (d1 == INFINITE_LEN || d2 == INFINITE_LEN)
return INFINITE_LEN;
else {
if (d1 <= INFINITE_LEN - d2) return d1 + d2;
else return INFINITE_LEN;
}
}
static OnigLen
distance_multiply(OnigLen d, int m)
{
if (m == 0) return 0;
if (d < INFINITE_LEN / m)
return d * m;
else
return INFINITE_LEN;
}
static int
bitset_is_empty(BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) {
if (bs[i] != 0) return 0;
}
return 1;
}
#ifdef USE_CALL
static int
unset_addr_list_init(UnsetAddrList* list, int size)
{
UnsetAddr* p = (UnsetAddr* )xmalloc(sizeof(UnsetAddr)* size);
CHECK_NULL_RETURN_MEMERR(p);
list->num = 0;
list->alloc = size;
list->us = p;
return 0;
}
static void
unset_addr_list_end(UnsetAddrList* list)
{
if (IS_NOT_NULL(list->us))
xfree(list->us);
}
static int
unset_addr_list_add(UnsetAddrList* list, int offset, struct _Node* node)
{
UnsetAddr* p;
int size;
if (list->num >= list->alloc) {
size = list->alloc * 2;
p = (UnsetAddr* )xrealloc(list->us, sizeof(UnsetAddr) * size);
CHECK_NULL_RETURN_MEMERR(p);
list->alloc = size;
list->us = p;
}
list->us[list->num].offset = offset;
list->us[list->num].target = node;
list->num++;
return 0;
}
#endif /* USE_CALL */
static int
add_op(regex_t* reg, int opcode)
{
int r;
r = ops_new(reg);
if (r != ONIG_NORMAL) return r;
#ifdef USE_DIRECT_THREADED_CODE
*(reg->ocs + (reg->ops_curr - reg->ops)) = opcode;
#else
reg->ops_curr->opcode = opcode;
#endif
return 0;
}
static int compile_length_tree(Node* node, regex_t* reg);
static int compile_tree(Node* node, regex_t* reg, ScanEnv* env);
#define IS_NEED_STR_LEN_OP_EXACT(op) \
((op) == OP_EXACTN || (op) == OP_EXACTMB2N ||\
(op) == OP_EXACTMB3N || (op) == OP_EXACTMBN || (op) == OP_EXACTN_IC)
static int
select_str_opcode(int mb_len, int str_len, int ignore_case)
{
int op;
if (ignore_case) {
switch (str_len) {
case 1: op = OP_EXACT1_IC; break;
default: op = OP_EXACTN_IC; break;
}
}
else {
switch (mb_len) {
case 1:
switch (str_len) {
case 1: op = OP_EXACT1; break;
case 2: op = OP_EXACT2; break;
case 3: op = OP_EXACT3; break;
case 4: op = OP_EXACT4; break;
case 5: op = OP_EXACT5; break;
default: op = OP_EXACTN; break;
}
break;
case 2:
switch (str_len) {
case 1: op = OP_EXACTMB2N1; break;
case 2: op = OP_EXACTMB2N2; break;
case 3: op = OP_EXACTMB2N3; break;
default: op = OP_EXACTMB2N; break;
}
break;
case 3:
op = OP_EXACTMB3N;
break;
default:
op = OP_EXACTMBN;
break;
}
}
return op;
}
static int
compile_tree_empty_check(Node* node, regex_t* reg, int empty_info, ScanEnv* env)
{
int r;
int saved_num_null_check = reg->num_null_check;
if (empty_info != BODY_IS_NOT_EMPTY) {
r = add_op(reg, OP_EMPTY_CHECK_START);
if (r != 0) return r;
COP(reg)->empty_check_start.mem = reg->num_null_check; /* NULL CHECK ID */
reg->num_null_check++;
}
r = compile_tree(node, reg, env);
if (r != 0) return r;
if (empty_info != BODY_IS_NOT_EMPTY) {
if (empty_info == BODY_IS_EMPTY)
r = add_op(reg, OP_EMPTY_CHECK_END);
else if (empty_info == BODY_IS_EMPTY_MEM)
r = add_op(reg, OP_EMPTY_CHECK_END_MEMST);
else if (empty_info == BODY_IS_EMPTY_REC)
r = add_op(reg, OP_EMPTY_CHECK_END_MEMST_PUSH);
if (r != 0) return r;
COP(reg)->empty_check_end.mem = saved_num_null_check; /* NULL CHECK ID */
}
return r;
}
#ifdef USE_CALL
static int
compile_call(CallNode* node, regex_t* reg, ScanEnv* env)
{
int r;
int offset;
r = add_op(reg, OP_CALL);
if (r != 0) return r;
COP(reg)->call.addr = 0; /* dummy addr. */
offset = COP_CURR_OFFSET_BYTES(reg, call.addr);
r = unset_addr_list_add(env->unset_addr_list, offset, NODE_CALL_BODY(node));
return r;
}
#endif
static int
compile_tree_n_times(Node* node, int n, regex_t* reg, ScanEnv* env)
{
int i, r;
for (i = 0; i < n; i++) {
r = compile_tree(node, reg, env);
if (r != 0) return r;
}
return 0;
}
static int
add_compile_string_length(UChar* s ARG_UNUSED, int mb_len, int str_len,
regex_t* reg ARG_UNUSED, int ignore_case)
{
return 1;
}
static int
add_compile_string(UChar* s, int mb_len, int str_len,
regex_t* reg, int ignore_case)
{
int op;
int r;
int byte_len;
UChar* p;
UChar* end;
op = select_str_opcode(mb_len, str_len, ignore_case);
r = add_op(reg, op);
if (r != 0) return r;
byte_len = mb_len * str_len;
end = s + byte_len;
if (op == OP_EXACTMBN) {
p = onigenc_strdup(reg->enc, s, end);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->exact_len_n.len = mb_len;
COP(reg)->exact_len_n.n = str_len;
COP(reg)->exact_len_n.s = p;
}
else if (IS_NEED_STR_LEN_OP_EXACT(op)) {
p = onigenc_strdup(reg->enc, s, end);
CHECK_NULL_RETURN_MEMERR(p);
if (op == OP_EXACTN_IC)
COP(reg)->exact_n.n = byte_len;
else
COP(reg)->exact_n.n = str_len;
COP(reg)->exact_n.s = p;
}
else {
xmemcpy(COP(reg)->exact.s, s, (size_t )byte_len);
COP(reg)->exact.s[byte_len] = '\0';
}
return 0;
}
static int
compile_length_string_node(Node* node, regex_t* reg)
{
int rlen, r, len, prev_len, slen, ambig;
UChar *p, *prev;
StrNode* sn;
OnigEncoding enc = reg->enc;
sn = STR_(node);
if (sn->end <= sn->s)
return 0;
ambig = NODE_STRING_IS_AMBIG(node);
p = prev = sn->s;
prev_len = enclen(enc, p);
p += prev_len;
slen = 1;
rlen = 0;
for (; p < sn->end; ) {
len = enclen(enc, p);
if (len == prev_len) {
slen++;
}
else {
r = add_compile_string_length(prev, prev_len, slen, reg, ambig);
rlen += r;
prev = p;
slen = 1;
prev_len = len;
}
p += len;
}
r = add_compile_string_length(prev, prev_len, slen, reg, ambig);
rlen += r;
return rlen;
}
static int
compile_length_string_raw_node(StrNode* sn, regex_t* reg)
{
if (sn->end <= sn->s)
return 0;
return add_compile_string_length(sn->s, 1 /* sb */, (int )(sn->end - sn->s),
reg, 0);
}
static int
compile_string_node(Node* node, regex_t* reg)
{
int r, len, prev_len, slen, ambig;
UChar *p, *prev, *end;
StrNode* sn;
OnigEncoding enc = reg->enc;
sn = STR_(node);
if (sn->end <= sn->s)
return 0;
end = sn->end;
ambig = NODE_STRING_IS_AMBIG(node);
p = prev = sn->s;
prev_len = enclen(enc, p);
p += prev_len;
slen = 1;
for (; p < end; ) {
len = enclen(enc, p);
if (len == prev_len) {
slen++;
}
else {
r = add_compile_string(prev, prev_len, slen, reg, ambig);
if (r != 0) return r;
prev = p;
slen = 1;
prev_len = len;
}
p += len;
}
return add_compile_string(prev, prev_len, slen, reg, ambig);
}
static int
compile_string_raw_node(StrNode* sn, regex_t* reg)
{
if (sn->end <= sn->s)
return 0;
return add_compile_string(sn->s, 1 /* sb */, (int )(sn->end - sn->s), reg, 0);
}
static void*
set_multi_byte_cclass(BBuf* mbuf, regex_t* reg)
{
size_t len;
void* p;
len = (size_t )mbuf->used;
p = xmalloc(len);
if (IS_NULL(p)) return NULL;
xmemcpy(p, mbuf->p, len);
return p;
}
static int
compile_length_cclass_node(CClassNode* cc, regex_t* reg)
{
return 1;
}
static int
compile_cclass_node(CClassNode* cc, regex_t* reg)
{
int r;
if (IS_NULL(cc->mbuf)) {
r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_NOT : OP_CCLASS);
if (r != 0) return r;
COP(reg)->cclass.bsp = xmalloc(SIZE_BITSET);
CHECK_NULL_RETURN_MEMERR(COP(reg)->cclass.bsp);
xmemcpy(COP(reg)->cclass.bsp, cc->bs, SIZE_BITSET);
}
else {
void* p;
if (ONIGENC_MBC_MINLEN(reg->enc) > 1 || bitset_is_empty(cc->bs)) {
r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_MB_NOT : OP_CCLASS_MB);
if (r != 0) return r;
p = set_multi_byte_cclass(cc->mbuf, reg);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->cclass_mb.mb = p;
}
else {
r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_MIX_NOT : OP_CCLASS_MIX);
if (r != 0) return r;
COP(reg)->cclass_mix.bsp = xmalloc(SIZE_BITSET);
CHECK_NULL_RETURN_MEMERR(COP(reg)->cclass_mix.bsp);
xmemcpy(COP(reg)->cclass_mix.bsp, cc->bs, SIZE_BITSET);
p = set_multi_byte_cclass(cc->mbuf, reg);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->cclass_mix.mb = p;
}
}
return 0;
}
static int
entry_repeat_range(regex_t* reg, int id, int lower, int upper)
{
#define REPEAT_RANGE_ALLOC 4
OnigRepeatRange* p;
if (reg->repeat_range_alloc == 0) {
p = (OnigRepeatRange* )xmalloc(sizeof(OnigRepeatRange) * REPEAT_RANGE_ALLOC);
CHECK_NULL_RETURN_MEMERR(p);
reg->repeat_range = p;
reg->repeat_range_alloc = REPEAT_RANGE_ALLOC;
}
else if (reg->repeat_range_alloc <= id) {
int n;
n = reg->repeat_range_alloc + REPEAT_RANGE_ALLOC;
p = (OnigRepeatRange* )xrealloc(reg->repeat_range, sizeof(OnigRepeatRange) * n);
CHECK_NULL_RETURN_MEMERR(p);
reg->repeat_range = p;
reg->repeat_range_alloc = n;
}
else {
p = reg->repeat_range;
}
p[id].lower = lower;
p[id].upper = (IS_REPEAT_INFINITE(upper) ? 0x7fffffff : upper);
return 0;
}
static int
compile_range_repeat_node(QuantNode* qn, int target_len, int empty_info,
regex_t* reg, ScanEnv* env)
{
int r;
int num_repeat = reg->num_repeat++;
r = add_op(reg, qn->greedy ? OP_REPEAT : OP_REPEAT_NG);
if (r != 0) return r;
COP(reg)->repeat.id = num_repeat;
COP(reg)->repeat.addr = SIZE_INC_OP + target_len + SIZE_OP_REPEAT_INC;
r = entry_repeat_range(reg, num_repeat, qn->lower, qn->upper);
if (r != 0) return r;
r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env);
if (r != 0) return r;
if (
#ifdef USE_CALL
NODE_IS_IN_MULTI_ENTRY(qn) ||
#endif
NODE_IS_IN_REAL_REPEAT(qn)) {
r = add_op(reg, qn->greedy ? OP_REPEAT_INC_SG : OP_REPEAT_INC_NG_SG);
}
else {
r = add_op(reg, qn->greedy ? OP_REPEAT_INC : OP_REPEAT_INC_NG);
}
if (r != 0) return r;
COP(reg)->repeat_inc.id = num_repeat;
return r;
}
static int
is_anychar_infinite_greedy(QuantNode* qn)
{
if (qn->greedy && IS_REPEAT_INFINITE(qn->upper) &&
NODE_IS_ANYCHAR(NODE_QUANT_BODY(qn)))
return 1;
else
return 0;
}
#define QUANTIFIER_EXPAND_LIMIT_SIZE 10
#define CKN_ON (ckn > 0)
static int
compile_length_quantifier_node(QuantNode* qn, regex_t* reg)
{
int len, mod_tlen;
int infinite = IS_REPEAT_INFINITE(qn->upper);
enum BodyEmpty empty_info = qn->empty_info;
int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
if (tlen == 0) return 0;
/* anychar repeat */
if (is_anychar_infinite_greedy(qn)) {
if (qn->lower <= 1 ||
int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0) {
if (IS_NOT_NULL(qn->next_head_exact))
return SIZE_OP_ANYCHAR_STAR_PEEK_NEXT + tlen * qn->lower;
else
return SIZE_OP_ANYCHAR_STAR + tlen * qn->lower;
}
}
if (empty_info == BODY_IS_NOT_EMPTY)
mod_tlen = tlen;
else
mod_tlen = tlen + (SIZE_OP_EMPTY_CHECK_START + SIZE_OP_EMPTY_CHECK_END);
if (infinite &&
(qn->lower <= 1 ||
int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) {
len = SIZE_OP_JUMP;
}
else {
len = tlen * qn->lower;
}
if (qn->greedy) {
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
if (IS_NOT_NULL(qn->head_exact))
len += SIZE_OP_PUSH_OR_JUMP_EXACT1 + mod_tlen + SIZE_OP_JUMP;
else
#endif
if (IS_NOT_NULL(qn->next_head_exact))
len += SIZE_OP_PUSH_IF_PEEK_NEXT + mod_tlen + SIZE_OP_JUMP;
else
len += SIZE_OP_PUSH + mod_tlen + SIZE_OP_JUMP;
}
else
len += SIZE_OP_JUMP + mod_tlen + SIZE_OP_PUSH;
}
else if (qn->upper == 0) {
if (qn->is_refered != 0) { /* /(?<n>..){0}/ */
len = SIZE_OP_JUMP + tlen;
}
else
len = 0;
}
else if (!infinite && qn->greedy &&
(qn->upper == 1 ||
int_multiply_cmp(tlen + SIZE_OP_PUSH, qn->upper,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
len = tlen * qn->lower;
len += (SIZE_OP_PUSH + tlen) * (qn->upper - qn->lower);
}
else if (!qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */
len = SIZE_OP_PUSH + SIZE_OP_JUMP + tlen;
}
else {
len = SIZE_OP_REPEAT_INC + mod_tlen + SIZE_OP_REPEAT;
}
return len;
}
static int
compile_quantifier_node(QuantNode* qn, regex_t* reg, ScanEnv* env)
{
int i, r, mod_tlen;
int infinite = IS_REPEAT_INFINITE(qn->upper);
enum BodyEmpty empty_info = qn->empty_info;
int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
if (tlen == 0) return 0;
if (is_anychar_infinite_greedy(qn) &&
(qn->lower <= 1 ||
int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
if (IS_NOT_NULL(qn->next_head_exact)) {
r = add_op(reg,
IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), reg)) ?
OP_ANYCHAR_ML_STAR_PEEK_NEXT : OP_ANYCHAR_STAR_PEEK_NEXT);
if (r != 0) return r;
COP(reg)->anychar_star_peek_next.c = STR_(qn->next_head_exact)->s[0];
return 0;
}
else {
r = add_op(reg,
IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), reg)) ?
OP_ANYCHAR_ML_STAR : OP_ANYCHAR_STAR);
return r;
}
}
if (empty_info == BODY_IS_NOT_EMPTY)
mod_tlen = tlen;
else
mod_tlen = tlen + (SIZE_OP_EMPTY_CHECK_START + SIZE_OP_EMPTY_CHECK_END);
if (infinite &&
(qn->lower <= 1 ||
int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
int addr;
if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) {
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
if (qn->greedy) {
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
if (IS_NOT_NULL(qn->head_exact))
COP(reg)->jump.addr = SIZE_OP_PUSH_OR_JUMP_EXACT1 + SIZE_INC_OP;
else
#endif
if (IS_NOT_NULL(qn->next_head_exact))
COP(reg)->jump.addr = SIZE_OP_PUSH_IF_PEEK_NEXT + SIZE_INC_OP;
else
COP(reg)->jump.addr = SIZE_OP_PUSH + SIZE_INC_OP;
}
else {
COP(reg)->jump.addr = SIZE_OP_JUMP + SIZE_INC_OP;
}
}
else {
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
}
if (qn->greedy) {
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
if (IS_NOT_NULL(qn->head_exact)) {
r = add_op(reg, OP_PUSH_OR_JUMP_EXACT1);
if (r != 0) return r;
COP(reg)->push_or_jump_exact1.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP;
COP(reg)->push_or_jump_exact1.c = STR_(qn->head_exact)->s[0];
r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env);
if (r != 0) return r;
addr = -(mod_tlen + (int )SIZE_OP_PUSH_OR_JUMP_EXACT1);
}
else
#endif
if (IS_NOT_NULL(qn->next_head_exact)) {
r = add_op(reg, OP_PUSH_IF_PEEK_NEXT);
if (r != 0) return r;
COP(reg)->push_if_peek_next.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP;
COP(reg)->push_if_peek_next.c = STR_(qn->next_head_exact)->s[0];
r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env);
if (r != 0) return r;
addr = -(mod_tlen + (int )SIZE_OP_PUSH_IF_PEEK_NEXT);
}
else {
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP;
r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env);
if (r != 0) return r;
addr = -(mod_tlen + (int )SIZE_OP_PUSH);
}
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = addr;
}
else {
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = mod_tlen + SIZE_INC_OP;
r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env);
if (r != 0) return r;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = -mod_tlen;
}
}
else if (qn->upper == 0) {
if (qn->is_refered != 0) { /* /(?<n>..){0}/ */
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = tlen + SIZE_INC_OP;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
}
else {
/* Nothing output */
r = 0;
}
}
else if (! infinite && qn->greedy &&
(qn->upper == 1 ||
int_multiply_cmp(tlen + SIZE_OP_PUSH, qn->upper,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
int n = qn->upper - qn->lower;
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
for (i = 0; i < n; i++) {
int v = onig_positive_int_multiply(n - i, tlen + SIZE_OP_PUSH);
if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = v;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
if (r != 0) return r;
}
}
else if (! qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC_OP + SIZE_OP_JUMP;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = tlen + SIZE_INC_OP;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
}
else {
r = compile_range_repeat_node(qn, mod_tlen, empty_info, reg, env);
}
return r;
}
static int
compile_length_option_node(BagNode* node, regex_t* reg)
{
int tlen;
OnigOptionType prev = reg->options;
reg->options = node->o.options;
tlen = compile_length_tree(NODE_BAG_BODY(node), reg);
reg->options = prev;
return tlen;
}
static int
compile_option_node(BagNode* node, regex_t* reg, ScanEnv* env)
{
int r;
OnigOptionType prev = reg->options;
reg->options = node->o.options;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
reg->options = prev;
return r;
}
static int
compile_length_bag_node(BagNode* node, regex_t* reg)
{
int len;
int tlen;
if (node->type == BAG_OPTION)
return compile_length_option_node(node, reg);
if (NODE_BAG_BODY(node)) {
tlen = compile_length_tree(NODE_BAG_BODY(node), reg);
if (tlen < 0) return tlen;
}
else
tlen = 0;
switch (node->type) {
case BAG_MEMORY:
#ifdef USE_CALL
if (node->m.regnum == 0 && NODE_IS_CALLED(node)) {
len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;
return len;
}
if (NODE_IS_CALLED(node)) {
len = SIZE_OP_MEMORY_START_PUSH + tlen
+ SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;
if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum))
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH);
else
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END);
}
else if (NODE_IS_RECURSION(node)) {
len = SIZE_OP_MEMORY_START_PUSH;
len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)
? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC);
}
else
#endif
{
if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum))
len = SIZE_OP_MEMORY_START_PUSH;
else
len = SIZE_OP_MEMORY_START;
len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)
? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END);
}
break;
case BAG_STOP_BACKTRACK:
if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) {
int v;
QuantNode* qn;
qn = QUANT_(NODE_BAG_BODY(node));
tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
v = onig_positive_int_multiply(qn->lower, tlen);
if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP;
}
else {
len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END;
}
break;
case BAG_IF_ELSE:
{
Node* cond = NODE_BAG_BODY(node);
Node* Then = node->te.Then;
Node* Else = node->te.Else;
len = compile_length_tree(cond, reg);
if (len < 0) return len;
len += SIZE_OP_PUSH;
len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END;
if (IS_NOT_NULL(Then)) {
tlen = compile_length_tree(Then, reg);
if (tlen < 0) return tlen;
len += tlen;
}
len += SIZE_OP_JUMP + SIZE_OP_ATOMIC_END;
if (IS_NOT_NULL(Else)) {
tlen = compile_length_tree(Else, reg);
if (tlen < 0) return tlen;
len += tlen;
}
}
break;
case BAG_OPTION:
/* never come here, but set for escape warning */
len = 0;
break;
}
return len;
}
static int get_char_len_node(Node* node, regex_t* reg, int* len);
static int
compile_bag_memory_node(BagNode* node, regex_t* reg, ScanEnv* env)
{
int r;
int len;
#ifdef USE_CALL
if (NODE_IS_CALLED(node)) {
r = add_op(reg, OP_CALL);
if (r != 0) return r;
node->m.called_addr = COP_CURR_OFFSET(reg) + 1 + SIZE_OP_JUMP;
NODE_STATUS_ADD(node, ADDR_FIXED);
COP(reg)->call.addr = (int )node->m.called_addr;
if (node->m.regnum == 0) {
len = compile_length_tree(NODE_BAG_BODY(node), reg);
len += SIZE_OP_RETURN;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = len + SIZE_INC_OP;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_RETURN);
return r;
}
else {
len = compile_length_tree(NODE_BAG_BODY(node), reg);
len += (SIZE_OP_MEMORY_START_PUSH + SIZE_OP_RETURN);
if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum))
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH);
else
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END);
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = len + SIZE_INC_OP;
}
}
#endif
if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum))
r = add_op(reg, OP_MEMORY_START_PUSH);
else
r = add_op(reg, OP_MEMORY_START);
if (r != 0) return r;
COP(reg)->memory_start.num = node->m.regnum;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
if (r != 0) return r;
#ifdef USE_CALL
if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum))
r = add_op(reg, (NODE_IS_RECURSION(node)
? OP_MEMORY_END_PUSH_REC : OP_MEMORY_END_PUSH));
else
r = add_op(reg, (NODE_IS_RECURSION(node) ? OP_MEMORY_END_REC : OP_MEMORY_END));
if (r != 0) return r;
COP(reg)->memory_end.num = node->m.regnum;
if (NODE_IS_CALLED(node)) {
if (r != 0) return r;
r = add_op(reg, OP_RETURN);
}
#else
if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum))
r = add_op(reg, OP_MEMORY_END_PUSH);
else
r = add_op(reg, OP_MEMORY_END);
if (r != 0) return r;
COP(reg)->memory_end.num = node->m.regnum;
#endif
return r;
}
static int
compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)
{
int r, len;
switch (node->type) {
case BAG_MEMORY:
r = compile_bag_memory_node(node, reg, env);
break;
case BAG_OPTION:
r = compile_option_node(node, reg, env);
break;
case BAG_STOP_BACKTRACK:
if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) {
QuantNode* qn = QUANT_(NODE_BAG_BODY(node));
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
len = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (len < 0) return len;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_POP_OUT);
if (r != 0) return r;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT);
}
else {
r = add_op(reg, OP_ATOMIC_START);
if (r != 0) return r;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_ATOMIC_END);
}
break;
case BAG_IF_ELSE:
{
int cond_len, then_len, else_len, jump_len;
Node* cond = NODE_BAG_BODY(node);
Node* Then = node->te.Then;
Node* Else = node->te.Else;
r = add_op(reg, OP_ATOMIC_START);
if (r != 0) return r;
cond_len = compile_length_tree(cond, reg);
if (cond_len < 0) return cond_len;
if (IS_NOT_NULL(Then)) {
then_len = compile_length_tree(Then, reg);
if (then_len < 0) return then_len;
}
else
then_len = 0;
jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC_OP + jump_len;
r = compile_tree(cond, reg, env);
if (r != 0) return r;
r = add_op(reg, OP_ATOMIC_END);
if (r != 0) return r;
if (IS_NOT_NULL(Then)) {
r = compile_tree(Then, reg, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(Else)) {
else_len = compile_length_tree(Else, reg);
if (else_len < 0) return else_len;
}
else
else_len = 0;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP;
r = add_op(reg, OP_ATOMIC_END);
if (r != 0) return r;
if (IS_NOT_NULL(Else)) {
r = compile_tree(Else, reg, env);
}
}
break;
}
return r;
}
static int
compile_length_anchor_node(AnchorNode* node, regex_t* reg)
{
int len;
int tlen = 0;
if (IS_NOT_NULL(NODE_ANCHOR_BODY(node))) {
tlen = compile_length_tree(NODE_ANCHOR_BODY(node), reg);
if (tlen < 0) return tlen;
}
switch (node->type) {
case ANCR_PREC_READ:
len = SIZE_OP_PREC_READ_START + tlen + SIZE_OP_PREC_READ_END;
break;
case ANCR_PREC_READ_NOT:
len = SIZE_OP_PREC_READ_NOT_START + tlen + SIZE_OP_PREC_READ_NOT_END;
break;
case ANCR_LOOK_BEHIND:
len = SIZE_OP_LOOK_BEHIND + tlen;
break;
case ANCR_LOOK_BEHIND_NOT:
len = SIZE_OP_LOOK_BEHIND_NOT_START + tlen + SIZE_OP_LOOK_BEHIND_NOT_END;
break;
case ANCR_WORD_BOUNDARY:
case ANCR_NO_WORD_BOUNDARY:
#ifdef USE_WORD_BEGIN_END
case ANCR_WORD_BEGIN:
case ANCR_WORD_END:
#endif
len = SIZE_OP_WORD_BOUNDARY;
break;
case ANCR_TEXT_SEGMENT_BOUNDARY:
case ANCR_NO_TEXT_SEGMENT_BOUNDARY:
len = SIZE_OPCODE;
break;
default:
len = SIZE_OPCODE;
break;
}
return len;
}
static int
compile_anchor_node(AnchorNode* node, regex_t* reg, ScanEnv* env)
{
int r, len;
enum OpCode op;
switch (node->type) {
case ANCR_BEGIN_BUF: r = add_op(reg, OP_BEGIN_BUF); break;
case ANCR_END_BUF: r = add_op(reg, OP_END_BUF); break;
case ANCR_BEGIN_LINE: r = add_op(reg, OP_BEGIN_LINE); break;
case ANCR_END_LINE: r = add_op(reg, OP_END_LINE); break;
case ANCR_SEMI_END_BUF: r = add_op(reg, OP_SEMI_END_BUF); break;
case ANCR_BEGIN_POSITION: r = add_op(reg, OP_BEGIN_POSITION); break;
case ANCR_WORD_BOUNDARY:
op = OP_WORD_BOUNDARY;
word:
r = add_op(reg, op);
if (r != 0) return r;
COP(reg)->word_boundary.mode = (ModeType )node->ascii_mode;
break;
case ANCR_NO_WORD_BOUNDARY:
op = OP_NO_WORD_BOUNDARY; goto word;
break;
#ifdef USE_WORD_BEGIN_END
case ANCR_WORD_BEGIN:
op = OP_WORD_BEGIN; goto word;
break;
case ANCR_WORD_END:
op = OP_WORD_END; goto word;
break;
#endif
case ANCR_TEXT_SEGMENT_BOUNDARY:
case ANCR_NO_TEXT_SEGMENT_BOUNDARY:
{
enum TextSegmentBoundaryType type;
r = add_op(reg, OP_TEXT_SEGMENT_BOUNDARY);
if (r != 0) return r;
type = EXTENDED_GRAPHEME_CLUSTER_BOUNDARY;
#ifdef USE_UNICODE_WORD_BREAK
if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_TEXT_SEGMENT_WORD))
type = WORD_BOUNDARY;
#endif
COP(reg)->text_segment_boundary.type = type;
COP(reg)->text_segment_boundary.not =
(node->type == ANCR_NO_TEXT_SEGMENT_BOUNDARY ? 1 : 0);
}
break;
case ANCR_PREC_READ:
r = add_op(reg, OP_PREC_READ_START);
if (r != 0) return r;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_PREC_READ_END);
break;
case ANCR_PREC_READ_NOT:
len = compile_length_tree(NODE_ANCHOR_BODY(node), reg);
if (len < 0) return len;
r = add_op(reg, OP_PREC_READ_NOT_START);
if (r != 0) return r;
COP(reg)->prec_read_not_start.addr = SIZE_INC_OP + len + SIZE_OP_PREC_READ_NOT_END;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_PREC_READ_NOT_END);
break;
case ANCR_LOOK_BEHIND:
{
int n;
r = add_op(reg, OP_LOOK_BEHIND);
if (r != 0) return r;
if (node->char_len < 0) {
r = get_char_len_node(NODE_ANCHOR_BODY(node), reg, &n);
if (r != 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
else
n = node->char_len;
COP(reg)->look_behind.len = n;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
}
break;
case ANCR_LOOK_BEHIND_NOT:
{
int n;
len = compile_length_tree(NODE_ANCHOR_BODY(node), reg);
r = add_op(reg, OP_LOOK_BEHIND_NOT_START);
if (r != 0) return r;
COP(reg)->look_behind_not_start.addr = SIZE_INC_OP + len + SIZE_OP_LOOK_BEHIND_NOT_END;
if (node->char_len < 0) {
r = get_char_len_node(NODE_ANCHOR_BODY(node), reg, &n);
if (r != 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
else
n = node->char_len;
COP(reg)->look_behind_not_start.len = n;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_LOOK_BEHIND_NOT_END);
}
break;
default:
return ONIGERR_TYPE_BUG;
break;
}
return r;
}
static int
compile_gimmick_node(GimmickNode* node, regex_t* reg)
{
int r;
switch (node->type) {
case GIMMICK_FAIL:
r = add_op(reg, OP_FAIL);
break;
case GIMMICK_SAVE:
r = add_op(reg, OP_PUSH_SAVE_VAL);
if (r != 0) return r;
COP(reg)->push_save_val.type = node->detail_type;
COP(reg)->push_save_val.id = node->id;
break;
case GIMMICK_UPDATE_VAR:
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = node->detail_type;
COP(reg)->update_var.id = node->id;
break;
#ifdef USE_CALLOUT
case GIMMICK_CALLOUT:
switch (node->detail_type) {
case ONIG_CALLOUT_OF_CONTENTS:
case ONIG_CALLOUT_OF_NAME:
{
if (node->detail_type == ONIG_CALLOUT_OF_NAME) {
r = add_op(reg, OP_CALLOUT_NAME);
if (r != 0) return r;
COP(reg)->callout_name.id = node->id;
COP(reg)->callout_name.num = node->num;
}
else {
r = add_op(reg, OP_CALLOUT_CONTENTS);
if (r != 0) return r;
COP(reg)->callout_contents.num = node->num;
}
}
break;
default:
r = ONIGERR_TYPE_BUG;
break;
}
#endif
}
return r;
}
static int
compile_length_gimmick_node(GimmickNode* node, regex_t* reg)
{
int len;
switch (node->type) {
case GIMMICK_FAIL:
len = SIZE_OP_FAIL;
break;
case GIMMICK_SAVE:
len = SIZE_OP_PUSH_SAVE_VAL;
break;
case GIMMICK_UPDATE_VAR:
len = SIZE_OP_UPDATE_VAR;
break;
#ifdef USE_CALLOUT
case GIMMICK_CALLOUT:
switch (node->detail_type) {
case ONIG_CALLOUT_OF_CONTENTS:
len = SIZE_OP_CALLOUT_CONTENTS;
break;
case ONIG_CALLOUT_OF_NAME:
len = SIZE_OP_CALLOUT_NAME;
break;
default:
len = ONIGERR_TYPE_BUG;
break;
}
break;
#endif
}
return len;
}
static int
compile_length_tree(Node* node, regex_t* reg)
{
int len, r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
len = 0;
do {
r = compile_length_tree(NODE_CAR(node), reg);
if (r < 0) return r;
len += r;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
r = len;
break;
case NODE_ALT:
{
int n;
n = r = 0;
do {
r += compile_length_tree(NODE_CAR(node), reg);
n++;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
r += (SIZE_OP_PUSH + SIZE_OP_JUMP) * (n - 1);
}
break;
case NODE_STRING:
if (NODE_STRING_IS_RAW(node))
r = compile_length_string_raw_node(STR_(node), reg);
else
r = compile_length_string_node(node, reg);
break;
case NODE_CCLASS:
r = compile_length_cclass_node(CCLASS_(node), reg);
break;
case NODE_CTYPE:
r = SIZE_OPCODE;
break;
case NODE_BACKREF:
r = SIZE_OP_BACKREF;
break;
#ifdef USE_CALL
case NODE_CALL:
r = SIZE_OP_CALL;
break;
#endif
case NODE_QUANT:
r = compile_length_quantifier_node(QUANT_(node), reg);
break;
case NODE_BAG:
r = compile_length_bag_node(BAG_(node), reg);
break;
case NODE_ANCHOR:
r = compile_length_anchor_node(ANCHOR_(node), reg);
break;
case NODE_GIMMICK:
r = compile_length_gimmick_node(GIMMICK_(node), reg);
break;
default:
return ONIGERR_TYPE_BUG;
break;
}
return r;
}
static int
compile_tree(Node* node, regex_t* reg, ScanEnv* env)
{
int n, len, pos, r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
do {
r = compile_tree(NODE_CAR(node), reg, env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
{
Node* x = node;
len = 0;
do {
len += compile_length_tree(NODE_CAR(x), reg);
if (IS_NOT_NULL(NODE_CDR(x))) {
len += SIZE_OP_PUSH + SIZE_OP_JUMP;
}
} while (IS_NOT_NULL(x = NODE_CDR(x)));
pos = COP_CURR_OFFSET(reg) + 1 + len; /* goal position */
do {
len = compile_length_tree(NODE_CAR(node), reg);
if (IS_NOT_NULL(NODE_CDR(node))) {
enum OpCode push = NODE_IS_SUPER(node) ? OP_PUSH_SUPER : OP_PUSH;
r = add_op(reg, push);
if (r != 0) break;
COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_JUMP;
}
r = compile_tree(NODE_CAR(node), reg, env);
if (r != 0) break;
if (IS_NOT_NULL(NODE_CDR(node))) {
len = pos - (COP_CURR_OFFSET(reg) + 1);
r = add_op(reg, OP_JUMP);
if (r != 0) break;
COP(reg)->jump.addr = len;
}
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_STRING:
if (NODE_STRING_IS_RAW(node))
r = compile_string_raw_node(STR_(node), reg);
else
r = compile_string_node(node, reg);
break;
case NODE_CCLASS:
r = compile_cclass_node(CCLASS_(node), reg);
break;
case NODE_CTYPE:
{
int op;
switch (CTYPE_(node)->ctype) {
case CTYPE_ANYCHAR:
r = add_op(reg, IS_MULTILINE(CTYPE_OPTION(node, reg)) ?
OP_ANYCHAR_ML : OP_ANYCHAR);
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(node)->ascii_mode == 0) {
op = CTYPE_(node)->not != 0 ? OP_NO_WORD : OP_WORD;
}
else {
op = CTYPE_(node)->not != 0 ? OP_NO_WORD_ASCII : OP_WORD_ASCII;
}
r = add_op(reg, op);
break;
default:
return ONIGERR_TYPE_BUG;
break;
}
}
break;
case NODE_BACKREF:
{
BackRefNode* br = BACKREF_(node);
if (NODE_IS_CHECKER(node)) {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
r = add_op(reg, OP_BACKREF_CHECK_WITH_LEVEL);
if (r != 0) return r;
COP(reg)->backref_general.nest_level = br->nest_level;
}
else
#endif
{
r = add_op(reg, OP_BACKREF_CHECK);
if (r != 0) return r;
}
goto add_bacref_mems;
}
else {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
if ((reg->options & ONIG_OPTION_IGNORECASE) != 0)
r = add_op(reg, OP_BACKREF_WITH_LEVEL_IC);
else
r = add_op(reg, OP_BACKREF_WITH_LEVEL);
if (r != 0) return r;
COP(reg)->backref_general.nest_level = br->nest_level;
goto add_bacref_mems;
}
else
#endif
if (br->back_num == 1) {
n = br->back_static[0];
if (IS_IGNORECASE(reg->options)) {
r = add_op(reg, OP_BACKREF_N_IC);
if (r != 0) return r;
COP(reg)->backref_n.n1 = n;
}
else {
switch (n) {
case 1: r = add_op(reg, OP_BACKREF1); break;
case 2: r = add_op(reg, OP_BACKREF2); break;
default:
r = add_op(reg, OP_BACKREF_N);
if (r != 0) return r;
COP(reg)->backref_n.n1 = n;
break;
}
}
}
else {
int num;
int* p;
r = add_op(reg, IS_IGNORECASE(reg->options) ?
OP_BACKREF_MULTI_IC : OP_BACKREF_MULTI);
if (r != 0) return r;
add_bacref_mems:
num = br->back_num;
COP(reg)->backref_general.num = num;
if (num == 1) {
COP(reg)->backref_general.n1 = br->back_static[0];
}
else {
int i, j;
MemNumType* ns;
ns = xmalloc(sizeof(MemNumType) * num);
CHECK_NULL_RETURN_MEMERR(ns);
COP(reg)->backref_general.ns = ns;
p = BACKREFS_P(br);
for (i = num - 1, j = 0; i >= 0; i--, j++) {
ns[j] = p[i];
}
}
}
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
r = compile_call(CALL_(node), reg, env);
break;
#endif
case NODE_QUANT:
r = compile_quantifier_node(QUANT_(node), reg, env);
break;
case NODE_BAG:
r = compile_bag_node(BAG_(node), reg, env);
break;
case NODE_ANCHOR:
r = compile_anchor_node(ANCHOR_(node), reg, env);
break;
case NODE_GIMMICK:
r = compile_gimmick_node(GIMMICK_(node), reg);
break;
default:
#ifdef ONIG_DEBUG
fprintf(stderr, "compile_tree: undefined node type %d\n", NODE_TYPE(node));
#endif
break;
}
return r;
}
static int
noname_disable_map(Node** plink, GroupNumRemap* map, int* counter)
{
int r = 0;
Node* node = *plink;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = noname_disable_map(&(NODE_CAR(node)), map, counter);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
{
Node** ptarget = &(NODE_BODY(node));
Node* old = *ptarget;
r = noname_disable_map(ptarget, map, counter);
if (*ptarget != old && NODE_TYPE(*ptarget) == NODE_QUANT) {
onig_reduce_nested_quantifier(node, *ptarget);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_NAMED_GROUP(node)) {
(*counter)++;
map[en->m.regnum].new_val = *counter;
en->m.regnum = *counter;
r = noname_disable_map(&(NODE_BODY(node)), map, counter);
}
else {
*plink = NODE_BODY(node);
NODE_BODY(node) = NULL_NODE;
onig_node_free(node);
r = noname_disable_map(plink, map, counter);
}
}
else if (en->type == BAG_IF_ELSE) {
r = noname_disable_map(&(NODE_BAG_BODY(en)), map, counter);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = noname_disable_map(&(en->te.Then), map, counter);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = noname_disable_map(&(en->te.Else), map, counter);
if (r != 0) return r;
}
}
else
r = noname_disable_map(&(NODE_BODY(node)), map, counter);
}
break;
case NODE_ANCHOR:
if (IS_NOT_NULL(NODE_BODY(node)))
r = noname_disable_map(&(NODE_BODY(node)), map, counter);
break;
default:
break;
}
return r;
}
static int
renumber_node_backref(Node* node, GroupNumRemap* map)
{
int i, pos, n, old_num;
int *backs;
BackRefNode* bn = BACKREF_(node);
if (! NODE_IS_BY_NAME(node))
return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
old_num = bn->back_num;
if (IS_NULL(bn->back_dynamic))
backs = bn->back_static;
else
backs = bn->back_dynamic;
for (i = 0, pos = 0; i < old_num; i++) {
n = map[backs[i]].new_val;
if (n > 0) {
backs[pos] = n;
pos++;
}
}
bn->back_num = pos;
return 0;
}
static int
renumber_by_map(Node* node, GroupNumRemap* map)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = renumber_by_map(NODE_CAR(node), map);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = renumber_by_map(NODE_BODY(node), map);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = renumber_by_map(NODE_BODY(node), map);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = renumber_by_map(en->te.Then, map);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = renumber_by_map(en->te.Else, map);
if (r != 0) return r;
}
}
}
break;
case NODE_BACKREF:
r = renumber_node_backref(node, map);
break;
case NODE_ANCHOR:
if (IS_NOT_NULL(NODE_BODY(node)))
r = renumber_by_map(NODE_BODY(node), map);
break;
default:
break;
}
return r;
}
static int
numbered_ref_check(Node* node)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = numbered_ref_check(NODE_CAR(node));
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (IS_NULL(NODE_BODY(node)))
break;
/* fall */
case NODE_QUANT:
r = numbered_ref_check(NODE_BODY(node));
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = numbered_ref_check(NODE_BODY(node));
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = numbered_ref_check(en->te.Then);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = numbered_ref_check(en->te.Else);
if (r != 0) return r;
}
}
}
break;
case NODE_BACKREF:
if (! NODE_IS_BY_NAME(node))
return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
break;
default:
break;
}
return r;
}
static int
disable_noname_group_capture(Node** root, regex_t* reg, ScanEnv* env)
{
int r, i, pos, counter;
MemStatusType loc;
GroupNumRemap* map;
map = (GroupNumRemap* )xalloca(sizeof(GroupNumRemap) * (env->num_mem + 1));
CHECK_NULL_RETURN_MEMERR(map);
for (i = 1; i <= env->num_mem; i++) {
map[i].new_val = 0;
}
counter = 0;
r = noname_disable_map(root, map, &counter);
if (r != 0) return r;
r = renumber_by_map(*root, map);
if (r != 0) return r;
for (i = 1, pos = 1; i <= env->num_mem; i++) {
if (map[i].new_val > 0) {
SCANENV_MEMENV(env)[pos] = SCANENV_MEMENV(env)[i];
pos++;
}
}
loc = env->capture_history;
MEM_STATUS_CLEAR(env->capture_history);
for (i = 1; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) {
if (MEM_STATUS_AT(loc, i)) {
MEM_STATUS_ON_SIMPLE(env->capture_history, map[i].new_val);
}
}
env->num_mem = env->num_named;
reg->num_mem = env->num_named;
return onig_renumber_name_table(reg, map);
}
#ifdef USE_CALL
static int
fix_unset_addr_list(UnsetAddrList* uslist, regex_t* reg)
{
int i, offset;
BagNode* en;
AbsAddrType addr;
AbsAddrType* paddr;
for (i = 0; i < uslist->num; i++) {
if (! NODE_IS_ADDR_FIXED(uslist->us[i].target))
return ONIGERR_PARSER_BUG;
en = BAG_(uslist->us[i].target);
addr = en->m.called_addr;
offset = uslist->us[i].offset;
paddr = (AbsAddrType* )((char* )reg->ops + offset);
*paddr = addr;
}
return 0;
}
#endif
#define GET_CHAR_LEN_VARLEN -1
#define GET_CHAR_LEN_TOP_ALT_VARLEN -2
/* fixed size pattern node only */
static int
get_char_len_node1(Node* node, regex_t* reg, int* len, int level)
{
int tlen;
int r = 0;
level++;
*len = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
do {
r = get_char_len_node1(NODE_CAR(node), reg, &tlen, level);
if (r == 0)
*len = distance_add(*len, tlen);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
{
int tlen2;
int varlen = 0;
r = get_char_len_node1(NODE_CAR(node), reg, &tlen, level);
while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))) {
r = get_char_len_node1(NODE_CAR(node), reg, &tlen2, level);
if (r == 0) {
if (tlen != tlen2)
varlen = 1;
}
}
if (r == 0) {
if (varlen != 0) {
if (level == 1)
r = GET_CHAR_LEN_TOP_ALT_VARLEN;
else
r = GET_CHAR_LEN_VARLEN;
}
else
*len = tlen;
}
}
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
UChar *s = sn->s;
while (s < sn->end) {
s += enclen(reg->enc, s);
(*len)++;
}
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower == qn->upper) {
if (qn->upper == 0) {
*len = 0;
}
else {
r = get_char_len_node1(NODE_BODY(node), reg, &tlen, level);
if (r == 0)
*len = distance_multiply(tlen, qn->lower);
}
}
else
r = GET_CHAR_LEN_VARLEN;
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (! NODE_IS_RECURSION(node))
r = get_char_len_node1(NODE_BODY(node), reg, len, level);
else
r = GET_CHAR_LEN_VARLEN;
break;
#endif
case NODE_CTYPE:
case NODE_CCLASS:
*len = 1;
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
#ifdef USE_CALL
if (NODE_IS_CLEN_FIXED(node))
*len = en->char_len;
else {
r = get_char_len_node1(NODE_BODY(node), reg, len, level);
if (r == 0) {
en->char_len = *len;
NODE_STATUS_ADD(node, CLEN_FIXED);
}
}
break;
#endif
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
r = get_char_len_node1(NODE_BODY(node), reg, len, level);
break;
case BAG_IF_ELSE:
{
int clen, elen;
r = get_char_len_node1(NODE_BODY(node), reg, &clen, level);
if (r == 0) {
if (IS_NOT_NULL(en->te.Then)) {
r = get_char_len_node1(en->te.Then, reg, &tlen, level);
if (r != 0) break;
}
else tlen = 0;
if (IS_NOT_NULL(en->te.Else)) {
r = get_char_len_node1(en->te.Else, reg, &elen, level);
if (r != 0) break;
}
else elen = 0;
if (clen + tlen != elen) {
r = GET_CHAR_LEN_VARLEN;
}
else {
*len = elen;
}
}
}
break;
}
}
break;
case NODE_ANCHOR:
case NODE_GIMMICK:
break;
case NODE_BACKREF:
if (NODE_IS_CHECKER(node))
break;
/* fall */
default:
r = GET_CHAR_LEN_VARLEN;
break;
}
return r;
}
static int
get_char_len_node(Node* node, regex_t* reg, int* len)
{
return get_char_len_node1(node, reg, len, 0);
}
/* x is not included y ==> 1 : 0 */
static int
is_exclusive(Node* x, Node* y, regex_t* reg)
{
int i, len;
OnigCodePoint code;
UChar *p;
NodeType ytype;
retry:
ytype = NODE_TYPE(y);
switch (NODE_TYPE(x)) {
case NODE_CTYPE:
{
if (CTYPE_(x)->ctype == CTYPE_ANYCHAR ||
CTYPE_(y)->ctype == CTYPE_ANYCHAR)
break;
switch (ytype) {
case NODE_CTYPE:
if (CTYPE_(y)->ctype == CTYPE_(x)->ctype &&
CTYPE_(y)->not != CTYPE_(x)->not &&
CTYPE_(y)->ascii_mode == CTYPE_(x)->ascii_mode)
return 1;
else
return 0;
break;
case NODE_CCLASS:
swap:
{
Node* tmp;
tmp = x; x = y; y = tmp;
goto retry;
}
break;
case NODE_STRING:
goto swap;
break;
default:
break;
}
}
break;
case NODE_CCLASS:
{
int range;
CClassNode* xc = CCLASS_(x);
switch (ytype) {
case NODE_CTYPE:
switch (CTYPE_(y)->ctype) {
case CTYPE_ANYCHAR:
return 0;
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(y)->not == 0) {
if (IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) {
range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;
for (i = 0; i < range; i++) {
if (BITSET_AT(xc->bs, i)) {
if (ONIGENC_IS_CODE_WORD(reg->enc, i)) return 0;
}
}
return 1;
}
return 0;
}
else {
if (IS_NOT_NULL(xc->mbuf)) return 0;
if (IS_NCCLASS_NOT(xc)) return 0;
range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;
for (i = 0; i < range; i++) {
if (! ONIGENC_IS_CODE_WORD(reg->enc, i)) {
if (BITSET_AT(xc->bs, i))
return 0;
}
}
for (i = range; i < SINGLE_BYTE_SIZE; i++) {
if (BITSET_AT(xc->bs, i)) return 0;
}
return 1;
}
break;
default:
break;
}
break;
case NODE_CCLASS:
{
int v;
CClassNode* yc = CCLASS_(y);
for (i = 0; i < SINGLE_BYTE_SIZE; i++) {
v = BITSET_AT(xc->bs, i);
if ((v != 0 && !IS_NCCLASS_NOT(xc)) || (v == 0 && IS_NCCLASS_NOT(xc))) {
v = BITSET_AT(yc->bs, i);
if ((v != 0 && !IS_NCCLASS_NOT(yc)) ||
(v == 0 && IS_NCCLASS_NOT(yc)))
return 0;
}
}
if ((IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) ||
(IS_NULL(yc->mbuf) && !IS_NCCLASS_NOT(yc)))
return 1;
return 0;
}
break;
case NODE_STRING:
goto swap;
break;
default:
break;
}
}
break;
case NODE_STRING:
{
StrNode* xs = STR_(x);
if (NODE_STRING_LEN(x) == 0)
break;
switch (ytype) {
case NODE_CTYPE:
switch (CTYPE_(y)->ctype) {
case CTYPE_ANYCHAR:
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(y)->ascii_mode == 0) {
if (ONIGENC_IS_MBC_WORD(reg->enc, xs->s, xs->end))
return CTYPE_(y)->not;
else
return !(CTYPE_(y)->not);
}
else {
if (ONIGENC_IS_MBC_WORD_ASCII(reg->enc, xs->s, xs->end))
return CTYPE_(y)->not;
else
return !(CTYPE_(y)->not);
}
break;
default:
break;
}
break;
case NODE_CCLASS:
{
CClassNode* cc = CCLASS_(y);
code = ONIGENC_MBC_TO_CODE(reg->enc, xs->s,
xs->s + ONIGENC_MBC_MAXLEN(reg->enc));
return onig_is_code_in_cc(reg->enc, code, cc) == 0;
}
break;
case NODE_STRING:
{
UChar *q;
StrNode* ys = STR_(y);
len = NODE_STRING_LEN(x);
if (len > NODE_STRING_LEN(y)) len = NODE_STRING_LEN(y);
if (NODE_STRING_IS_AMBIG(x) || NODE_STRING_IS_AMBIG(y)) {
/* tiny version */
return 0;
}
else {
for (i = 0, p = ys->s, q = xs->s; i < len; i++, p++, q++) {
if (*p != *q) return 1;
}
}
}
break;
default:
break;
}
}
break;
default:
break;
}
return 0;
}
static Node*
get_head_value_node(Node* node, int exact, regex_t* reg)
{
Node* n = NULL_NODE;
switch (NODE_TYPE(node)) {
case NODE_BACKREF:
case NODE_ALT:
#ifdef USE_CALL
case NODE_CALL:
#endif
break;
case NODE_CTYPE:
if (CTYPE_(node)->ctype == CTYPE_ANYCHAR)
break;
/* fall */
case NODE_CCLASS:
if (exact == 0) {
n = node;
}
break;
case NODE_LIST:
n = get_head_value_node(NODE_CAR(node), exact, reg);
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
if (sn->end <= sn->s)
break;
if (exact == 0 ||
! IS_IGNORECASE(reg->options) || NODE_STRING_IS_RAW(node)) {
n = node;
}
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower > 0) {
if (IS_NOT_NULL(qn->head_exact))
n = qn->head_exact;
else
n = get_head_value_node(NODE_BODY(node), exact, reg);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_OPTION:
{
OnigOptionType options = reg->options;
reg->options = BAG_(node)->o.options;
n = get_head_value_node(NODE_BODY(node), exact, reg);
reg->options = options;
}
break;
case BAG_MEMORY:
case BAG_STOP_BACKTRACK:
case BAG_IF_ELSE:
n = get_head_value_node(NODE_BODY(node), exact, reg);
break;
}
}
break;
case NODE_ANCHOR:
if (ANCHOR_(node)->type == ANCR_PREC_READ)
n = get_head_value_node(NODE_BODY(node), exact, reg);
break;
case NODE_GIMMICK:
default:
break;
}
return n;
}
static int
check_type_tree(Node* node, int type_mask, int bag_mask, int anchor_mask)
{
NodeType type;
int r = 0;
type = NODE_TYPE(node);
if ((NODE_TYPE2BIT(type) & type_mask) == 0)
return 1;
switch (type) {
case NODE_LIST:
case NODE_ALT:
do {
r = check_type_tree(NODE_CAR(node), type_mask, bag_mask, anchor_mask);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = check_type_tree(NODE_BODY(node), type_mask, bag_mask, anchor_mask);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (((1<<en->type) & bag_mask) == 0)
return 1;
r = check_type_tree(NODE_BODY(node), type_mask, bag_mask, anchor_mask);
if (r == 0 && en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = check_type_tree(en->te.Then, type_mask, bag_mask, anchor_mask);
if (r != 0) break;
}
if (IS_NOT_NULL(en->te.Else)) {
r = check_type_tree(en->te.Else, type_mask, bag_mask, anchor_mask);
}
}
}
break;
case NODE_ANCHOR:
type = ANCHOR_(node)->type;
if ((type & anchor_mask) == 0)
return 1;
if (IS_NOT_NULL(NODE_BODY(node)))
r = check_type_tree(NODE_BODY(node), type_mask, bag_mask, anchor_mask);
break;
case NODE_GIMMICK:
default:
break;
}
return r;
}
static OnigLen
tree_min_len(Node* node, ScanEnv* env)
{
OnigLen len;
OnigLen tmin;
len = 0;
switch (NODE_TYPE(node)) {
case NODE_BACKREF:
if (! NODE_IS_CHECKER(node)) {
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
if (NODE_IS_RECURSION(node)) break;
backs = BACKREFS_P(br);
len = tree_min_len(mem_env[backs[0]].node, env);
for (i = 1; i < br->back_num; i++) {
tmin = tree_min_len(mem_env[backs[i]].node, env);
if (len > tmin) len = tmin;
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
{
Node* t = NODE_BODY(node);
if (NODE_IS_RECURSION(node)) {
if (NODE_IS_MIN_FIXED(t))
len = BAG_(t)->min_len;
}
else
len = tree_min_len(t, env);
}
break;
#endif
case NODE_LIST:
do {
tmin = tree_min_len(NODE_CAR(node), env);
len = distance_add(len, tmin);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
{
Node *x, *y;
y = node;
do {
x = NODE_CAR(y);
tmin = tree_min_len(x, env);
if (y == node) len = tmin;
else if (len > tmin) len = tmin;
} while (IS_NOT_NULL(y = NODE_CDR(y)));
}
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
len = (int )(sn->end - sn->s);
}
break;
case NODE_CTYPE:
case NODE_CCLASS:
len = ONIGENC_MBC_MINLEN(env->enc);
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower > 0) {
len = tree_min_len(NODE_BODY(node), env);
len = distance_multiply(len, qn->lower);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_MIN_FIXED(node))
len = en->min_len;
else {
if (NODE_IS_MARK1(node))
len = 0; /* recursive */
else {
NODE_STATUS_ADD(node, MARK1);
len = tree_min_len(NODE_BODY(node), env);
NODE_STATUS_REMOVE(node, MARK1);
en->min_len = len;
NODE_STATUS_ADD(node, MIN_FIXED);
}
}
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
len = tree_min_len(NODE_BODY(node), env);
break;
case BAG_IF_ELSE:
{
OnigLen elen;
len = tree_min_len(NODE_BODY(node), env);
if (IS_NOT_NULL(en->te.Then))
len += tree_min_len(en->te.Then, env);
if (IS_NOT_NULL(en->te.Else))
elen = tree_min_len(en->te.Else, env);
else elen = 0;
if (elen < len) len = elen;
}
break;
}
}
break;
case NODE_GIMMICK:
{
GimmickNode* g = GIMMICK_(node);
if (g->type == GIMMICK_FAIL) {
len = INFINITE_LEN;
break;
}
}
/* fall */
case NODE_ANCHOR:
default:
break;
}
return len;
}
static OnigLen
tree_max_len(Node* node, ScanEnv* env)
{
OnigLen len;
OnigLen tmax;
len = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
do {
tmax = tree_max_len(NODE_CAR(node), env);
len = distance_add(len, tmax);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
do {
tmax = tree_max_len(NODE_CAR(node), env);
if (len < tmax) len = tmax;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
len = (OnigLen )(sn->end - sn->s);
}
break;
case NODE_CTYPE:
case NODE_CCLASS:
len = ONIGENC_MBC_MAXLEN_DIST(env->enc);
break;
case NODE_BACKREF:
if (! NODE_IS_CHECKER(node)) {
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
if (NODE_IS_RECURSION(node)) {
len = INFINITE_LEN;
break;
}
backs = BACKREFS_P(br);
for (i = 0; i < br->back_num; i++) {
tmax = tree_max_len(mem_env[backs[i]].node, env);
if (len < tmax) len = tmax;
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (! NODE_IS_RECURSION(node))
len = tree_max_len(NODE_BODY(node), env);
else
len = INFINITE_LEN;
break;
#endif
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->upper != 0) {
len = tree_max_len(NODE_BODY(node), env);
if (len != 0) {
if (! IS_REPEAT_INFINITE(qn->upper))
len = distance_multiply(len, qn->upper);
else
len = INFINITE_LEN;
}
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_MAX_FIXED(node))
len = en->max_len;
else {
if (NODE_IS_MARK1(node))
len = INFINITE_LEN;
else {
NODE_STATUS_ADD(node, MARK1);
len = tree_max_len(NODE_BODY(node), env);
NODE_STATUS_REMOVE(node, MARK1);
en->max_len = len;
NODE_STATUS_ADD(node, MAX_FIXED);
}
}
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
len = tree_max_len(NODE_BODY(node), env);
break;
case BAG_IF_ELSE:
{
OnigLen tlen, elen;
len = tree_max_len(NODE_BODY(node), env);
if (IS_NOT_NULL(en->te.Then)) {
tlen = tree_max_len(en->te.Then, env);
len = distance_add(len, tlen);
}
if (IS_NOT_NULL(en->te.Else))
elen = tree_max_len(en->te.Else, env);
else elen = 0;
if (elen > len) len = elen;
}
break;
}
}
break;
case NODE_ANCHOR:
case NODE_GIMMICK:
default:
break;
}
return len;
}
static int
check_backrefs(Node* node, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = check_backrefs(NODE_CAR(node), env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) {
r = 0;
break;
}
/* fall */
case NODE_QUANT:
r = check_backrefs(NODE_BODY(node), env);
break;
case NODE_BAG:
r = check_backrefs(NODE_BODY(node), env);
{
BagNode* en = BAG_(node);
if (en->type == BAG_IF_ELSE) {
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = check_backrefs(en->te.Then, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = check_backrefs(en->te.Else, env);
}
}
}
break;
case NODE_BACKREF:
{
int i;
BackRefNode* br = BACKREF_(node);
int* backs = BACKREFS_P(br);
MemEnv* mem_env = SCANENV_MEMENV(env);
for (i = 0; i < br->back_num; i++) {
if (backs[i] > env->num_mem)
return ONIGERR_INVALID_BACKREF;
NODE_STATUS_ADD(mem_env[backs[i]].node, BACKREF);
}
r = 0;
}
break;
default:
r = 0;
break;
}
return r;
}
#ifdef USE_CALL
#define RECURSION_EXIST (1<<0)
#define RECURSION_MUST (1<<1)
#define RECURSION_INFINITE (1<<2)
static int
infinite_recursive_call_check(Node* node, ScanEnv* env, int head)
{
int ret;
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
Node *x;
OnigLen min;
x = node;
do {
ret = infinite_recursive_call_check(NODE_CAR(x), env, head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= ret;
if (head != 0) {
min = tree_min_len(NODE_CAR(x), env);
if (min != 0) head = 0;
}
} while (IS_NOT_NULL(x = NODE_CDR(x)));
}
break;
case NODE_ALT:
{
int must;
must = RECURSION_MUST;
do {
ret = infinite_recursive_call_check(NODE_CAR(node), env, head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= (ret & RECURSION_EXIST);
must &= ret;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
r |= must;
}
break;
case NODE_QUANT:
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
if (r < 0) return r;
if ((r & RECURSION_MUST) != 0) {
if (QUANT_(node)->lower == 0)
r &= ~RECURSION_MUST;
}
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node)))
break;
/* fall */
case NODE_CALL:
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK2(node))
return 0;
else if (NODE_IS_MARK1(node))
return (head == 0 ? RECURSION_EXIST | RECURSION_MUST
: RECURSION_EXIST | RECURSION_MUST | RECURSION_INFINITE);
else {
NODE_STATUS_ADD(node, MARK2);
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
NODE_STATUS_REMOVE(node, MARK2);
}
}
else if (en->type == BAG_IF_ELSE) {
int eret;
ret = infinite_recursive_call_check(NODE_BODY(node), env, head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= ret;
if (IS_NOT_NULL(en->te.Then)) {
OnigLen min;
if (head != 0) {
min = tree_min_len(NODE_BODY(node), env);
}
else min = 0;
ret = infinite_recursive_call_check(en->te.Then, env, min != 0 ? 0:head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= ret;
}
if (IS_NOT_NULL(en->te.Else)) {
eret = infinite_recursive_call_check(en->te.Else, env, head);
if (eret < 0 || (eret & RECURSION_INFINITE) != 0) return eret;
r |= (eret & RECURSION_EXIST);
if ((eret & RECURSION_MUST) == 0)
r &= ~RECURSION_MUST;
}
}
else {
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
}
}
break;
default:
break;
}
return r;
}
static int
infinite_recursive_call_check_trav(Node* node, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = infinite_recursive_call_check_trav(NODE_CAR(node), env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) {
r = 0;
break;
}
/* fall */
case NODE_QUANT:
r = infinite_recursive_call_check_trav(NODE_BODY(node), env);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_RECURSION(node) && NODE_IS_CALLED(node)) {
int ret;
NODE_STATUS_ADD(node, MARK1);
ret = infinite_recursive_call_check(NODE_BODY(node), env, 1);
if (ret < 0) return ret;
else if ((ret & (RECURSION_MUST | RECURSION_INFINITE)) != 0)
return ONIGERR_NEVER_ENDING_RECURSION;
NODE_STATUS_REMOVE(node, MARK1);
}
}
else if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = infinite_recursive_call_check_trav(en->te.Then, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = infinite_recursive_call_check_trav(en->te.Else, env);
if (r != 0) return r;
}
}
}
r = infinite_recursive_call_check_trav(NODE_BODY(node), env);
break;
default:
r = 0;
break;
}
return r;
}
static int
recursive_call_check(Node* node)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
r = 0;
do {
r |= recursive_call_check(NODE_CAR(node));
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) {
r = 0;
break;
}
/* fall */
case NODE_QUANT:
r = recursive_call_check(NODE_BODY(node));
break;
case NODE_CALL:
r = recursive_call_check(NODE_BODY(node));
if (r != 0) {
if (NODE_IS_MARK1(NODE_BODY(node)))
NODE_STATUS_ADD(node, RECURSION);
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK2(node))
return 0;
else if (NODE_IS_MARK1(node))
return 1; /* recursion */
else {
NODE_STATUS_ADD(node, MARK2);
r = recursive_call_check(NODE_BODY(node));
NODE_STATUS_REMOVE(node, MARK2);
}
}
else if (en->type == BAG_IF_ELSE) {
r = 0;
if (IS_NOT_NULL(en->te.Then)) {
r |= recursive_call_check(en->te.Then);
}
if (IS_NOT_NULL(en->te.Else)) {
r |= recursive_call_check(en->te.Else);
}
r |= recursive_call_check(NODE_BODY(node));
}
else {
r = recursive_call_check(NODE_BODY(node));
}
}
break;
default:
r = 0;
break;
}
return r;
}
#define IN_RECURSION (1<<0)
#define FOUND_CALLED_NODE 1
static int
recursive_call_check_trav(Node* node, ScanEnv* env, int state)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
{
int ret;
do {
ret = recursive_call_check_trav(NODE_CAR(node), env, state);
if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE;
else if (ret < 0) return ret;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_QUANT:
r = recursive_call_check_trav(NODE_BODY(node), env, state);
if (QUANT_(node)->upper == 0) {
if (r == FOUND_CALLED_NODE)
QUANT_(node)->is_refered = 1;
}
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
if (ANCHOR_HAS_BODY(an))
r = recursive_call_check_trav(NODE_ANCHOR_BODY(an), env, state);
}
break;
case NODE_BAG:
{
int ret;
int state1;
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_CALLED(node) || (state & IN_RECURSION) != 0) {
if (! NODE_IS_RECURSION(node)) {
NODE_STATUS_ADD(node, MARK1);
r = recursive_call_check(NODE_BODY(node));
if (r != 0)
NODE_STATUS_ADD(node, RECURSION);
NODE_STATUS_REMOVE(node, MARK1);
}
if (NODE_IS_CALLED(node))
r = FOUND_CALLED_NODE;
}
}
state1 = state;
if (NODE_IS_RECURSION(node))
state1 |= IN_RECURSION;
ret = recursive_call_check_trav(NODE_BODY(node), env, state1);
if (ret == FOUND_CALLED_NODE)
r = FOUND_CALLED_NODE;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
ret = recursive_call_check_trav(en->te.Then, env, state1);
if (ret == FOUND_CALLED_NODE)
r = FOUND_CALLED_NODE;
}
if (IS_NOT_NULL(en->te.Else)) {
ret = recursive_call_check_trav(en->te.Else, env, state1);
if (ret == FOUND_CALLED_NODE)
r = FOUND_CALLED_NODE;
}
}
}
break;
default:
break;
}
return r;
}
#endif
#define IN_ALT (1<<0)
#define IN_NOT (1<<1)
#define IN_REAL_REPEAT (1<<2)
#define IN_VAR_REPEAT (1<<3)
#define IN_ZERO_REPEAT (1<<4)
#define IN_MULTI_ENTRY (1<<5)
#define IN_LOOK_BEHIND (1<<6)
/* divide different length alternatives in look-behind.
(?<=A|B) ==> (?<=A)|(?<=B)
(?<!A|B) ==> (?<!A)(?<!B)
*/
static int
divide_look_behind_alternatives(Node* node)
{
Node *head, *np, *insert_node;
AnchorNode* an = ANCHOR_(node);
int anc_type = an->type;
head = NODE_ANCHOR_BODY(an);
np = NODE_CAR(head);
swap_node(node, head);
NODE_CAR(node) = head;
NODE_BODY(head) = np;
np = node;
while (IS_NOT_NULL(np = NODE_CDR(np))) {
insert_node = onig_node_new_anchor(anc_type, an->ascii_mode);
CHECK_NULL_RETURN_MEMERR(insert_node);
NODE_BODY(insert_node) = NODE_CAR(np);
NODE_CAR(np) = insert_node;
}
if (anc_type == ANCR_LOOK_BEHIND_NOT) {
np = node;
do {
NODE_SET_TYPE(np, NODE_LIST); /* alt -> list */
} while (IS_NOT_NULL(np = NODE_CDR(np)));
}
return 0;
}
static int
setup_look_behind(Node* node, regex_t* reg, ScanEnv* env)
{
int r, len;
AnchorNode* an = ANCHOR_(node);
r = get_char_len_node(NODE_ANCHOR_BODY(an), reg, &len);
if (r == 0)
an->char_len = len;
else if (r == GET_CHAR_LEN_VARLEN)
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
else if (r == GET_CHAR_LEN_TOP_ALT_VARLEN) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND))
r = divide_look_behind_alternatives(node);
else
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
return r;
}
static int
next_setup(Node* node, Node* next_node, regex_t* reg)
{
NodeType type;
retry:
type = NODE_TYPE(node);
if (type == NODE_QUANT) {
QuantNode* qn = QUANT_(node);
if (qn->greedy && IS_REPEAT_INFINITE(qn->upper)) {
#ifdef USE_QUANT_PEEK_NEXT
Node* n = get_head_value_node(next_node, 1, reg);
/* '\0': for UTF-16BE etc... */
if (IS_NOT_NULL(n) && STR_(n)->s[0] != '\0') {
qn->next_head_exact = n;
}
#endif
/* automatic posseivation a*b ==> (?>a*)b */
if (qn->lower <= 1) {
if (NODE_IS_SIMPLE_TYPE(NODE_BODY(node))) {
Node *x, *y;
x = get_head_value_node(NODE_BODY(node), 0, reg);
if (IS_NOT_NULL(x)) {
y = get_head_value_node(next_node, 0, reg);
if (IS_NOT_NULL(y) && is_exclusive(x, y, reg)) {
Node* en = onig_node_new_bag(BAG_STOP_BACKTRACK);
CHECK_NULL_RETURN_MEMERR(en);
NODE_STATUS_ADD(en, STOP_BT_SIMPLE_REPEAT);
swap_node(node, en);
NODE_BODY(node) = en;
}
}
}
}
}
}
else if (type == NODE_BAG) {
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
node = NODE_BODY(node);
goto retry;
}
}
return 0;
}
static int
update_string_node_case_fold(regex_t* reg, Node *node)
{
UChar *p, *end, buf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
UChar *sbuf, *ebuf, *sp;
int r, i, len, sbuf_size;
StrNode* sn = STR_(node);
end = sn->end;
sbuf_size = (int )(end - sn->s) * 2;
sbuf = (UChar* )xmalloc(sbuf_size);
CHECK_NULL_RETURN_MEMERR(sbuf);
ebuf = sbuf + sbuf_size;
sp = sbuf;
p = sn->s;
while (p < end) {
len = ONIGENC_MBC_CASE_FOLD(reg->enc, reg->case_fold_flag, &p, end, buf);
for (i = 0; i < len; i++) {
if (sp >= ebuf) {
sbuf = (UChar* )xrealloc(sbuf, sbuf_size * 2);
CHECK_NULL_RETURN_MEMERR(sbuf);
sp = sbuf + sbuf_size;
sbuf_size *= 2;
ebuf = sbuf + sbuf_size;
}
*sp++ = buf[i];
}
}
r = onig_node_str_set(node, sbuf, sp);
if (r != 0) {
xfree(sbuf);
return r;
}
xfree(sbuf);
return 0;
}
static int
expand_case_fold_make_rem_string(Node** rnode, UChar *s, UChar *end, regex_t* reg)
{
int r;
Node *node;
node = onig_node_new_str(s, end);
if (IS_NULL(node)) return ONIGERR_MEMORY;
r = update_string_node_case_fold(reg, node);
if (r != 0) {
onig_node_free(node);
return r;
}
NODE_STRING_SET_AMBIG(node);
NODE_STRING_SET_DONT_GET_OPT_INFO(node);
*rnode = node;
return 0;
}
static int
expand_case_fold_string_alt(int item_num, OnigCaseFoldCodeItem items[], UChar *p,
int slen, UChar *end, regex_t* reg, Node **rnode)
{
int r, i, j;
int len;
int varlen;
Node *anode, *var_anode, *snode, *xnode, *an;
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
*rnode = var_anode = NULL_NODE;
varlen = 0;
for (i = 0; i < item_num; i++) {
if (items[i].byte_len != slen) {
varlen = 1;
break;
}
}
if (varlen != 0) {
*rnode = var_anode = onig_node_new_alt(NULL_NODE, NULL_NODE);
if (IS_NULL(var_anode)) return ONIGERR_MEMORY;
xnode = onig_node_new_list(NULL, NULL);
if (IS_NULL(xnode)) goto mem_err;
NODE_CAR(var_anode) = xnode;
anode = onig_node_new_alt(NULL_NODE, NULL_NODE);
if (IS_NULL(anode)) goto mem_err;
NODE_CAR(xnode) = anode;
}
else {
*rnode = anode = onig_node_new_alt(NULL_NODE, NULL_NODE);
if (IS_NULL(anode)) return ONIGERR_MEMORY;
}
snode = onig_node_new_str(p, p + slen);
if (IS_NULL(snode)) goto mem_err;
NODE_CAR(anode) = snode;
for (i = 0; i < item_num; i++) {
snode = onig_node_new_str(NULL, NULL);
if (IS_NULL(snode)) goto mem_err;
for (j = 0; j < items[i].code_len; j++) {
len = ONIGENC_CODE_TO_MBC(reg->enc, items[i].code[j], buf);
if (len < 0) {
r = len;
goto mem_err2;
}
r = onig_node_str_cat(snode, buf, buf + len);
if (r != 0) goto mem_err2;
}
an = onig_node_new_alt(NULL_NODE, NULL_NODE);
if (IS_NULL(an)) {
goto mem_err2;
}
if (items[i].byte_len != slen && IS_NOT_NULL(var_anode)) {
Node *rem;
UChar *q = p + items[i].byte_len;
if (q < end) {
r = expand_case_fold_make_rem_string(&rem, q, end, reg);
if (r != 0) {
onig_node_free(an);
goto mem_err2;
}
xnode = onig_node_list_add(NULL_NODE, snode);
if (IS_NULL(xnode)) {
onig_node_free(an);
onig_node_free(rem);
goto mem_err2;
}
if (IS_NULL(onig_node_list_add(xnode, rem))) {
onig_node_free(an);
onig_node_free(xnode);
onig_node_free(rem);
goto mem_err;
}
NODE_CAR(an) = xnode;
}
else {
NODE_CAR(an) = snode;
}
NODE_CDR(var_anode) = an;
var_anode = an;
}
else {
NODE_CAR(an) = snode;
NODE_CDR(anode) = an;
anode = an;
}
}
return varlen;
mem_err2:
onig_node_free(snode);
mem_err:
onig_node_free(*rnode);
return ONIGERR_MEMORY;
}
static int
is_good_case_fold_items_for_search(OnigEncoding enc, int slen,
int n, OnigCaseFoldCodeItem items[])
{
int i, len;
UChar buf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
if (item->code_len != 1) return 0;
if (item->byte_len != slen) return 0;
len = ONIGENC_CODE_TO_MBC(enc, item->code[0], buf);
if (len != slen) return 0;
}
return 1;
}
#define THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION 8
static int
expand_case_fold_string(Node* node, regex_t* reg, int state)
{
int r, n, len, alt_num;
int fold_len;
int prev_is_ambig, prev_is_good, is_good, is_in_look_behind;
UChar *start, *end, *p;
UChar* foldp;
Node *top_root, *root, *snode, *prev_node;
OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
UChar buf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
StrNode* sn;
if (NODE_STRING_IS_AMBIG(node)) return 0;
sn = STR_(node);
start = sn->s;
end = sn->end;
if (start >= end) return 0;
is_in_look_behind = (state & IN_LOOK_BEHIND) != 0;
r = 0;
top_root = root = prev_node = snode = NULL_NODE;
alt_num = 1;
p = start;
while (p < end) {
n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(reg->enc, reg->case_fold_flag,
p, end, items);
if (n < 0) {
r = n;
goto err;
}
len = enclen(reg->enc, p);
is_good = is_good_case_fold_items_for_search(reg->enc, len, n, items);
if (is_in_look_behind ||
(IS_NOT_NULL(snode) ||
(is_good
/* expand single char case: ex. /(?i:a)/ */
&& !(p == start && p + len >= end)))) {
if (IS_NULL(snode)) {
if (IS_NULL(root) && IS_NOT_NULL(prev_node)) {
top_root = root = onig_node_list_add(NULL_NODE, prev_node);
if (IS_NULL(root)) {
onig_node_free(prev_node);
goto mem_err;
}
}
prev_node = snode = onig_node_new_str(NULL, NULL);
if (IS_NULL(snode)) goto mem_err;
if (IS_NOT_NULL(root)) {
if (IS_NULL(onig_node_list_add(root, snode))) {
onig_node_free(snode);
goto mem_err;
}
}
prev_is_ambig = -1; /* -1: new */
prev_is_good = 0; /* escape compiler warning */
}
else {
prev_is_ambig = NODE_STRING_IS_AMBIG(snode);
prev_is_good = NODE_STRING_IS_GOOD_AMBIG(snode);
}
if (n != 0) {
foldp = p;
fold_len = ONIGENC_MBC_CASE_FOLD(reg->enc, reg->case_fold_flag,
&foldp, end, buf);
foldp = buf;
}
else {
foldp = p; fold_len = len;
}
if ((prev_is_ambig == 0 && n != 0) ||
(prev_is_ambig > 0 && (n == 0 || prev_is_good != is_good))) {
if (IS_NULL(root) /* && IS_NOT_NULL(prev_node) */) {
top_root = root = onig_node_list_add(NULL_NODE, prev_node);
if (IS_NULL(root)) {
onig_node_free(prev_node);
goto mem_err;
}
}
prev_node = snode = onig_node_new_str(foldp, foldp + fold_len);
if (IS_NULL(snode)) goto mem_err;
if (IS_NULL(onig_node_list_add(root, snode))) {
onig_node_free(snode);
goto mem_err;
}
}
else {
r = onig_node_str_cat(snode, foldp, foldp + fold_len);
if (r != 0) goto err;
}
if (n != 0) NODE_STRING_SET_AMBIG(snode);
if (is_good != 0) NODE_STRING_SET_GOOD_AMBIG(snode);
}
else {
alt_num *= (n + 1);
if (alt_num > THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION) break;
if (IS_NULL(root) && IS_NOT_NULL(prev_node)) {
top_root = root = onig_node_list_add(NULL_NODE, prev_node);
if (IS_NULL(root)) {
onig_node_free(prev_node);
goto mem_err;
}
}
r = expand_case_fold_string_alt(n, items, p, len, end, reg, &prev_node);
if (r < 0) goto mem_err;
if (r == 1) {
if (IS_NULL(root)) {
top_root = prev_node;
}
else {
if (IS_NULL(onig_node_list_add(root, prev_node))) {
onig_node_free(prev_node);
goto mem_err;
}
}
root = NODE_CAR(prev_node);
}
else { /* r == 0 */
if (IS_NOT_NULL(root)) {
if (IS_NULL(onig_node_list_add(root, prev_node))) {
onig_node_free(prev_node);
goto mem_err;
}
}
}
snode = NULL_NODE;
}
p += len;
}
if (p < end) {
Node *srem;
r = expand_case_fold_make_rem_string(&srem, p, end, reg);
if (r != 0) goto mem_err;
if (IS_NOT_NULL(prev_node) && IS_NULL(root)) {
top_root = root = onig_node_list_add(NULL_NODE, prev_node);
if (IS_NULL(root)) {
onig_node_free(srem);
onig_node_free(prev_node);
goto mem_err;
}
}
if (IS_NULL(root)) {
prev_node = srem;
}
else {
if (IS_NULL(onig_node_list_add(root, srem))) {
onig_node_free(srem);
goto mem_err;
}
}
}
/* ending */
top_root = (IS_NOT_NULL(top_root) ? top_root : prev_node);
swap_node(node, top_root);
onig_node_free(top_root);
return 0;
mem_err:
r = ONIGERR_MEMORY;
err:
onig_node_free(top_root);
return r;
}
#ifdef USE_INSISTENT_CHECK_CAPTURES_IN_EMPTY_REPEAT
static enum BodyEmpty
quantifiers_memory_node_info(Node* node)
{
int r = BODY_IS_EMPTY;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
{
int v;
do {
v = quantifiers_memory_node_info(NODE_CAR(node));
if (v > r) r = v;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (NODE_IS_RECURSION(node)) {
return BODY_IS_EMPTY_REC; /* tiny version */
}
else
r = quantifiers_memory_node_info(NODE_BODY(node));
break;
#endif
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->upper != 0) {
r = quantifiers_memory_node_info(NODE_BODY(node));
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_RECURSION(node)) {
return BODY_IS_EMPTY_REC;
}
return BODY_IS_EMPTY_MEM;
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
r = quantifiers_memory_node_info(NODE_BODY(node));
break;
case BAG_IF_ELSE:
{
int v;
r = quantifiers_memory_node_info(NODE_BODY(node));
if (IS_NOT_NULL(en->te.Then)) {
v = quantifiers_memory_node_info(en->te.Then);
if (v > r) r = v;
}
if (IS_NOT_NULL(en->te.Else)) {
v = quantifiers_memory_node_info(en->te.Else);
if (v > r) r = v;
}
}
break;
}
}
break;
case NODE_BACKREF:
case NODE_STRING:
case NODE_CTYPE:
case NODE_CCLASS:
case NODE_ANCHOR:
case NODE_GIMMICK:
default:
break;
}
return r;
}
#endif /* USE_INSISTENT_CHECK_CAPTURES_IN_EMPTY_REPEAT */
#ifdef USE_CALL
#ifdef __GNUC__
__inline
#endif
static int
setup_call_node_call(CallNode* cn, ScanEnv* env, int state)
{
MemEnv* mem_env = SCANENV_MEMENV(env);
if (cn->by_number != 0) {
int gnum = cn->group_num;
if (env->num_named > 0 &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&
! ONIG_IS_OPTION_ON(env->options, ONIG_OPTION_CAPTURE_GROUP)) {
return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
}
if (gnum > env->num_mem) {
onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_GROUP_REFERENCE,
cn->name, cn->name_end);
return ONIGERR_UNDEFINED_GROUP_REFERENCE;
}
set_call_attr:
NODE_CALL_BODY(cn) = mem_env[cn->group_num].node;
if (IS_NULL(NODE_CALL_BODY(cn))) {
onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE,
cn->name, cn->name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
}
else {
int *refs;
int n = onig_name_to_group_numbers(env->reg, cn->name, cn->name_end, &refs);
if (n <= 0) {
onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE,
cn->name, cn->name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
else if (n > 1) {
onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINITION_NAME_CALL,
cn->name, cn->name_end);
return ONIGERR_MULTIPLEX_DEFINITION_NAME_CALL;
}
else {
cn->group_num = refs[0];
goto set_call_attr;
}
}
return 0;
}
static void
setup_call2_call(Node* node)
{
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
setup_call2_call(NODE_CAR(node));
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
setup_call2_call(NODE_BODY(node));
break;
case NODE_ANCHOR:
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
setup_call2_call(NODE_BODY(node));
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (! NODE_IS_MARK1(node)) {
NODE_STATUS_ADD(node, MARK1);
setup_call2_call(NODE_BODY(node));
NODE_STATUS_REMOVE(node, MARK1);
}
}
else if (en->type == BAG_IF_ELSE) {
setup_call2_call(NODE_BODY(node));
if (IS_NOT_NULL(en->te.Then))
setup_call2_call(en->te.Then);
if (IS_NOT_NULL(en->te.Else))
setup_call2_call(en->te.Else);
}
else {
setup_call2_call(NODE_BODY(node));
}
}
break;
case NODE_CALL:
if (! NODE_IS_MARK1(node)) {
NODE_STATUS_ADD(node, MARK1);
{
CallNode* cn = CALL_(node);
Node* called = NODE_CALL_BODY(cn);
cn->entry_count++;
NODE_STATUS_ADD(called, CALLED);
BAG_(called)->m.entry_count++;
setup_call2_call(called);
}
NODE_STATUS_REMOVE(node, MARK1);
}
break;
default:
break;
}
}
static int
setup_call(Node* node, ScanEnv* env, int state)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = setup_call(NODE_CAR(node), env, state);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
if (QUANT_(node)->upper == 0)
state |= IN_ZERO_REPEAT;
r = setup_call(NODE_BODY(node), env, state);
break;
case NODE_ANCHOR:
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
r = setup_call(NODE_BODY(node), env, state);
else
r = 0;
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if ((state & IN_ZERO_REPEAT) != 0) {
NODE_STATUS_ADD(node, IN_ZERO_REPEAT);
BAG_(node)->m.entry_count--;
}
r = setup_call(NODE_BODY(node), env, state);
}
else if (en->type == BAG_IF_ELSE) {
r = setup_call(NODE_BODY(node), env, state);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = setup_call(en->te.Then, env, state);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else))
r = setup_call(en->te.Else, env, state);
}
else
r = setup_call(NODE_BODY(node), env, state);
}
break;
case NODE_CALL:
if ((state & IN_ZERO_REPEAT) != 0) {
NODE_STATUS_ADD(node, IN_ZERO_REPEAT);
CALL_(node)->entry_count--;
}
r = setup_call_node_call(CALL_(node), env, state);
break;
default:
r = 0;
break;
}
return r;
}
static int
setup_call2(Node* node)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = setup_call2(NODE_CAR(node));
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
if (QUANT_(node)->upper != 0)
r = setup_call2(NODE_BODY(node));
break;
case NODE_ANCHOR:
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
r = setup_call2(NODE_BODY(node));
break;
case NODE_BAG:
if (! NODE_IS_IN_ZERO_REPEAT(node))
r = setup_call2(NODE_BODY(node));
{
BagNode* en = BAG_(node);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = setup_call2(en->te.Then);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else))
r = setup_call2(en->te.Else);
}
}
break;
case NODE_CALL:
if (! NODE_IS_IN_ZERO_REPEAT(node)) {
setup_call2_call(node);
}
break;
default:
break;
}
return r;
}
static void
setup_called_state_call(Node* node, int state)
{
switch (NODE_TYPE(node)) {
case NODE_ALT:
state |= IN_ALT;
/* fall */
case NODE_LIST:
do {
setup_called_state_call(NODE_CAR(node), state);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (IS_REPEAT_INFINITE(qn->upper) || qn->upper >= 2)
state |= IN_REAL_REPEAT;
if (qn->lower != qn->upper)
state |= IN_VAR_REPEAT;
setup_called_state_call(NODE_QUANT_BODY(qn), state);
}
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
switch (an->type) {
case ANCR_PREC_READ_NOT:
case ANCR_LOOK_BEHIND_NOT:
state |= IN_NOT;
/* fall */
case ANCR_PREC_READ:
case ANCR_LOOK_BEHIND:
setup_called_state_call(NODE_ANCHOR_BODY(an), state);
break;
default:
break;
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK1(node)) {
if ((~en->m.called_state & state) != 0) {
en->m.called_state |= state;
setup_called_state_call(NODE_BODY(node), state);
}
}
else {
NODE_STATUS_ADD(node, MARK1);
en->m.called_state |= state;
setup_called_state_call(NODE_BODY(node), state);
NODE_STATUS_REMOVE(node, MARK1);
}
}
else if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
setup_called_state_call(en->te.Then, state);
}
if (IS_NOT_NULL(en->te.Else))
setup_called_state_call(en->te.Else, state);
}
else {
setup_called_state_call(NODE_BODY(node), state);
}
}
break;
case NODE_CALL:
setup_called_state_call(NODE_BODY(node), state);
break;
default:
break;
}
}
static void
setup_called_state(Node* node, int state)
{
switch (NODE_TYPE(node)) {
case NODE_ALT:
state |= IN_ALT;
/* fall */
case NODE_LIST:
do {
setup_called_state(NODE_CAR(node), state);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
#ifdef USE_CALL
case NODE_CALL:
setup_called_state_call(node, state);
break;
#endif
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (en->m.entry_count > 1)
state |= IN_MULTI_ENTRY;
en->m.called_state |= state;
/* fall */
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
setup_called_state(NODE_BODY(node), state);
break;
case BAG_IF_ELSE:
setup_called_state(NODE_BODY(node), state);
if (IS_NOT_NULL(en->te.Then))
setup_called_state(en->te.Then, state);
if (IS_NOT_NULL(en->te.Else))
setup_called_state(en->te.Else, state);
break;
}
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (IS_REPEAT_INFINITE(qn->upper) || qn->upper >= 2)
state |= IN_REAL_REPEAT;
if (qn->lower != qn->upper)
state |= IN_VAR_REPEAT;
setup_called_state(NODE_QUANT_BODY(qn), state);
}
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
switch (an->type) {
case ANCR_PREC_READ_NOT:
case ANCR_LOOK_BEHIND_NOT:
state |= IN_NOT;
/* fall */
case ANCR_PREC_READ:
case ANCR_LOOK_BEHIND:
setup_called_state(NODE_ANCHOR_BODY(an), state);
break;
default:
break;
}
}
break;
case NODE_BACKREF:
case NODE_STRING:
case NODE_CTYPE:
case NODE_CCLASS:
case NODE_GIMMICK:
default:
break;
}
}
#endif /* USE_CALL */
static int setup_tree(Node* node, regex_t* reg, int state, ScanEnv* env);
#ifdef __GNUC__
__inline
#endif
static int
setup_anchor(Node* node, regex_t* reg, int state, ScanEnv* env)
{
/* allowed node types in look-behind */
#define ALLOWED_TYPE_IN_LB \
( NODE_BIT_LIST | NODE_BIT_ALT | NODE_BIT_STRING | NODE_BIT_CCLASS \
| NODE_BIT_CTYPE | NODE_BIT_ANCHOR | NODE_BIT_BAG | NODE_BIT_QUANT \
| NODE_BIT_CALL | NODE_BIT_GIMMICK)
#define ALLOWED_BAG_IN_LB ( 1<<BAG_MEMORY | 1<<BAG_OPTION | 1<<BAG_IF_ELSE )
#define ALLOWED_BAG_IN_LB_NOT ( 1<<BAG_OPTION | 1<<BAG_IF_ELSE )
#define ALLOWED_ANCHOR_IN_LB \
( ANCR_LOOK_BEHIND | ANCR_BEGIN_LINE | ANCR_END_LINE | ANCR_BEGIN_BUF \
| ANCR_BEGIN_POSITION | ANCR_WORD_BOUNDARY | ANCR_NO_WORD_BOUNDARY \
| ANCR_WORD_BEGIN | ANCR_WORD_END \
| ANCR_TEXT_SEGMENT_BOUNDARY | ANCR_NO_TEXT_SEGMENT_BOUNDARY )
#define ALLOWED_ANCHOR_IN_LB_NOT \
( ANCR_LOOK_BEHIND | ANCR_LOOK_BEHIND_NOT | ANCR_BEGIN_LINE \
| ANCR_END_LINE | ANCR_BEGIN_BUF | ANCR_BEGIN_POSITION | ANCR_WORD_BOUNDARY \
| ANCR_NO_WORD_BOUNDARY | ANCR_WORD_BEGIN | ANCR_WORD_END \
| ANCR_TEXT_SEGMENT_BOUNDARY | ANCR_NO_TEXT_SEGMENT_BOUNDARY )
int r;
AnchorNode* an = ANCHOR_(node);
switch (an->type) {
case ANCR_PREC_READ:
r = setup_tree(NODE_ANCHOR_BODY(an), reg, state, env);
break;
case ANCR_PREC_READ_NOT:
r = setup_tree(NODE_ANCHOR_BODY(an), reg, (state | IN_NOT), env);
break;
case ANCR_LOOK_BEHIND:
{
r = check_type_tree(NODE_ANCHOR_BODY(an), ALLOWED_TYPE_IN_LB,
ALLOWED_BAG_IN_LB, ALLOWED_ANCHOR_IN_LB);
if (r < 0) return r;
if (r > 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
r = setup_tree(NODE_ANCHOR_BODY(an), reg, (state|IN_LOOK_BEHIND), env);
if (r != 0) return r;
r = setup_look_behind(node, reg, env);
}
break;
case ANCR_LOOK_BEHIND_NOT:
{
r = check_type_tree(NODE_ANCHOR_BODY(an), ALLOWED_TYPE_IN_LB,
ALLOWED_BAG_IN_LB_NOT, ALLOWED_ANCHOR_IN_LB_NOT);
if (r < 0) return r;
if (r > 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
r = setup_tree(NODE_ANCHOR_BODY(an), reg, (state|IN_NOT|IN_LOOK_BEHIND),
env);
if (r != 0) return r;
r = setup_look_behind(node, reg, env);
}
break;
default:
r = 0;
break;
}
return r;
}
#ifdef __GNUC__
__inline
#endif
static int
setup_quant(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r;
OnigLen d;
QuantNode* qn = QUANT_(node);
Node* body = NODE_BODY(node);
if ((state & IN_REAL_REPEAT) != 0) {
NODE_STATUS_ADD(node, IN_REAL_REPEAT);
}
if ((state & IN_MULTI_ENTRY) != 0) {
NODE_STATUS_ADD(node, IN_MULTI_ENTRY);
}
if (IS_REPEAT_INFINITE(qn->upper) || qn->upper >= 1) {
d = tree_min_len(body, env);
if (d == 0) {
#ifdef USE_INSISTENT_CHECK_CAPTURES_IN_EMPTY_REPEAT
qn->empty_info = quantifiers_memory_node_info(body);
if (qn->empty_info == BODY_IS_EMPTY_REC) {
if (NODE_TYPE(body) == NODE_BAG &&
BAG_(body)->type == BAG_MEMORY) {
MEM_STATUS_ON(env->bt_mem_end, BAG_(body)->m.regnum);
}
}
#else
qn->empty_info = BODY_IS_EMPTY;
#endif
}
}
if (IS_REPEAT_INFINITE(qn->upper) || qn->upper >= 2)
state |= IN_REAL_REPEAT;
if (qn->lower != qn->upper)
state |= IN_VAR_REPEAT;
r = setup_tree(body, reg, state, env);
if (r != 0) return r;
/* expand string */
#define EXPAND_STRING_MAX_LENGTH 100
if (NODE_TYPE(body) == NODE_STRING) {
if (!IS_REPEAT_INFINITE(qn->lower) && qn->lower == qn->upper &&
qn->lower > 1 && qn->lower <= EXPAND_STRING_MAX_LENGTH) {
int len = NODE_STRING_LEN(body);
StrNode* sn = STR_(body);
if (len * qn->lower <= EXPAND_STRING_MAX_LENGTH) {
int i, n = qn->lower;
onig_node_conv_to_str_node(node, STR_(body)->flag);
for (i = 0; i < n; i++) {
r = onig_node_str_cat(node, sn->s, sn->end);
if (r != 0) return r;
}
onig_node_free(body);
return r;
}
}
}
if (qn->greedy && (qn->empty_info == BODY_IS_NOT_EMPTY)) {
if (NODE_TYPE(body) == NODE_QUANT) {
QuantNode* tqn = QUANT_(body);
if (IS_NOT_NULL(tqn->head_exact)) {
qn->head_exact = tqn->head_exact;
tqn->head_exact = NULL;
}
}
else {
qn->head_exact = get_head_value_node(NODE_BODY(node), 1, reg);
}
}
return r;
}
/* setup_tree does the following work.
1. check empty loop. (set qn->empty_info)
2. expand ignore-case in char class.
3. set memory status bit flags. (reg->mem_stats)
4. set qn->head_exact for [push, exact] -> [push_or_jump_exact1, exact].
5. find invalid patterns in look-behind.
6. expand repeated string.
*/
static int
setup_tree(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
Node* prev = NULL_NODE;
do {
r = setup_tree(NODE_CAR(node), reg, state, env);
if (IS_NOT_NULL(prev) && r == 0) {
r = next_setup(prev, NODE_CAR(node), reg);
}
prev = NODE_CAR(node);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_ALT:
do {
r = setup_tree(NODE_CAR(node), reg, (state | IN_ALT), env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_STRING:
if (IS_IGNORECASE(reg->options) && !NODE_STRING_IS_RAW(node)) {
r = expand_case_fold_string(node, reg, state);
}
break;
case NODE_BACKREF:
{
int i;
int* p;
BackRefNode* br = BACKREF_(node);
p = BACKREFS_P(br);
for (i = 0; i < br->back_num; i++) {
if (p[i] > env->num_mem) return ONIGERR_INVALID_BACKREF;
MEM_STATUS_ON(env->backrefed_mem, p[i]);
MEM_STATUS_ON(env->bt_mem_start, p[i]);
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
MEM_STATUS_ON(env->bt_mem_end, p[i]);
}
#endif
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_OPTION:
{
OnigOptionType options = reg->options;
reg->options = BAG_(node)->o.options;
r = setup_tree(NODE_BODY(node), reg, state, env);
reg->options = options;
}
break;
case BAG_MEMORY:
#ifdef USE_CALL
state |= en->m.called_state;
#endif
if ((state & (IN_ALT | IN_NOT | IN_VAR_REPEAT | IN_MULTI_ENTRY)) != 0
|| NODE_IS_RECURSION(node)) {
MEM_STATUS_ON(env->bt_mem_start, en->m.regnum);
}
r = setup_tree(NODE_BODY(node), reg, state, env);
break;
case BAG_STOP_BACKTRACK:
{
Node* target = NODE_BODY(node);
r = setup_tree(target, reg, state, env);
if (NODE_TYPE(target) == NODE_QUANT) {
QuantNode* tqn = QUANT_(target);
if (IS_REPEAT_INFINITE(tqn->upper) && tqn->lower <= 1 &&
tqn->greedy != 0) { /* (?>a*), a*+ etc... */
if (NODE_IS_SIMPLE_TYPE(NODE_BODY(target)))
NODE_STATUS_ADD(node, STOP_BT_SIMPLE_REPEAT);
}
}
}
break;
case BAG_IF_ELSE:
r = setup_tree(NODE_BODY(node), reg, (state | IN_ALT), env);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = setup_tree(en->te.Then, reg, (state | IN_ALT), env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else))
r = setup_tree(en->te.Else, reg, (state | IN_ALT), env);
break;
}
}
break;
case NODE_QUANT:
r = setup_quant(node, reg, state, env);
break;
case NODE_ANCHOR:
r = setup_anchor(node, reg, state, env);
break;
#ifdef USE_CALL
case NODE_CALL:
#endif
case NODE_CTYPE:
case NODE_CCLASS:
case NODE_GIMMICK:
default:
break;
}
return r;
}
static int
set_sunday_quick_search_or_bmh_skip_table(regex_t* reg, int case_expand,
UChar* s, UChar* end,
UChar skip[], int* roffset)
{
int i, j, k, len, offset;
int n, clen;
UChar* p;
OnigEncoding enc;
OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
UChar buf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
enc = reg->enc;
offset = ENC_GET_SKIP_OFFSET(enc);
if (offset == ENC_SKIP_OFFSET_1_OR_0) {
UChar* p = s;
while (1) {
len = enclen(enc, p);
if (p + len >= end) {
if (len == 1) offset = 1;
else offset = 0;
break;
}
p += len;
}
}
len = (int )(end - s);
if (len + offset >= UCHAR_MAX)
return ONIGERR_PARSER_BUG;
*roffset = offset;
for (i = 0; i < CHAR_MAP_SIZE; i++) {
skip[i] = (UChar )(len + offset);
}
for (p = s; p < end; ) {
int z;
clen = enclen(enc, p);
if (p + clen > end) clen = (int )(end - p);
len = (int )(end - p);
for (j = 0; j < clen; j++) {
z = len - j + (offset - 1);
if (z <= 0) break;
skip[p[j]] = z;
}
if (case_expand != 0) {
n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, reg->case_fold_flag,
p, end, items);
for (k = 0; k < n; k++) {
ONIGENC_CODE_TO_MBC(enc, items[k].code[0], buf);
for (j = 0; j < clen; j++) {
z = len - j + (offset - 1);
if (z <= 0) break;
if (skip[buf[j]] > z)
skip[buf[j]] = z;
}
}
}
p += clen;
}
return 0;
}
#define OPT_EXACT_MAXLEN 24
#if OPT_EXACT_MAXLEN >= UCHAR_MAX
#error Too big OPT_EXACT_MAXLEN
#endif
typedef struct {
OnigLen min; /* min byte length */
OnigLen max; /* max byte length */
} MinMax;
typedef struct {
MinMax mmd;
OnigEncoding enc;
OnigOptionType options;
OnigCaseFoldType case_fold_flag;
ScanEnv* scan_env;
} OptEnv;
typedef struct {
int left;
int right;
} OptAnc;
typedef struct {
MinMax mmd; /* position */
OptAnc anc;
int reach_end;
int case_fold;
int good_case_fold;
int len;
UChar s[OPT_EXACT_MAXLEN];
} OptStr;
typedef struct {
MinMax mmd; /* position */
OptAnc anc;
int value; /* weighted value */
UChar map[CHAR_MAP_SIZE];
} OptMap;
typedef struct {
MinMax len;
OptAnc anc;
OptStr sb; /* boundary */
OptStr sm; /* middle */
OptStr spr; /* prec read (?=...) */
OptMap map; /* boundary */
} OptNode;
static int
map_position_value(OnigEncoding enc, int i)
{
static const short int Vals[] = {
5, 1, 1, 1, 1, 1, 1, 1, 1, 10, 10, 1, 1, 10, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
12, 4, 7, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5,
5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 6, 5, 5, 5,
5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 1
};
if (i < (int )(sizeof(Vals)/sizeof(Vals[0]))) {
if (i == 0 && ONIGENC_MBC_MINLEN(enc) > 1)
return 20;
else
return (int )Vals[i];
}
else
return 4; /* Take it easy. */
}
static int
distance_value(MinMax* mm)
{
/* 1000 / (min-max-dist + 1) */
static const short int dist_vals[] = {
1000, 500, 333, 250, 200, 167, 143, 125, 111, 100,
91, 83, 77, 71, 67, 63, 59, 56, 53, 50,
48, 45, 43, 42, 40, 38, 37, 36, 34, 33,
32, 31, 30, 29, 29, 28, 27, 26, 26, 25,
24, 24, 23, 23, 22, 22, 21, 21, 20, 20,
20, 19, 19, 19, 18, 18, 18, 17, 17, 17,
16, 16, 16, 16, 15, 15, 15, 15, 14, 14,
14, 14, 14, 14, 13, 13, 13, 13, 13, 13,
12, 12, 12, 12, 12, 12, 11, 11, 11, 11,
11, 11, 11, 11, 11, 10, 10, 10, 10, 10
};
OnigLen d;
if (mm->max == INFINITE_LEN) return 0;
d = mm->max - mm->min;
if (d < (OnigLen )(sizeof(dist_vals)/sizeof(dist_vals[0])))
/* return dist_vals[d] * 16 / (mm->min + 12); */
return (int )dist_vals[d];
else
return 1;
}
static int
comp_distance_value(MinMax* d1, MinMax* d2, int v1, int v2)
{
if (v2 <= 0) return -1;
if (v1 <= 0) return 1;
v1 *= distance_value(d1);
v2 *= distance_value(d2);
if (v2 > v1) return 1;
if (v2 < v1) return -1;
if (d2->min < d1->min) return 1;
if (d2->min > d1->min) return -1;
return 0;
}
static int
is_equal_mml(MinMax* a, MinMax* b)
{
return a->min == b->min && a->max == b->max;
}
static void
set_mml(MinMax* l, OnigLen min, OnigLen max)
{
l->min = min;
l->max = max;
}
static void
clear_mml(MinMax* l)
{
l->min = l->max = 0;
}
static void
copy_mml(MinMax* to, MinMax* from)
{
to->min = from->min;
to->max = from->max;
}
static void
add_mml(MinMax* to, MinMax* from)
{
to->min = distance_add(to->min, from->min);
to->max = distance_add(to->max, from->max);
}
static void
alt_merge_mml(MinMax* to, MinMax* from)
{
if (to->min > from->min) to->min = from->min;
if (to->max < from->max) to->max = from->max;
}
static void
copy_opt_env(OptEnv* to, OptEnv* from)
{
*to = *from;
}
static void
clear_opt_anc_info(OptAnc* a)
{
a->left = 0;
a->right = 0;
}
static void
copy_opt_anc_info(OptAnc* to, OptAnc* from)
{
*to = *from;
}
static void
concat_opt_anc_info(OptAnc* to, OptAnc* left, OptAnc* right,
OnigLen left_len, OnigLen right_len)
{
clear_opt_anc_info(to);
to->left = left->left;
if (left_len == 0) {
to->left |= right->left;
}
to->right = right->right;
if (right_len == 0) {
to->right |= left->right;
}
else {
to->right |= (left->right & ANCR_PREC_READ_NOT);
}
}
static int
is_left(int a)
{
if (a == ANCR_END_BUF || a == ANCR_SEMI_END_BUF ||
a == ANCR_END_LINE || a == ANCR_PREC_READ || a == ANCR_PREC_READ_NOT)
return 0;
return 1;
}
static int
is_set_opt_anc_info(OptAnc* to, int anc)
{
if ((to->left & anc) != 0) return 1;
return ((to->right & anc) != 0 ? 1 : 0);
}
static void
add_opt_anc_info(OptAnc* to, int anc)
{
if (is_left(anc))
to->left |= anc;
else
to->right |= anc;
}
static void
remove_opt_anc_info(OptAnc* to, int anc)
{
if (is_left(anc))
to->left &= ~anc;
else
to->right &= ~anc;
}
static void
alt_merge_opt_anc_info(OptAnc* to, OptAnc* add)
{
to->left &= add->left;
to->right &= add->right;
}
static int
is_full_opt_exact(OptStr* e)
{
return e->len >= OPT_EXACT_MAXLEN;
}
static void
clear_opt_exact(OptStr* e)
{
clear_mml(&e->mmd);
clear_opt_anc_info(&e->anc);
e->reach_end = 0;
e->case_fold = 0;
e->good_case_fold = 0;
e->len = 0;
e->s[0] = '\0';
}
static void
copy_opt_exact(OptStr* to, OptStr* from)
{
*to = *from;
}
static int
concat_opt_exact(OptStr* to, OptStr* add, OnigEncoding enc)
{
int i, j, len, r;
UChar *p, *end;
OptAnc tanc;
if (add->case_fold != 0) {
if (! to->case_fold) {
if (to->len > 1 || to->len >= add->len) return 0; /* avoid */
to->case_fold = 1;
}
else {
if (to->good_case_fold != 0) {
if (add->good_case_fold == 0) return 0;
}
}
}
r = 0;
p = add->s;
end = p + add->len;
for (i = to->len; p < end; ) {
len = enclen(enc, p);
if (i + len > OPT_EXACT_MAXLEN) {
r = 1; /* 1:full */
break;
}
for (j = 0; j < len && p < end; j++)
to->s[i++] = *p++;
}
to->len = i;
to->reach_end = (p == end ? add->reach_end : 0);
concat_opt_anc_info(&tanc, &to->anc, &add->anc, 1, 1);
if (! to->reach_end) tanc.right = 0;
copy_opt_anc_info(&to->anc, &tanc);
return r;
}
static void
concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc)
{
int i, j, len;
UChar *p;
for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) {
len = enclen(enc, p);
if (i + len > OPT_EXACT_MAXLEN) break;
for (j = 0; j < len && p < end; j++)
to->s[i++] = *p++;
}
to->len = i;
if (p >= end && to->len == (int )(end - s))
to->reach_end = 1;
}
static void
alt_merge_opt_exact(OptStr* to, OptStr* add, OptEnv* env)
{
int i, j, len;
if (add->len == 0 || to->len == 0) {
clear_opt_exact(to);
return ;
}
if (! is_equal_mml(&to->mmd, &add->mmd)) {
clear_opt_exact(to);
return ;
}
for (i = 0; i < to->len && i < add->len; ) {
if (to->s[i] != add->s[i]) break;
len = enclen(env->enc, to->s + i);
for (j = 1; j < len; j++) {
if (to->s[i+j] != add->s[i+j]) break;
}
if (j < len) break;
i += len;
}
if (! add->reach_end || i < add->len || i < to->len) {
to->reach_end = 0;
}
to->len = i;
if (add->case_fold != 0)
to->case_fold = 1;
if (add->good_case_fold == 0)
to->good_case_fold = 0;
alt_merge_opt_anc_info(&to->anc, &add->anc);
if (! to->reach_end) to->anc.right = 0;
}
static void
select_opt_exact(OnigEncoding enc, OptStr* now, OptStr* alt)
{
int vn, va;
vn = now->len;
va = alt->len;
if (va == 0) {
return ;
}
else if (vn == 0) {
copy_opt_exact(now, alt);
return ;
}
else if (vn <= 2 && va <= 2) {
/* ByteValTable[x] is big value --> low price */
va = map_position_value(enc, now->s[0]);
vn = map_position_value(enc, alt->s[0]);
if (now->len > 1) vn += 5;
if (alt->len > 1) va += 5;
}
if (now->case_fold == 0) vn *= 2;
if (alt->case_fold == 0) va *= 2;
if (now->good_case_fold != 0) vn *= 4;
if (alt->good_case_fold != 0) va *= 4;
if (comp_distance_value(&now->mmd, &alt->mmd, vn, va) > 0)
copy_opt_exact(now, alt);
}
static void
clear_opt_map(OptMap* map)
{
static const OptMap clean_info = {
{0, 0}, {0, 0}, 0,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
};
xmemcpy(map, &clean_info, sizeof(OptMap));
}
static void
copy_opt_map(OptMap* to, OptMap* from)
{
*to = *from;
}
static void
add_char_opt_map(OptMap* m, UChar c, OnigEncoding enc)
{
if (m->map[c] == 0) {
m->map[c] = 1;
m->value += map_position_value(enc, c);
}
}
static int
add_char_amb_opt_map(OptMap* map, UChar* p, UChar* end,
OnigEncoding enc, OnigCaseFoldType fold_flag)
{
OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
int i, n;
add_char_opt_map(map, p[0], enc);
fold_flag = DISABLE_CASE_FOLD_MULTI_CHAR(fold_flag);
n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, fold_flag, p, end, items);
if (n < 0) return n;
for (i = 0; i < n; i++) {
ONIGENC_CODE_TO_MBC(enc, items[i].code[0], buf);
add_char_opt_map(map, buf[0], enc);
}
return 0;
}
static void
select_opt_map(OptMap* now, OptMap* alt)
{
static int z = 1<<15; /* 32768: something big value */
int vn, va;
if (alt->value == 0) return ;
if (now->value == 0) {
copy_opt_map(now, alt);
return ;
}
vn = z / now->value;
va = z / alt->value;
if (comp_distance_value(&now->mmd, &alt->mmd, vn, va) > 0)
copy_opt_map(now, alt);
}
static int
comp_opt_exact_or_map(OptStr* e, OptMap* m)
{
#define COMP_EM_BASE 20
int ae, am;
int case_value;
if (m->value <= 0) return -1;
if (e->case_fold != 0) {
if (e->good_case_fold != 0)
case_value = 2;
else
case_value = 1;
}
else
case_value = 3;
ae = COMP_EM_BASE * e->len * case_value;
am = COMP_EM_BASE * 5 * 2 / m->value;
return comp_distance_value(&e->mmd, &m->mmd, ae, am);
}
static void
alt_merge_opt_map(OnigEncoding enc, OptMap* to, OptMap* add)
{
int i, val;
/* if (! is_equal_mml(&to->mmd, &add->mmd)) return ; */
if (to->value == 0) return ;
if (add->value == 0 || to->mmd.max < add->mmd.min) {
clear_opt_map(to);
return ;
}
alt_merge_mml(&to->mmd, &add->mmd);
val = 0;
for (i = 0; i < CHAR_MAP_SIZE; i++) {
if (add->map[i])
to->map[i] = 1;
if (to->map[i])
val += map_position_value(enc, i);
}
to->value = val;
alt_merge_opt_anc_info(&to->anc, &add->anc);
}
static void
set_bound_node_opt_info(OptNode* opt, MinMax* plen)
{
copy_mml(&(opt->sb.mmd), plen);
copy_mml(&(opt->spr.mmd), plen);
copy_mml(&(opt->map.mmd), plen);
}
static void
clear_node_opt_info(OptNode* opt)
{
clear_mml(&opt->len);
clear_opt_anc_info(&opt->anc);
clear_opt_exact(&opt->sb);
clear_opt_exact(&opt->sm);
clear_opt_exact(&opt->spr);
clear_opt_map(&opt->map);
}
static void
copy_node_opt_info(OptNode* to, OptNode* from)
{
*to = *from;
}
static void
concat_left_node_opt_info(OnigEncoding enc, OptNode* to, OptNode* add)
{
int sb_reach, sm_reach;
OptAnc tanc;
concat_opt_anc_info(&tanc, &to->anc, &add->anc, to->len.max, add->len.max);
copy_opt_anc_info(&to->anc, &tanc);
if (add->sb.len > 0 && to->len.max == 0) {
concat_opt_anc_info(&tanc, &to->anc, &add->sb.anc, to->len.max, add->len.max);
copy_opt_anc_info(&add->sb.anc, &tanc);
}
if (add->map.value > 0 && to->len.max == 0) {
if (add->map.mmd.max == 0)
add->map.anc.left |= to->anc.left;
}
sb_reach = to->sb.reach_end;
sm_reach = to->sm.reach_end;
if (add->len.max != 0)
to->sb.reach_end = to->sm.reach_end = 0;
if (add->sb.len > 0) {
if (sb_reach) {
concat_opt_exact(&to->sb, &add->sb, enc);
clear_opt_exact(&add->sb);
}
else if (sm_reach) {
concat_opt_exact(&to->sm, &add->sb, enc);
clear_opt_exact(&add->sb);
}
}
select_opt_exact(enc, &to->sm, &add->sb);
select_opt_exact(enc, &to->sm, &add->sm);
if (to->spr.len > 0) {
if (add->len.max > 0) {
if (to->spr.len > (int )add->len.max)
to->spr.len = add->len.max;
if (to->spr.mmd.max == 0)
select_opt_exact(enc, &to->sb, &to->spr);
else
select_opt_exact(enc, &to->sm, &to->spr);
}
}
else if (add->spr.len > 0) {
copy_opt_exact(&to->spr, &add->spr);
}
select_opt_map(&to->map, &add->map);
add_mml(&to->len, &add->len);
}
static void
alt_merge_node_opt_info(OptNode* to, OptNode* add, OptEnv* env)
{
alt_merge_opt_anc_info(&to->anc, &add->anc);
alt_merge_opt_exact(&to->sb, &add->sb, env);
alt_merge_opt_exact(&to->sm, &add->sm, env);
alt_merge_opt_exact(&to->spr, &add->spr, env);
alt_merge_opt_map(env->enc, &to->map, &add->map);
alt_merge_mml(&to->len, &add->len);
}
#define MAX_NODE_OPT_INFO_REF_COUNT 5
static int
optimize_nodes(Node* node, OptNode* opt, OptEnv* env)
{
int i;
int r;
OptNode xo;
OnigEncoding enc;
r = 0;
enc = env->enc;
clear_node_opt_info(opt);
set_bound_node_opt_info(opt, &env->mmd);
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
OptEnv nenv;
Node* nd = node;
copy_opt_env(&nenv, env);
do {
r = optimize_nodes(NODE_CAR(nd), &xo, &nenv);
if (r == 0) {
add_mml(&nenv.mmd, &xo.len);
concat_left_node_opt_info(enc, opt, &xo);
}
} while (r == 0 && IS_NOT_NULL(nd = NODE_CDR(nd)));
}
break;
case NODE_ALT:
{
Node* nd = node;
do {
r = optimize_nodes(NODE_CAR(nd), &xo, env);
if (r == 0) {
if (nd == node) copy_node_opt_info(opt, &xo);
else alt_merge_node_opt_info(opt, &xo, env);
}
} while ((r == 0) && IS_NOT_NULL(nd = NODE_CDR(nd)));
}
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
int slen = (int )(sn->end - sn->s);
/* int is_raw = NODE_STRING_IS_RAW(node); */
if (! NODE_STRING_IS_AMBIG(node)) {
concat_opt_exact_str(&opt->sb, sn->s, sn->end, enc);
if (slen > 0) {
add_char_opt_map(&opt->map, *(sn->s), enc);
}
set_mml(&opt->len, slen, slen);
}
else {
int max;
if (NODE_STRING_IS_DONT_GET_OPT_INFO(node)) {
int n = onigenc_strlen(enc, sn->s, sn->end);
max = ONIGENC_MBC_MAXLEN_DIST(enc) * n;
}
else {
concat_opt_exact_str(&opt->sb, sn->s, sn->end, enc);
opt->sb.case_fold = 1;
if (NODE_STRING_IS_GOOD_AMBIG(node))
opt->sb.good_case_fold = 1;
if (slen > 0) {
r = add_char_amb_opt_map(&opt->map, sn->s, sn->end,
enc, env->case_fold_flag);
if (r != 0) break;
}
max = slen;
}
set_mml(&opt->len, slen, max);
}
}
break;
case NODE_CCLASS:
{
int z;
CClassNode* cc = CCLASS_(node);
/* no need to check ignore case. (set in setup_tree()) */
if (IS_NOT_NULL(cc->mbuf) || IS_NCCLASS_NOT(cc)) {
OnigLen min = ONIGENC_MBC_MINLEN(enc);
OnigLen max = ONIGENC_MBC_MAXLEN_DIST(enc);
set_mml(&opt->len, min, max);
}
else {
for (i = 0; i < SINGLE_BYTE_SIZE; i++) {
z = BITSET_AT(cc->bs, i);
if ((z && ! IS_NCCLASS_NOT(cc)) || (! z && IS_NCCLASS_NOT(cc))) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
set_mml(&opt->len, 1, 1);
}
}
break;
case NODE_CTYPE:
{
int min, max;
int range;
max = ONIGENC_MBC_MAXLEN_DIST(enc);
if (max == 1) {
min = 1;
switch (CTYPE_(node)->ctype) {
case CTYPE_ANYCHAR:
break;
case ONIGENC_CTYPE_WORD:
range = CTYPE_(node)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;
if (CTYPE_(node)->not != 0) {
for (i = 0; i < range; i++) {
if (! ONIGENC_IS_CODE_WORD(enc, i)) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
for (i = range; i < SINGLE_BYTE_SIZE; i++) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
else {
for (i = 0; i < range; i++) {
if (ONIGENC_IS_CODE_WORD(enc, i)) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
}
break;
}
}
else {
min = ONIGENC_MBC_MINLEN(enc);
}
set_mml(&opt->len, min, max);
}
break;
case NODE_ANCHOR:
switch (ANCHOR_(node)->type) {
case ANCR_BEGIN_BUF:
case ANCR_BEGIN_POSITION:
case ANCR_BEGIN_LINE:
case ANCR_END_BUF:
case ANCR_SEMI_END_BUF:
case ANCR_END_LINE:
case ANCR_PREC_READ_NOT:
case ANCR_LOOK_BEHIND:
add_opt_anc_info(&opt->anc, ANCHOR_(node)->type);
break;
case ANCR_PREC_READ:
{
r = optimize_nodes(NODE_BODY(node), &xo, env);
if (r == 0) {
if (xo.sb.len > 0)
copy_opt_exact(&opt->spr, &xo.sb);
else if (xo.sm.len > 0)
copy_opt_exact(&opt->spr, &xo.sm);
opt->spr.reach_end = 0;
if (xo.map.value > 0)
copy_opt_map(&opt->map, &xo.map);
}
}
break;
case ANCR_LOOK_BEHIND_NOT:
break;
}
break;
case NODE_BACKREF:
if (! NODE_IS_CHECKER(node)) {
int* backs;
OnigLen min, max, tmin, tmax;
MemEnv* mem_env = SCANENV_MEMENV(env->scan_env);
BackRefNode* br = BACKREF_(node);
if (NODE_IS_RECURSION(node)) {
set_mml(&opt->len, 0, INFINITE_LEN);
break;
}
backs = BACKREFS_P(br);
min = tree_min_len(mem_env[backs[0]].node, env->scan_env);
max = tree_max_len(mem_env[backs[0]].node, env->scan_env);
for (i = 1; i < br->back_num; i++) {
tmin = tree_min_len(mem_env[backs[i]].node, env->scan_env);
tmax = tree_max_len(mem_env[backs[i]].node, env->scan_env);
if (min > tmin) min = tmin;
if (max < tmax) max = tmax;
}
set_mml(&opt->len, min, max);
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (NODE_IS_RECURSION(node))
set_mml(&opt->len, 0, INFINITE_LEN);
else {
OnigOptionType save = env->options;
env->options = BAG_(NODE_BODY(node))->o.options;
r = optimize_nodes(NODE_BODY(node), opt, env);
env->options = save;
}
break;
#endif
case NODE_QUANT:
{
OnigLen min, max;
QuantNode* qn = QUANT_(node);
r = optimize_nodes(NODE_BODY(node), &xo, env);
if (r != 0) break;
if (qn->lower > 0) {
copy_node_opt_info(opt, &xo);
if (xo.sb.len > 0) {
if (xo.sb.reach_end) {
for (i = 2; i <= qn->lower && ! is_full_opt_exact(&opt->sb); i++) {
int rc = concat_opt_exact(&opt->sb, &xo.sb, enc);
if (rc > 0) break;
}
if (i < qn->lower) opt->sb.reach_end = 0;
}
}
if (qn->lower != qn->upper) {
opt->sb.reach_end = 0;
opt->sm.reach_end = 0;
}
if (qn->lower > 1)
opt->sm.reach_end = 0;
}
if (IS_REPEAT_INFINITE(qn->upper)) {
if (env->mmd.max == 0 &&
NODE_IS_ANYCHAR(NODE_BODY(node)) && qn->greedy != 0) {
if (IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), env)))
add_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_ML);
else
add_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF);
}
max = (xo.len.max > 0 ? INFINITE_LEN : 0);
}
else {
max = distance_multiply(xo.len.max, qn->upper);
}
min = distance_multiply(xo.len.min, qn->lower);
set_mml(&opt->len, min, max);
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_OPTION:
{
OnigOptionType save = env->options;
env->options = en->o.options;
r = optimize_nodes(NODE_BODY(node), opt, env);
env->options = save;
}
break;
case BAG_MEMORY:
#ifdef USE_CALL
en->opt_count++;
if (en->opt_count > MAX_NODE_OPT_INFO_REF_COUNT) {
OnigLen min, max;
min = 0;
max = INFINITE_LEN;
if (NODE_IS_MIN_FIXED(node)) min = en->min_len;
if (NODE_IS_MAX_FIXED(node)) max = en->max_len;
set_mml(&opt->len, min, max);
}
else
#endif
{
r = optimize_nodes(NODE_BODY(node), opt, env);
if (is_set_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_MASK)) {
if (MEM_STATUS_AT0(env->scan_env->backrefed_mem, en->m.regnum))
remove_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_MASK);
}
}
break;
case BAG_STOP_BACKTRACK:
r = optimize_nodes(NODE_BODY(node), opt, env);
break;
case BAG_IF_ELSE:
{
OptEnv nenv;
copy_opt_env(&nenv, env);
r = optimize_nodes(NODE_BAG_BODY(en), &xo, &nenv);
if (r == 0) {
add_mml(&nenv.mmd, &xo.len);
concat_left_node_opt_info(enc, opt, &xo);
if (IS_NOT_NULL(en->te.Then)) {
r = optimize_nodes(en->te.Then, &xo, &nenv);
if (r == 0) {
concat_left_node_opt_info(enc, opt, &xo);
}
}
if (IS_NOT_NULL(en->te.Else)) {
r = optimize_nodes(en->te.Else, &xo, env);
if (r == 0)
alt_merge_node_opt_info(opt, &xo, env);
}
}
}
break;
}
}
break;
case NODE_GIMMICK:
break;
default:
#ifdef ONIG_DEBUG
fprintf(stderr, "optimize_nodes: undefined node type %d\n", NODE_TYPE(node));
#endif
r = ONIGERR_TYPE_BUG;
break;
}
return r;
}
static int
set_optimize_exact(regex_t* reg, OptStr* e)
{
int r;
if (e->len == 0) return 0;
reg->exact = (UChar* )xmalloc(e->len);
CHECK_NULL_RETURN_MEMERR(reg->exact);
xmemcpy(reg->exact, e->s, e->len);
reg->exact_end = reg->exact + e->len;
if (e->case_fold) {
reg->optimize = OPTIMIZE_STR_CASE_FOLD;
if (e->good_case_fold != 0) {
if (e->len >= 2) {
r = set_sunday_quick_search_or_bmh_skip_table(reg, 1,
reg->exact, reg->exact_end,
reg->map, &(reg->map_offset));
if (r != 0) return r;
reg->optimize = OPTIMIZE_STR_CASE_FOLD_FAST;
}
}
}
else {
int allow_reverse;
allow_reverse =
ONIGENC_IS_ALLOWED_REVERSE_MATCH(reg->enc, reg->exact, reg->exact_end);
if (e->len >= 2 || (e->len >= 1 && allow_reverse)) {
r = set_sunday_quick_search_or_bmh_skip_table(reg, 0,
reg->exact, reg->exact_end,
reg->map, &(reg->map_offset));
if (r != 0) return r;
reg->optimize = (allow_reverse != 0
? OPTIMIZE_STR_FAST
: OPTIMIZE_STR_FAST_STEP_FORWARD);
}
else {
reg->optimize = OPTIMIZE_STR;
}
}
reg->dmin = e->mmd.min;
reg->dmax = e->mmd.max;
if (reg->dmin != INFINITE_LEN) {
reg->threshold_len = reg->dmin + (int )(reg->exact_end - reg->exact);
}
return 0;
}
static void
set_optimize_map(regex_t* reg, OptMap* m)
{
int i;
for (i = 0; i < CHAR_MAP_SIZE; i++)
reg->map[i] = m->map[i];
reg->optimize = OPTIMIZE_MAP;
reg->dmin = m->mmd.min;
reg->dmax = m->mmd.max;
if (reg->dmin != INFINITE_LEN) {
reg->threshold_len = reg->dmin + 1;
}
}
static void
set_sub_anchor(regex_t* reg, OptAnc* anc)
{
reg->sub_anchor |= anc->left & ANCR_BEGIN_LINE;
reg->sub_anchor |= anc->right & ANCR_END_LINE;
}
#if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH)
static void print_optimize_info(FILE* f, regex_t* reg);
#endif
static int
set_optimize_info_from_tree(Node* node, regex_t* reg, ScanEnv* scan_env)
{
int r;
OptNode opt;
OptEnv env;
env.enc = reg->enc;
env.options = reg->options;
env.case_fold_flag = reg->case_fold_flag;
env.scan_env = scan_env;
clear_mml(&env.mmd);
r = optimize_nodes(node, &opt, &env);
if (r != 0) return r;
reg->anchor = opt.anc.left & (ANCR_BEGIN_BUF |
ANCR_BEGIN_POSITION | ANCR_ANYCHAR_INF | ANCR_ANYCHAR_INF_ML |
ANCR_LOOK_BEHIND);
if ((opt.anc.left & (ANCR_LOOK_BEHIND | ANCR_PREC_READ_NOT)) != 0)
reg->anchor &= ~ANCR_ANYCHAR_INF_ML;
reg->anchor |= opt.anc.right & (ANCR_END_BUF | ANCR_SEMI_END_BUF |
ANCR_PREC_READ_NOT);
if (reg->anchor & (ANCR_END_BUF | ANCR_SEMI_END_BUF)) {
reg->anchor_dmin = opt.len.min;
reg->anchor_dmax = opt.len.max;
}
if (opt.sb.len > 0 || opt.sm.len > 0) {
select_opt_exact(reg->enc, &opt.sb, &opt.sm);
if (opt.map.value > 0 && comp_opt_exact_or_map(&opt.sb, &opt.map) > 0) {
goto set_map;
}
else {
r = set_optimize_exact(reg, &opt.sb);
set_sub_anchor(reg, &opt.sb.anc);
}
}
else if (opt.map.value > 0) {
set_map:
set_optimize_map(reg, &opt.map);
set_sub_anchor(reg, &opt.map.anc);
}
else {
reg->sub_anchor |= opt.anc.left & ANCR_BEGIN_LINE;
if (opt.len.max == 0)
reg->sub_anchor |= opt.anc.right & ANCR_END_LINE;
}
#if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH)
print_optimize_info(stderr, reg);
#endif
return r;
}
static void
clear_optimize_info(regex_t* reg)
{
reg->optimize = OPTIMIZE_NONE;
reg->anchor = 0;
reg->anchor_dmin = 0;
reg->anchor_dmax = 0;
reg->sub_anchor = 0;
reg->exact_end = (UChar* )NULL;
reg->map_offset = 0;
reg->threshold_len = 0;
if (IS_NOT_NULL(reg->exact)) {
xfree(reg->exact);
reg->exact = (UChar* )NULL;
}
}
#ifdef ONIG_DEBUG
static void print_enc_string(FILE* fp, OnigEncoding enc,
const UChar *s, const UChar *end)
{
fprintf(fp, "\nPATTERN: /");
if (ONIGENC_MBC_MINLEN(enc) > 1) {
const UChar *p;
OnigCodePoint code;
p = s;
while (p < end) {
code = ONIGENC_MBC_TO_CODE(enc, p, end);
if (code >= 0x80) {
fprintf(fp, " 0x%04x ", (int )code);
}
else {
fputc((int )code, fp);
}
p += enclen(enc, p);
}
}
else {
while (s < end) {
fputc((int )*s, fp);
s++;
}
}
fprintf(fp, "/\n");
}
#endif /* ONIG_DEBUG */
#if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH)
static void
print_distance_range(FILE* f, OnigLen a, OnigLen b)
{
if (a == INFINITE_LEN)
fputs("inf", f);
else
fprintf(f, "(%u)", a);
fputs("-", f);
if (b == INFINITE_LEN)
fputs("inf", f);
else
fprintf(f, "(%u)", b);
}
static void
print_anchor(FILE* f, int anchor)
{
int q = 0;
fprintf(f, "[");
if (anchor & ANCR_BEGIN_BUF) {
fprintf(f, "begin-buf");
q = 1;
}
if (anchor & ANCR_BEGIN_LINE) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "begin-line");
}
if (anchor & ANCR_BEGIN_POSITION) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "begin-pos");
}
if (anchor & ANCR_END_BUF) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "end-buf");
}
if (anchor & ANCR_SEMI_END_BUF) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "semi-end-buf");
}
if (anchor & ANCR_END_LINE) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "end-line");
}
if (anchor & ANCR_ANYCHAR_INF) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "anychar-inf");
}
if (anchor & ANCR_ANYCHAR_INF_ML) {
if (q) fprintf(f, ", ");
fprintf(f, "anychar-inf-ml");
}
fprintf(f, "]");
}
static void
print_optimize_info(FILE* f, regex_t* reg)
{
static const char* on[] = { "NONE", "STR",
"STR_FAST", "STR_FAST_STEP_FORWARD",
"STR_CASE_FOLD_FAST", "STR_CASE_FOLD", "MAP" };
fprintf(f, "optimize: %s\n", on[reg->optimize]);
fprintf(f, " anchor: "); print_anchor(f, reg->anchor);
if ((reg->anchor & ANCR_END_BUF_MASK) != 0)
print_distance_range(f, reg->anchor_dmin, reg->anchor_dmax);
fprintf(f, "\n");
if (reg->optimize) {
fprintf(f, " sub anchor: "); print_anchor(f, reg->sub_anchor);
fprintf(f, "\n");
}
fprintf(f, "\n");
if (reg->exact) {
UChar *p;
fprintf(f, "exact: [");
for (p = reg->exact; p < reg->exact_end; p++) {
fputc(*p, f);
}
fprintf(f, "]: length: %ld\n", (reg->exact_end - reg->exact));
}
else if (reg->optimize & OPTIMIZE_MAP) {
int c, i, n = 0;
for (i = 0; i < CHAR_MAP_SIZE; i++)
if (reg->map[i]) n++;
fprintf(f, "map: n=%d\n", n);
if (n > 0) {
c = 0;
fputc('[', f);
for (i = 0; i < CHAR_MAP_SIZE; i++) {
if (reg->map[i] != 0) {
if (c > 0) fputs(", ", f);
c++;
if (ONIGENC_MBC_MAXLEN(reg->enc) == 1 &&
ONIGENC_IS_CODE_PRINT(reg->enc, (OnigCodePoint )i))
fputc(i, f);
else
fprintf(f, "%d", i);
}
}
fprintf(f, "]\n");
}
}
}
#endif
extern RegexExt*
onig_get_regex_ext(regex_t* reg)
{
if (IS_NULL(reg->extp)) {
RegexExt* ext = (RegexExt* )xmalloc(sizeof(*ext));
if (IS_NULL(ext)) return 0;
ext->pattern = 0;
ext->pattern_end = 0;
#ifdef USE_CALLOUT
ext->tag_table = 0;
ext->callout_num = 0;
ext->callout_list_alloc = 0;
ext->callout_list = 0;
#endif
reg->extp = ext;
}
return reg->extp;
}
static void
free_regex_ext(RegexExt* ext)
{
if (IS_NOT_NULL(ext)) {
if (IS_NOT_NULL(ext->pattern))
xfree((void* )ext->pattern);
#ifdef USE_CALLOUT
if (IS_NOT_NULL(ext->tag_table))
onig_callout_tag_table_free(ext->tag_table);
if (IS_NOT_NULL(ext->callout_list))
onig_free_reg_callout_list(ext->callout_num, ext->callout_list);
#endif
xfree(ext);
}
}
extern int
onig_ext_set_pattern(regex_t* reg, const UChar* pattern, const UChar* pattern_end)
{
RegexExt* ext;
UChar* s;
ext = onig_get_regex_ext(reg);
CHECK_NULL_RETURN_MEMERR(ext);
s = onigenc_strdup(reg->enc, pattern, pattern_end);
CHECK_NULL_RETURN_MEMERR(s);
ext->pattern = s;
ext->pattern_end = s + (pattern_end - pattern);
return ONIG_NORMAL;
}
extern void
onig_free_body(regex_t* reg)
{
if (IS_NOT_NULL(reg)) {
ops_free(reg);
if (IS_NOT_NULL(reg->string_pool)) {
xfree(reg->string_pool);
reg->string_pool_end = reg->string_pool = 0;
}
if (IS_NOT_NULL(reg->exact)) xfree(reg->exact);
if (IS_NOT_NULL(reg->repeat_range)) xfree(reg->repeat_range);
if (IS_NOT_NULL(reg->extp)) {
free_regex_ext(reg->extp);
reg->extp = 0;
}
onig_names_free(reg);
}
}
extern void
onig_free(regex_t* reg)
{
if (IS_NOT_NULL(reg)) {
onig_free_body(reg);
xfree(reg);
}
}
#ifdef ONIG_DEBUG_PARSE
static void print_tree P_((FILE* f, Node* node));
#endif
extern int onig_init_for_match_at(regex_t* reg);
extern int
onig_compile(regex_t* reg, const UChar* pattern, const UChar* pattern_end,
OnigErrorInfo* einfo)
{
int r;
Node* root;
ScanEnv scan_env;
#ifdef USE_CALL
UnsetAddrList uslist;
#endif
root = 0;
if (IS_NOT_NULL(einfo)) {
einfo->enc = reg->enc;
einfo->par = (UChar* )NULL;
}
#ifdef ONIG_DEBUG
print_enc_string(stderr, reg->enc, pattern, pattern_end);
#endif
if (reg->ops_alloc == 0) {
r = ops_init(reg, OPS_INIT_SIZE);
if (r != 0) goto end;
}
else
reg->ops_used = 0;
reg->string_pool = 0;
reg->string_pool_end = 0;
reg->num_mem = 0;
reg->num_repeat = 0;
reg->num_null_check = 0;
reg->repeat_range_alloc = 0;
reg->repeat_range = (OnigRepeatRange* )NULL;
r = onig_parse_tree(&root, pattern, pattern_end, reg, &scan_env);
if (r != 0) goto err;
/* mixed use named group and no-named group */
if (scan_env.num_named > 0 &&
IS_SYNTAX_BV(scan_env.syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&
! ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) {
if (scan_env.num_named != scan_env.num_mem)
r = disable_noname_group_capture(&root, reg, &scan_env);
else
r = numbered_ref_check(root);
if (r != 0) goto err;
}
r = check_backrefs(root, &scan_env);
if (r != 0) goto err;
#ifdef USE_CALL
if (scan_env.num_call > 0) {
r = unset_addr_list_init(&uslist, scan_env.num_call);
if (r != 0) goto err;
scan_env.unset_addr_list = &uslist;
r = setup_call(root, &scan_env, 0);
if (r != 0) goto err_unset;
r = setup_call2(root);
if (r != 0) goto err_unset;
r = recursive_call_check_trav(root, &scan_env, 0);
if (r < 0) goto err_unset;
r = infinite_recursive_call_check_trav(root, &scan_env);
if (r != 0) goto err_unset;
setup_called_state(root, 0);
}
reg->num_call = scan_env.num_call;
#endif
r = setup_tree(root, reg, 0, &scan_env);
if (r != 0) goto err_unset;
#ifdef ONIG_DEBUG_PARSE
print_tree(stderr, root);
#endif
reg->capture_history = scan_env.capture_history;
reg->bt_mem_start = scan_env.bt_mem_start;
reg->bt_mem_start |= reg->capture_history;
if (IS_FIND_CONDITION(reg->options))
MEM_STATUS_ON_ALL(reg->bt_mem_end);
else {
reg->bt_mem_end = scan_env.bt_mem_end;
reg->bt_mem_end |= reg->capture_history;
}
reg->bt_mem_start |= reg->bt_mem_end;
clear_optimize_info(reg);
#ifndef ONIG_DONT_OPTIMIZE
r = set_optimize_info_from_tree(root, reg, &scan_env);
if (r != 0) goto err_unset;
#endif
if (IS_NOT_NULL(scan_env.mem_env_dynamic)) {
xfree(scan_env.mem_env_dynamic);
scan_env.mem_env_dynamic = (MemEnv* )NULL;
}
r = compile_tree(root, reg, &scan_env);
if (r == 0) {
if (scan_env.keep_num > 0) {
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) goto err;
COP(reg)->update_var.type = UPDATE_VAR_KEEP_FROM_STACK_LAST;
COP(reg)->update_var.id = 0; /* not used */
}
r = add_op(reg, OP_END);
if (r != 0) goto err;
#ifdef USE_CALL
if (scan_env.num_call > 0) {
r = fix_unset_addr_list(&uslist, reg);
unset_addr_list_end(&uslist);
if (r != 0) goto err;
}
#endif
if ((reg->num_repeat != 0) || (reg->bt_mem_end != 0)
#ifdef USE_CALLOUT
|| (IS_NOT_NULL(reg->extp) && reg->extp->callout_num != 0)
#endif
)
reg->stack_pop_level = STACK_POP_LEVEL_ALL;
else {
if (reg->bt_mem_start != 0)
reg->stack_pop_level = STACK_POP_LEVEL_MEM_START;
else
reg->stack_pop_level = STACK_POP_LEVEL_FREE;
}
r = ops_make_string_pool(reg);
if (r != 0) goto err;
}
#ifdef USE_CALL
else if (scan_env.num_call > 0) {
unset_addr_list_end(&uslist);
}
#endif
onig_node_free(root);
#ifdef ONIG_DEBUG_COMPILE
onig_print_names(stderr, reg);
onig_print_compiled_byte_code_list(stderr, reg);
#endif
#ifdef USE_DIRECT_THREADED_CODE
/* opcode -> opaddr */
onig_init_for_match_at(reg);
#endif
end:
return r;
err_unset:
#ifdef USE_CALL
if (scan_env.num_call > 0) {
unset_addr_list_end(&uslist);
}
#endif
err:
if (IS_NOT_NULL(scan_env.error)) {
if (IS_NOT_NULL(einfo)) {
einfo->par = scan_env.error;
einfo->par_end = scan_env.error_end;
}
}
onig_node_free(root);
if (IS_NOT_NULL(scan_env.mem_env_dynamic))
xfree(scan_env.mem_env_dynamic);
return r;
}
static int onig_inited = 0;
extern int
onig_reg_init(regex_t* reg, OnigOptionType option, OnigCaseFoldType case_fold_flag,
OnigEncoding enc, OnigSyntaxType* syntax)
{
int r;
xmemset(reg, 0, sizeof(*reg));
if (onig_inited == 0) {
#if 0
return ONIGERR_LIBRARY_IS_NOT_INITIALIZED;
#else
r = onig_initialize(&enc, 1);
if (r != 0)
return ONIGERR_FAIL_TO_INITIALIZE;
onig_warning("You didn't call onig_initialize() explicitly");
#endif
}
if (IS_NULL(reg))
return ONIGERR_INVALID_ARGUMENT;
if (ONIGENC_IS_UNDEF(enc))
return ONIGERR_DEFAULT_ENCODING_IS_NOT_SETTED;
if ((option & (ONIG_OPTION_DONT_CAPTURE_GROUP|ONIG_OPTION_CAPTURE_GROUP))
== (ONIG_OPTION_DONT_CAPTURE_GROUP|ONIG_OPTION_CAPTURE_GROUP)) {
return ONIGERR_INVALID_COMBINATION_OF_OPTIONS;
}
if ((option & ONIG_OPTION_NEGATE_SINGLELINE) != 0) {
option |= syntax->options;
option &= ~ONIG_OPTION_SINGLELINE;
}
else
option |= syntax->options;
(reg)->enc = enc;
(reg)->options = option;
(reg)->syntax = syntax;
(reg)->optimize = 0;
(reg)->exact = (UChar* )NULL;
(reg)->extp = (RegexExt* )NULL;
(reg)->ops = (Operation* )NULL;
(reg)->ops_curr = (Operation* )NULL;
(reg)->ops_used = 0;
(reg)->ops_alloc = 0;
(reg)->name_table = (void* )NULL;
(reg)->case_fold_flag = case_fold_flag;
return 0;
}
extern int
onig_new_without_alloc(regex_t* reg,
const UChar* pattern, const UChar* pattern_end,
OnigOptionType option, OnigEncoding enc,
OnigSyntaxType* syntax, OnigErrorInfo* einfo)
{
int r;
r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
if (r != 0) return r;
r = onig_compile(reg, pattern, pattern_end, einfo);
return r;
}
extern int
onig_new(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
OnigOptionType option, OnigEncoding enc, OnigSyntaxType* syntax,
OnigErrorInfo* einfo)
{
int r;
*reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(*reg)) return ONIGERR_MEMORY;
r = onig_reg_init(*reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
if (r != 0) goto err;
r = onig_compile(*reg, pattern, pattern_end, einfo);
if (r != 0) {
err:
onig_free(*reg);
*reg = NULL;
}
return r;
}
extern int
onig_initialize(OnigEncoding encodings[], int n)
{
int i;
int r;
if (onig_inited != 0)
return 0;
onigenc_init();
onig_inited = 1;
for (i = 0; i < n; i++) {
OnigEncoding enc = encodings[i];
r = onig_initialize_encoding(enc);
if (r != 0)
return r;
}
return ONIG_NORMAL;
}
typedef struct EndCallListItem {
struct EndCallListItem* next;
void (*func)(void);
} EndCallListItemType;
static EndCallListItemType* EndCallTop;
extern void onig_add_end_call(void (*func)(void))
{
EndCallListItemType* item;
item = (EndCallListItemType* )xmalloc(sizeof(*item));
if (item == 0) return ;
item->next = EndCallTop;
item->func = func;
EndCallTop = item;
}
static void
exec_end_call_list(void)
{
EndCallListItemType* prev;
void (*func)(void);
while (EndCallTop != 0) {
func = EndCallTop->func;
(*func)();
prev = EndCallTop;
EndCallTop = EndCallTop->next;
xfree(prev);
}
}
extern int
onig_end(void)
{
exec_end_call_list();
#ifdef USE_CALLOUT
onig_global_callout_names_free();
#endif
onigenc_end();
onig_inited = 0;
return 0;
}
extern int
onig_is_in_code_range(const UChar* p, OnigCodePoint code)
{
OnigCodePoint n, *data;
OnigCodePoint low, high, x;
GET_CODE_POINT(n, p);
data = (OnigCodePoint* )p;
data++;
for (low = 0, high = n; low < high; ) {
x = (low + high) >> 1;
if (code > data[x * 2 + 1])
low = x + 1;
else
high = x;
}
return ((low < n && code >= data[low * 2]) ? 1 : 0);
}
extern int
onig_is_code_in_cc_len(int elen, OnigCodePoint code, /* CClassNode* */ void* cc_arg)
{
int found;
CClassNode* cc = (CClassNode* )cc_arg;
if (elen > 1 || (code >= SINGLE_BYTE_SIZE)) {
if (IS_NULL(cc->mbuf)) {
found = 0;
}
else {
found = onig_is_in_code_range(cc->mbuf->p, code) != 0;
}
}
else {
found = BITSET_AT(cc->bs, code) != 0;
}
if (IS_NCCLASS_NOT(cc))
return !found;
else
return found;
}
extern int
onig_is_code_in_cc(OnigEncoding enc, OnigCodePoint code, CClassNode* cc)
{
int len;
if (ONIGENC_MBC_MINLEN(enc) > 1) {
len = 2;
}
else {
len = ONIGENC_CODE_TO_MBCLEN(enc, code);
}
return onig_is_code_in_cc_len(len, code, cc);
}
#ifdef ONIG_DEBUG_PARSE
static void
p_string(FILE* f, int len, UChar* s)
{
fputs(":", f);
while (len-- > 0) { fputc(*s++, f); }
}
static void
Indent(FILE* f, int indent)
{
int i;
for (i = 0; i < indent; i++) putc(' ', f);
}
static void
print_indent_tree(FILE* f, Node* node, int indent)
{
int i;
NodeType type;
UChar* p;
int add = 3;
Indent(f, indent);
if (IS_NULL(node)) {
fprintf(f, "ERROR: null node!!!\n");
exit (0);
}
type = NODE_TYPE(node);
switch (type) {
case NODE_LIST:
case NODE_ALT:
if (type == NODE_LIST)
fprintf(f, "<list:%p>\n", node);
else
fprintf(f, "<alt:%p>\n", node);
print_indent_tree(f, NODE_CAR(node), indent + add);
while (IS_NOT_NULL(node = NODE_CDR(node))) {
if (NODE_TYPE(node) != type) {
fprintf(f, "ERROR: list/alt right is not a cons. %d\n", NODE_TYPE(node));
exit(0);
}
print_indent_tree(f, NODE_CAR(node), indent + add);
}
break;
case NODE_STRING:
{
char* mode;
char* dont;
char* good;
if (NODE_STRING_IS_RAW(node))
mode = "-raw";
else if (NODE_STRING_IS_AMBIG(node))
mode = "-ambig";
else
mode = "";
if (NODE_STRING_IS_GOOD_AMBIG(node))
good = "-good";
else
good = "";
if (NODE_STRING_IS_DONT_GET_OPT_INFO(node))
dont = " (dont-opt)";
else
dont = "";
fprintf(f, "<string%s%s%s:%p>", mode, good, dont, node);
for (p = STR_(node)->s; p < STR_(node)->end; p++) {
if (*p >= 0x20 && *p < 0x7f)
fputc(*p, f);
else {
fprintf(f, " 0x%02x", *p);
}
}
}
break;
case NODE_CCLASS:
fprintf(f, "<cclass:%p>", node);
if (IS_NCCLASS_NOT(CCLASS_(node))) fputs(" not", f);
if (CCLASS_(node)->mbuf) {
BBuf* bbuf = CCLASS_(node)->mbuf;
for (i = 0; i < bbuf->used; i++) {
if (i > 0) fprintf(f, ",");
fprintf(f, "%0x", bbuf->p[i]);
}
}
break;
case NODE_CTYPE:
fprintf(f, "<ctype:%p> ", node);
switch (CTYPE_(node)->ctype) {
case CTYPE_ANYCHAR:
fprintf(f, "<anychar:%p>", node);
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(node)->not != 0)
fputs("not word", f);
else
fputs("word", f);
if (CTYPE_(node)->ascii_mode != 0)
fputs(" (ascii)", f);
break;
default:
fprintf(f, "ERROR: undefined ctype.\n");
exit(0);
}
break;
case NODE_ANCHOR:
fprintf(f, "<anchor:%p> ", node);
switch (ANCHOR_(node)->type) {
case ANCR_BEGIN_BUF: fputs("begin buf", f); break;
case ANCR_END_BUF: fputs("end buf", f); break;
case ANCR_BEGIN_LINE: fputs("begin line", f); break;
case ANCR_END_LINE: fputs("end line", f); break;
case ANCR_SEMI_END_BUF: fputs("semi end buf", f); break;
case ANCR_BEGIN_POSITION: fputs("begin position", f); break;
case ANCR_WORD_BOUNDARY: fputs("word boundary", f); break;
case ANCR_NO_WORD_BOUNDARY: fputs("not word boundary", f); break;
#ifdef USE_WORD_BEGIN_END
case ANCR_WORD_BEGIN: fputs("word begin", f); break;
case ANCR_WORD_END: fputs("word end", f); break;
#endif
case ANCR_TEXT_SEGMENT_BOUNDARY:
fputs("text-segment boundary", f); break;
case ANCR_NO_TEXT_SEGMENT_BOUNDARY:
fputs("no text-segment boundary", f); break;
case ANCR_PREC_READ:
fprintf(f, "prec read\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case ANCR_PREC_READ_NOT:
fprintf(f, "prec read not\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case ANCR_LOOK_BEHIND:
fprintf(f, "look behind\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case ANCR_LOOK_BEHIND_NOT:
fprintf(f, "look behind not\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
default:
fprintf(f, "ERROR: undefined anchor type.\n");
break;
}
break;
case NODE_BACKREF:
{
int* p;
BackRefNode* br = BACKREF_(node);
p = BACKREFS_P(br);
fprintf(f, "<backref%s:%p>", NODE_IS_CHECKER(node) ? "-checker" : "", node);
for (i = 0; i < br->back_num; i++) {
if (i > 0) fputs(", ", f);
fprintf(f, "%d", p[i]);
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
{
CallNode* cn = CALL_(node);
fprintf(f, "<call:%p>", node);
p_string(f, cn->name_end - cn->name, cn->name);
}
break;
#endif
case NODE_QUANT:
fprintf(f, "<quantifier:%p>{%d,%d}%s\n", node,
QUANT_(node)->lower, QUANT_(node)->upper,
(QUANT_(node)->greedy ? "" : "?"));
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case NODE_BAG:
fprintf(f, "<bag:%p> ", node);
switch (BAG_(node)->type) {
case BAG_OPTION:
fprintf(f, "option:%d", BAG_(node)->o.options);
break;
case BAG_MEMORY:
fprintf(f, "memory:%d", BAG_(node)->m.regnum);
break;
case BAG_STOP_BACKTRACK:
fprintf(f, "stop-bt");
break;
case BAG_IF_ELSE:
fprintf(f, "if-else");
break;
}
fprintf(f, "\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case NODE_GIMMICK:
fprintf(f, "<gimmick:%p> ", node);
switch (GIMMICK_(node)->type) {
case GIMMICK_FAIL:
fprintf(f, "fail");
break;
case GIMMICK_SAVE:
fprintf(f, "save:%d:%d", GIMMICK_(node)->detail_type, GIMMICK_(node)->id);
break;
case GIMMICK_UPDATE_VAR:
fprintf(f, "update_var:%d:%d", GIMMICK_(node)->detail_type, GIMMICK_(node)->id);
break;
#ifdef USE_CALLOUT
case GIMMICK_CALLOUT:
switch (GIMMICK_(node)->detail_type) {
case ONIG_CALLOUT_OF_CONTENTS:
fprintf(f, "callout:contents:%d", GIMMICK_(node)->num);
break;
case ONIG_CALLOUT_OF_NAME:
fprintf(f, "callout:name:%d:%d", GIMMICK_(node)->id, GIMMICK_(node)->num);
break;
}
#endif
}
break;
default:
fprintf(f, "print_indent_tree: undefined node type %d\n", NODE_TYPE(node));
break;
}
if (type != NODE_LIST && type != NODE_ALT && type != NODE_QUANT &&
type != NODE_BAG)
fprintf(f, "\n");
fflush(f);
}
static void
print_tree(FILE* f, Node* node)
{
print_indent_tree(f, node, 0);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_914_0 |
crossvul-cpp_data_bad_3404_0 | /*
* DNxHD/VC-3 parser
* Copyright (c) 2008 Baptiste Coudurier <baptiste.coudurier@free.fr>
*
* 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
* DNxHD/VC-3 parser
*/
#include "parser.h"
#include "dnxhddata.h"
typedef struct {
ParseContext pc;
int cur_byte;
int remaining;
int w, h;
} DNXHDParserContext;
static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
if (cid <= 0)
continue;
dctx->remaining = avpriv_dnxhd_get_frame_size(cid);
if (dctx->remaining <= 0) {
dctx->remaining = ff_dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (dctx->remaining <= 0)
return dctx->remaining;
}
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
static int dnxhd_parse(AVCodecParserContext *s,
AVCodecContext *avctx,
const uint8_t **poutbuf, int *poutbuf_size,
const uint8_t *buf, int buf_size)
{
DNXHDParserContext *dctx = s->priv_data;
ParseContext *pc = &dctx->pc;
int next;
if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
next = buf_size;
} else {
next = dnxhd_find_frame_end(dctx, buf, buf_size);
if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
*poutbuf = NULL;
*poutbuf_size = 0;
return buf_size;
}
}
*poutbuf = buf;
*poutbuf_size = buf_size;
return next;
}
AVCodecParser ff_dnxhd_parser = {
.codec_ids = { AV_CODEC_ID_DNXHD },
.priv_data_size = sizeof(DNXHDParserContext),
.parser_parse = dnxhd_parse,
.parser_close = ff_parse_close,
};
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_3404_0 |
crossvul-cpp_data_good_1324_2 | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle SELECT statements in SQLite.
*/
#include "sqliteInt.h"
/*
** Trace output macros
*/
#if SELECTTRACE_ENABLED
/***/ int sqlite3SelectTrace = 0;
# define SELECTTRACE(K,P,S,X) \
if(sqlite3SelectTrace&(K)) \
sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
sqlite3DebugPrintf X
#else
# define SELECTTRACE(K,P,S,X)
#endif
/*
** An instance of the following object is used to record information about
** how to process the DISTINCT keyword, to simplify passing that information
** into the selectInnerLoop() routine.
*/
typedef struct DistinctCtx DistinctCtx;
struct DistinctCtx {
u8 isTnct; /* True if the DISTINCT keyword is present */
u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
int tabTnct; /* Ephemeral table used for DISTINCT processing */
int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
};
/*
** An instance of the following object is used to record information about
** the ORDER BY (or GROUP BY) clause of query is being coded.
**
** The aDefer[] array is used by the sorter-references optimization. For
** example, assuming there is no index that can be used for the ORDER BY,
** for the query:
**
** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
**
** it may be more efficient to add just the "a" values to the sorter, and
** retrieve the associated "bigblob" values directly from table t1 as the
** 10 smallest "a" values are extracted from the sorter.
**
** When the sorter-reference optimization is used, there is one entry in the
** aDefer[] array for each database table that may be read as values are
** extracted from the sorter.
*/
typedef struct SortCtx SortCtx;
struct SortCtx {
ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
int nOBSat; /* Number of ORDER BY terms satisfied by indices */
int iECursor; /* Cursor number for the sorter */
int regReturn; /* Register holding block-output return address */
int labelBkOut; /* Start label for the block-output subroutine */
int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
int labelDone; /* Jump here when done, ex: LIMIT reached */
int labelOBLopt; /* Jump here when sorter is full */
u8 sortFlags; /* Zero or more SORTFLAG_* bits */
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
u8 nDefer; /* Number of valid entries in aDefer[] */
struct DeferredCsr {
Table *pTab; /* Table definition */
int iCsr; /* Cursor number for table */
int nKey; /* Number of PK columns for table pTab (>=1) */
} aDefer[4];
#endif
struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
};
#define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
/*
** Delete all the content of a Select structure. Deallocate the structure
** itself only if bFree is true.
*/
static void clearSelect(sqlite3 *db, Select *p, int bFree){
while( p ){
Select *pPrior = p->pPrior;
sqlite3ExprListDelete(db, p->pEList);
sqlite3SrcListDelete(db, p->pSrc);
sqlite3ExprDelete(db, p->pWhere);
sqlite3ExprListDelete(db, p->pGroupBy);
sqlite3ExprDelete(db, p->pHaving);
sqlite3ExprListDelete(db, p->pOrderBy);
sqlite3ExprDelete(db, p->pLimit);
#ifndef SQLITE_OMIT_WINDOWFUNC
if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
sqlite3WindowListDelete(db, p->pWinDefn);
}
assert( p->pWin==0 );
#endif
if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
if( bFree ) sqlite3DbFreeNN(db, p);
p = pPrior;
bFree = 1;
}
}
/*
** Initialize a SelectDest structure.
*/
void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
pDest->eDest = (u8)eDest;
pDest->iSDParm = iParm;
pDest->zAffSdst = 0;
pDest->iSdst = 0;
pDest->nSdst = 0;
}
/*
** Allocate a new Select structure and return a pointer to that
** structure.
*/
Select *sqlite3SelectNew(
Parse *pParse, /* Parsing context */
ExprList *pEList, /* which columns to include in the result */
SrcList *pSrc, /* the FROM clause -- which tables to scan */
Expr *pWhere, /* the WHERE clause */
ExprList *pGroupBy, /* the GROUP BY clause */
Expr *pHaving, /* the HAVING clause */
ExprList *pOrderBy, /* the ORDER BY clause */
u32 selFlags, /* Flag parameters, such as SF_Distinct */
Expr *pLimit /* LIMIT value. NULL means not used */
){
Select *pNew;
Select standin;
pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
if( pNew==0 ){
assert( pParse->db->mallocFailed );
pNew = &standin;
}
if( pEList==0 ){
pEList = sqlite3ExprListAppend(pParse, 0,
sqlite3Expr(pParse->db,TK_ASTERISK,0));
}
pNew->pEList = pEList;
pNew->op = TK_SELECT;
pNew->selFlags = selFlags;
pNew->iLimit = 0;
pNew->iOffset = 0;
pNew->selId = ++pParse->nSelect;
pNew->addrOpenEphm[0] = -1;
pNew->addrOpenEphm[1] = -1;
pNew->nSelectRow = 0;
if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
pNew->pSrc = pSrc;
pNew->pWhere = pWhere;
pNew->pGroupBy = pGroupBy;
pNew->pHaving = pHaving;
pNew->pOrderBy = pOrderBy;
pNew->pPrior = 0;
pNew->pNext = 0;
pNew->pLimit = pLimit;
pNew->pWith = 0;
#ifndef SQLITE_OMIT_WINDOWFUNC
pNew->pWin = 0;
pNew->pWinDefn = 0;
#endif
if( pParse->db->mallocFailed ) {
clearSelect(pParse->db, pNew, pNew!=&standin);
pNew = 0;
}else{
assert( pNew->pSrc!=0 || pParse->nErr>0 );
}
assert( pNew!=&standin );
return pNew;
}
/*
** Delete the given Select structure and all of its substructures.
*/
void sqlite3SelectDelete(sqlite3 *db, Select *p){
if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
}
/*
** Return a pointer to the right-most SELECT statement in a compound.
*/
static Select *findRightmost(Select *p){
while( p->pNext ) p = p->pNext;
return p;
}
/*
** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
** type of join. Return an integer constant that expresses that type
** in terms of the following bit values:
**
** JT_INNER
** JT_CROSS
** JT_OUTER
** JT_NATURAL
** JT_LEFT
** JT_RIGHT
**
** A full outer join is the combination of JT_LEFT and JT_RIGHT.
**
** If an illegal or unsupported join type is seen, then still return
** a join type, but put an error in the pParse structure.
*/
int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
int jointype = 0;
Token *apAll[3];
Token *p;
/* 0123456789 123456789 123456789 123 */
static const char zKeyText[] = "naturaleftouterightfullinnercross";
static const struct {
u8 i; /* Beginning of keyword text in zKeyText[] */
u8 nChar; /* Length of the keyword in characters */
u8 code; /* Join type mask */
} aKeyword[] = {
/* natural */ { 0, 7, JT_NATURAL },
/* left */ { 6, 4, JT_LEFT|JT_OUTER },
/* outer */ { 10, 5, JT_OUTER },
/* right */ { 14, 5, JT_RIGHT|JT_OUTER },
/* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
/* inner */ { 23, 5, JT_INNER },
/* cross */ { 28, 5, JT_INNER|JT_CROSS },
};
int i, j;
apAll[0] = pA;
apAll[1] = pB;
apAll[2] = pC;
for(i=0; i<3 && apAll[i]; i++){
p = apAll[i];
for(j=0; j<ArraySize(aKeyword); j++){
if( p->n==aKeyword[j].nChar
&& sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
jointype |= aKeyword[j].code;
break;
}
}
testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
if( j>=ArraySize(aKeyword) ){
jointype |= JT_ERROR;
break;
}
}
if(
(jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
(jointype & JT_ERROR)!=0
){
const char *zSp = " ";
assert( pB!=0 );
if( pC==0 ){ zSp++; }
sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
"%T %T%s%T", pA, pB, zSp, pC);
jointype = JT_INNER;
}else if( (jointype & JT_OUTER)!=0
&& (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
sqlite3ErrorMsg(pParse,
"RIGHT and FULL OUTER JOINs are not currently supported");
jointype = JT_INNER;
}
return jointype;
}
/*
** Return the index of a column in a table. Return -1 if the column
** is not contained in the table.
*/
static int columnIndex(Table *pTab, const char *zCol){
int i;
for(i=0; i<pTab->nCol; i++){
if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
}
return -1;
}
/*
** Search the first N tables in pSrc, from left to right, looking for a
** table that has a column named zCol.
**
** When found, set *piTab and *piCol to the table index and column index
** of the matching column and return TRUE.
**
** If not found, return FALSE.
*/
static int tableAndColumnIndex(
SrcList *pSrc, /* Array of tables to search */
int N, /* Number of tables in pSrc->a[] to search */
const char *zCol, /* Name of the column we are looking for */
int *piTab, /* Write index of pSrc->a[] here */
int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
){
int i; /* For looping over tables in pSrc */
int iCol; /* Index of column matching zCol */
assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
for(i=0; i<N; i++){
iCol = columnIndex(pSrc->a[i].pTab, zCol);
if( iCol>=0 ){
if( piTab ){
*piTab = i;
*piCol = iCol;
}
return 1;
}
}
return 0;
}
/*
** This function is used to add terms implied by JOIN syntax to the
** WHERE clause expression of a SELECT statement. The new term, which
** is ANDed with the existing WHERE clause, is of the form:
**
** (tab1.col1 = tab2.col2)
**
** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
** column iColRight of tab2.
*/
static void addWhereTerm(
Parse *pParse, /* Parsing context */
SrcList *pSrc, /* List of tables in FROM clause */
int iLeft, /* Index of first table to join in pSrc */
int iColLeft, /* Index of column in first table */
int iRight, /* Index of second table in pSrc */
int iColRight, /* Index of column in second table */
int isOuterJoin, /* True if this is an OUTER join */
Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
){
sqlite3 *db = pParse->db;
Expr *pE1;
Expr *pE2;
Expr *pEq;
assert( iLeft<iRight );
assert( pSrc->nSrc>iRight );
assert( pSrc->a[iLeft].pTab );
assert( pSrc->a[iRight].pTab );
pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
if( pEq && isOuterJoin ){
ExprSetProperty(pEq, EP_FromJoin);
assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
ExprSetVVAProperty(pEq, EP_NoReduce);
pEq->iRightJoinTable = (i16)pE2->iTable;
}
*ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);
}
/*
** Set the EP_FromJoin property on all terms of the given expression.
** And set the Expr.iRightJoinTable to iTable for every term in the
** expression.
**
** The EP_FromJoin property is used on terms of an expression to tell
** the LEFT OUTER JOIN processing logic that this term is part of the
** join restriction specified in the ON or USING clause and not a part
** of the more general WHERE clause. These terms are moved over to the
** WHERE clause during join processing but we need to remember that they
** originated in the ON or USING clause.
**
** The Expr.iRightJoinTable tells the WHERE clause processing that the
** expression depends on table iRightJoinTable even if that table is not
** explicitly mentioned in the expression. That information is needed
** for cases like this:
**
** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
**
** The where clause needs to defer the handling of the t1.x=5
** term until after the t2 loop of the join. In that way, a
** NULL t2 row will be inserted whenever t1.x!=5. If we do not
** defer the handling of t1.x=5, it will be processed immediately
** after the t1 loop and rows with t1.x!=5 will never appear in
** the output, which is incorrect.
*/
void sqlite3SetJoinExpr(Expr *p, int iTable){
while( p ){
ExprSetProperty(p, EP_FromJoin);
assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
ExprSetVVAProperty(p, EP_NoReduce);
p->iRightJoinTable = (i16)iTable;
if( p->op==TK_FUNCTION && p->x.pList ){
int i;
for(i=0; i<p->x.pList->nExpr; i++){
sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable);
}
}
sqlite3SetJoinExpr(p->pLeft, iTable);
p = p->pRight;
}
}
/* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every
** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
** an ordinary term that omits the EP_FromJoin mark.
**
** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
*/
static void unsetJoinExpr(Expr *p, int iTable){
while( p ){
if( ExprHasProperty(p, EP_FromJoin)
&& (iTable<0 || p->iRightJoinTable==iTable) ){
ExprClearProperty(p, EP_FromJoin);
}
if( p->op==TK_FUNCTION && p->x.pList ){
int i;
for(i=0; i<p->x.pList->nExpr; i++){
unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
}
}
unsetJoinExpr(p->pLeft, iTable);
p = p->pRight;
}
}
/*
** This routine processes the join information for a SELECT statement.
** ON and USING clauses are converted into extra terms of the WHERE clause.
** NATURAL joins also create extra WHERE clause terms.
**
** The terms of a FROM clause are contained in the Select.pSrc structure.
** The left most table is the first entry in Select.pSrc. The right-most
** table is the last entry. The join operator is held in the entry to
** the left. Thus entry 0 contains the join operator for the join between
** entries 0 and 1. Any ON or USING clauses associated with the join are
** also attached to the left entry.
**
** This routine returns the number of errors encountered.
*/
static int sqliteProcessJoin(Parse *pParse, Select *p){
SrcList *pSrc; /* All tables in the FROM clause */
int i, j; /* Loop counters */
struct SrcList_item *pLeft; /* Left table being joined */
struct SrcList_item *pRight; /* Right table being joined */
pSrc = p->pSrc;
pLeft = &pSrc->a[0];
pRight = &pLeft[1];
for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
Table *pRightTab = pRight->pTab;
int isOuter;
if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
/* When the NATURAL keyword is present, add WHERE clause terms for
** every column that the two tables have in common.
*/
if( pRight->fg.jointype & JT_NATURAL ){
if( pRight->pOn || pRight->pUsing ){
sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
"an ON or USING clause", 0);
return 1;
}
for(j=0; j<pRightTab->nCol; j++){
char *zName; /* Name of column in the right table */
int iLeft; /* Matching left table */
int iLeftCol; /* Matching column in the left table */
zName = pRightTab->aCol[j].zName;
if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
isOuter, &p->pWhere);
}
}
}
/* Disallow both ON and USING clauses in the same join
*/
if( pRight->pOn && pRight->pUsing ){
sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
"clauses in the same join");
return 1;
}
/* Add the ON clause to the end of the WHERE clause, connected by
** an AND operator.
*/
if( pRight->pOn ){
if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor);
p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn);
pRight->pOn = 0;
}
/* Create extra terms on the WHERE clause for each column named
** in the USING clause. Example: If the two tables to be joined are
** A and B and the USING clause names X, Y, and Z, then add this
** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
** Report an error if any column mentioned in the USING clause is
** not contained in both tables to be joined.
*/
if( pRight->pUsing ){
IdList *pList = pRight->pUsing;
for(j=0; j<pList->nId; j++){
char *zName; /* Name of the term in the USING clause */
int iLeft; /* Table on the left with matching column name */
int iLeftCol; /* Column number of matching column on the left */
int iRightCol; /* Column number of matching column on the right */
zName = pList->a[j].zName;
iRightCol = columnIndex(pRightTab, zName);
if( iRightCol<0
|| !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
){
sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
"not present in both tables", zName);
return 1;
}
addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
isOuter, &p->pWhere);
}
}
}
return 0;
}
/*
** An instance of this object holds information (beyond pParse and pSelect)
** needed to load the next result row that is to be added to the sorter.
*/
typedef struct RowLoadInfo RowLoadInfo;
struct RowLoadInfo {
int regResult; /* Store results in array of registers here */
u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
ExprList *pExtra; /* Extra columns needed by sorter refs */
int regExtraResult; /* Where to load the extra columns */
#endif
};
/*
** This routine does the work of loading query data into an array of
** registers so that it can be added to the sorter.
*/
static void innerLoopLoadRow(
Parse *pParse, /* Statement under construction */
Select *pSelect, /* The query being coded */
RowLoadInfo *pInfo /* Info needed to complete the row load */
){
sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
0, pInfo->ecelFlags);
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( pInfo->pExtra ){
sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
}
#endif
}
/*
** Code the OP_MakeRecord instruction that generates the entry to be
** added into the sorter.
**
** Return the register in which the result is stored.
*/
static int makeSorterRecord(
Parse *pParse,
SortCtx *pSort,
Select *pSelect,
int regBase,
int nBase
){
int nOBSat = pSort->nOBSat;
Vdbe *v = pParse->pVdbe;
int regOut = ++pParse->nMem;
if( pSort->pDeferredRowLoad ){
innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
}
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
return regOut;
}
/*
** Generate code that will push the record in registers regData
** through regData+nData-1 onto the sorter.
*/
static void pushOntoSorter(
Parse *pParse, /* Parser context */
SortCtx *pSort, /* Information about the ORDER BY clause */
Select *pSelect, /* The whole SELECT statement */
int regData, /* First register holding data to be sorted */
int regOrigData, /* First register holding data before packing */
int nData, /* Number of elements in the regData data array */
int nPrefixReg /* No. of reg prior to regData available for use */
){
Vdbe *v = pParse->pVdbe; /* Stmt under construction */
int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
int regBase; /* Regs for sorter record */
int regRecord = 0; /* Assembled sorter record */
int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
int op; /* Opcode to add sorter record to sorter */
int iLimit; /* LIMIT counter */
int iSkip = 0; /* End of the sorter insert loop */
assert( bSeq==0 || bSeq==1 );
/* Three cases:
** (1) The data to be sorted has already been packed into a Record
** by a prior OP_MakeRecord. In this case nData==1 and regData
** will be completely unrelated to regOrigData.
** (2) All output columns are included in the sort record. In that
** case regData==regOrigData.
** (3) Some output columns are omitted from the sort record due to
** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
** SQLITE_ECEL_OMITREF optimization, or due to the
** SortCtx.pDeferredRowLoad optimiation. In any of these cases
** regOrigData is 0 to prevent this routine from trying to copy
** values that might not yet exist.
*/
assert( nData==1 || regData==regOrigData || regOrigData==0 );
if( nPrefixReg ){
assert( nPrefixReg==nExpr+bSeq );
regBase = regData - nPrefixReg;
}else{
regBase = pParse->nMem + 1;
pParse->nMem += nBase;
}
assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
if( bSeq ){
sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
}
if( nPrefixReg==0 && nData>0 ){
sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
}
if( nOBSat>0 ){
int regPrevKey; /* The first nOBSat columns of the previous row */
int addrFirst; /* Address of the OP_IfNot opcode */
int addrJmp; /* Address of the OP_Jump opcode */
VdbeOp *pOp; /* Opcode that opens the sorter */
int nKey; /* Number of sorting key columns, including OP_Sequence */
KeyInfo *pKI; /* Original KeyInfo on the sorter table */
regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
regPrevKey = pParse->nMem+1;
pParse->nMem += pSort->nOBSat;
nKey = nExpr - pSort->nOBSat + bSeq;
if( bSeq ){
addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
}else{
addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
}
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
if( pParse->db->mallocFailed ) return;
pOp->p2 = nKey + nData;
pKI = pOp->p4.pKeyInfo;
memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
testcase( pKI->nAllField > pKI->nKeyField+2 );
pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
pKI->nAllField-pKI->nKeyField-1);
pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */
addrJmp = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
pSort->regReturn = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
if( iLimit ){
sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
VdbeCoverage(v);
}
sqlite3VdbeJumpHere(v, addrFirst);
sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
sqlite3VdbeJumpHere(v, addrJmp);
}
if( iLimit ){
/* At this point the values for the new sorter entry are stored
** in an array of registers. They need to be composed into a record
** and inserted into the sorter if either (a) there are currently
** less than LIMIT+OFFSET items or (b) the new record is smaller than
** the largest record currently in the sorter. If (b) is true and there
** are already LIMIT+OFFSET items in the sorter, delete the largest
** entry before inserting the new one. This way there are never more
** than LIMIT+OFFSET items in the sorter.
**
** If the new record does not need to be inserted into the sorter,
** jump to the next iteration of the loop. If the pSort->labelOBLopt
** value is not zero, then it is a label of where to jump. Otherwise,
** just bypass the row insert logic. See the header comment on the
** sqlite3WhereOrderByLimitOptLabel() function for additional info.
*/
int iCsr = pSort->iECursor;
sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
VdbeCoverage(v);
sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
VdbeCoverage(v);
sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
}
if( regRecord==0 ){
regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
}
if( pSort->sortFlags & SORTFLAG_UseSorter ){
op = OP_SorterInsert;
}else{
op = OP_IdxInsert;
}
sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
regBase+nOBSat, nBase-nOBSat);
if( iSkip ){
sqlite3VdbeChangeP2(v, iSkip,
pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
}
}
/*
** Add code to implement the OFFSET
*/
static void codeOffset(
Vdbe *v, /* Generate code into this VM */
int iOffset, /* Register holding the offset counter */
int iContinue /* Jump here to skip the current record */
){
if( iOffset>0 ){
sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
VdbeComment((v, "OFFSET"));
}
}
/*
** Add code that will check to make sure the N registers starting at iMem
** form a distinct entry. iTab is a sorting index that holds previously
** seen combinations of the N values. A new entry is made in iTab
** if the current N values are new.
**
** A jump to addrRepeat is made and the N+1 values are popped from the
** stack if the top N elements are not distinct.
*/
static void codeDistinct(
Parse *pParse, /* Parsing and code generating context */
int iTab, /* A sorting index used to test for distinctness */
int addrRepeat, /* Jump to here if not distinct */
int N, /* Number of elements */
int iMem /* First element */
){
Vdbe *v;
int r1;
v = pParse->pVdbe;
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
sqlite3ReleaseTempReg(pParse, r1);
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
/*
** This function is called as part of inner-loop generation for a SELECT
** statement with an ORDER BY that is not optimized by an index. It
** determines the expressions, if any, that the sorter-reference
** optimization should be used for. The sorter-reference optimization
** is used for SELECT queries like:
**
** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
**
** If the optimization is used for expression "bigblob", then instead of
** storing values read from that column in the sorter records, the PK of
** the row from table t1 is stored instead. Then, as records are extracted from
** the sorter to return to the user, the required value of bigblob is
** retrieved directly from table t1. If the values are very large, this
** can be more efficient than storing them directly in the sorter records.
**
** The ExprList_item.bSorterRef flag is set for each expression in pEList
** for which the sorter-reference optimization should be enabled.
** Additionally, the pSort->aDefer[] array is populated with entries
** for all cursors required to evaluate all selected expressions. Finally.
** output variable (*ppExtra) is set to an expression list containing
** expressions for all extra PK values that should be stored in the
** sorter records.
*/
static void selectExprDefer(
Parse *pParse, /* Leave any error here */
SortCtx *pSort, /* Sorter context */
ExprList *pEList, /* Expressions destined for sorter */
ExprList **ppExtra /* Expressions to append to sorter record */
){
int i;
int nDefer = 0;
ExprList *pExtra = 0;
for(i=0; i<pEList->nExpr; i++){
struct ExprList_item *pItem = &pEList->a[i];
if( pItem->u.x.iOrderByCol==0 ){
Expr *pExpr = pItem->pExpr;
Table *pTab = pExpr->y.pTab;
if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
&& (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
){
int j;
for(j=0; j<nDefer; j++){
if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
}
if( j==nDefer ){
if( nDefer==ArraySize(pSort->aDefer) ){
continue;
}else{
int nKey = 1;
int k;
Index *pPk = 0;
if( !HasRowid(pTab) ){
pPk = sqlite3PrimaryKeyIndex(pTab);
nKey = pPk->nKeyCol;
}
for(k=0; k<nKey; k++){
Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
if( pNew ){
pNew->iTable = pExpr->iTable;
pNew->y.pTab = pExpr->y.pTab;
pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
}
}
pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
pSort->aDefer[nDefer].iCsr = pExpr->iTable;
pSort->aDefer[nDefer].nKey = nKey;
nDefer++;
}
}
pItem->bSorterRef = 1;
}
}
}
pSort->nDefer = (u8)nDefer;
*ppExtra = pExtra;
}
#endif
/*
** This routine generates the code for the inside of the inner loop
** of a SELECT.
**
** If srcTab is negative, then the p->pEList expressions
** are evaluated in order to get the data for this row. If srcTab is
** zero or more, then data is pulled from srcTab and p->pEList is used only
** to get the number of columns and the collation sequence for each column.
*/
static void selectInnerLoop(
Parse *pParse, /* The parser context */
Select *p, /* The complete select statement being coded */
int srcTab, /* Pull data from this table if non-negative */
SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
SelectDest *pDest, /* How to dispose of the results */
int iContinue, /* Jump here to continue with next row */
int iBreak /* Jump here to break out of the inner loop */
){
Vdbe *v = pParse->pVdbe;
int i;
int hasDistinct; /* True if the DISTINCT keyword is present */
int eDest = pDest->eDest; /* How to dispose of results */
int iParm = pDest->iSDParm; /* First argument to disposal method */
int nResultCol; /* Number of result columns */
int nPrefixReg = 0; /* Number of extra registers before regResult */
RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
/* Usually, regResult is the first cell in an array of memory cells
** containing the current result row. In this case regOrig is set to the
** same value. However, if the results are being sent to the sorter, the
** values for any expressions that are also part of the sort-key are omitted
** from this array. In this case regOrig is set to zero. */
int regResult; /* Start of memory holding current results */
int regOrig; /* Start of memory holding full result (or 0) */
assert( v );
assert( p->pEList!=0 );
hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
if( pSort && pSort->pOrderBy==0 ) pSort = 0;
if( pSort==0 && !hasDistinct ){
assert( iContinue!=0 );
codeOffset(v, p->iOffset, iContinue);
}
/* Pull the requested columns.
*/
nResultCol = p->pEList->nExpr;
if( pDest->iSdst==0 ){
if( pSort ){
nPrefixReg = pSort->pOrderBy->nExpr;
if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
pParse->nMem += nPrefixReg;
}
pDest->iSdst = pParse->nMem+1;
pParse->nMem += nResultCol;
}else if( pDest->iSdst+nResultCol > pParse->nMem ){
/* This is an error condition that can result, for example, when a SELECT
** on the right-hand side of an INSERT contains more result columns than
** there are columns in the table on the left. The error will be caught
** and reported later. But we need to make sure enough memory is allocated
** to avoid other spurious errors in the meantime. */
pParse->nMem += nResultCol;
}
pDest->nSdst = nResultCol;
regOrig = regResult = pDest->iSdst;
if( srcTab>=0 ){
for(i=0; i<nResultCol; i++){
sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
VdbeComment((v, "%s", p->pEList->a[i].zName));
}
}else if( eDest!=SRT_Exists ){
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
ExprList *pExtra = 0;
#endif
/* If the destination is an EXISTS(...) expression, the actual
** values returned by the SELECT are not required.
*/
u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
ExprList *pEList;
if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
ecelFlags = SQLITE_ECEL_DUP;
}else{
ecelFlags = 0;
}
if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
/* For each expression in p->pEList that is a copy of an expression in
** the ORDER BY clause (pSort->pOrderBy), set the associated
** iOrderByCol value to one more than the index of the ORDER BY
** expression within the sort-key that pushOntoSorter() will generate.
** This allows the p->pEList field to be omitted from the sorted record,
** saving space and CPU cycles. */
ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
int j;
if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
}
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
selectExprDefer(pParse, pSort, p->pEList, &pExtra);
if( pExtra && pParse->db->mallocFailed==0 ){
/* If there are any extra PK columns to add to the sorter records,
** allocate extra memory cells and adjust the OpenEphemeral
** instruction to account for the larger records. This is only
** required if there are one or more WITHOUT ROWID tables with
** composite primary keys in the SortCtx.aDefer[] array. */
VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
pOp->p2 += (pExtra->nExpr - pSort->nDefer);
pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
pParse->nMem += pExtra->nExpr;
}
#endif
/* Adjust nResultCol to account for columns that are omitted
** from the sorter by the optimizations in this branch */
pEList = p->pEList;
for(i=0; i<pEList->nExpr; i++){
if( pEList->a[i].u.x.iOrderByCol>0
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
|| pEList->a[i].bSorterRef
#endif
){
nResultCol--;
regOrig = 0;
}
}
testcase( regOrig );
testcase( eDest==SRT_Set );
testcase( eDest==SRT_Mem );
testcase( eDest==SRT_Coroutine );
testcase( eDest==SRT_Output );
assert( eDest==SRT_Set || eDest==SRT_Mem
|| eDest==SRT_Coroutine || eDest==SRT_Output );
}
sRowLoadInfo.regResult = regResult;
sRowLoadInfo.ecelFlags = ecelFlags;
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
sRowLoadInfo.pExtra = pExtra;
sRowLoadInfo.regExtraResult = regResult + nResultCol;
if( pExtra ) nResultCol += pExtra->nExpr;
#endif
if( p->iLimit
&& (ecelFlags & SQLITE_ECEL_OMITREF)!=0
&& nPrefixReg>0
){
assert( pSort!=0 );
assert( hasDistinct==0 );
pSort->pDeferredRowLoad = &sRowLoadInfo;
regOrig = 0;
}else{
innerLoopLoadRow(pParse, p, &sRowLoadInfo);
}
}
/* If the DISTINCT keyword was present on the SELECT statement
** and this row has been seen before, then do not make this row
** part of the result.
*/
if( hasDistinct ){
switch( pDistinct->eTnctType ){
case WHERE_DISTINCT_ORDERED: {
VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
int iJump; /* Jump destination */
int regPrev; /* Previous row content */
/* Allocate space for the previous row */
regPrev = pParse->nMem+1;
pParse->nMem += nResultCol;
/* Change the OP_OpenEphemeral coded earlier to an OP_Null
** sets the MEM_Cleared bit on the first register of the
** previous value. This will cause the OP_Ne below to always
** fail on the first iteration of the loop even if the first
** row is all NULLs.
*/
sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
pOp->opcode = OP_Null;
pOp->p1 = 1;
pOp->p2 = regPrev;
pOp = 0; /* Ensure pOp is not used after sqlite3VdbeAddOp() */
iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
for(i=0; i<nResultCol; i++){
CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
if( i<nResultCol-1 ){
sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
VdbeCoverage(v);
}else{
sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
VdbeCoverage(v);
}
sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
}
assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
break;
}
case WHERE_DISTINCT_UNIQUE: {
sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
break;
}
default: {
assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
regResult);
break;
}
}
if( pSort==0 ){
codeOffset(v, p->iOffset, iContinue);
}
}
switch( eDest ){
/* In this mode, write each query result to the key of the temporary
** table iParm.
*/
#ifndef SQLITE_OMIT_COMPOUND_SELECT
case SRT_Union: {
int r1;
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
sqlite3ReleaseTempReg(pParse, r1);
break;
}
/* Construct a record from the query result, but instead of
** saving that record, use it as a key to delete elements from
** the temporary table iParm.
*/
case SRT_Except: {
sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
break;
}
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
/* Store the result as data using a unique key.
*/
case SRT_Fifo:
case SRT_DistFifo:
case SRT_Table:
case SRT_EphemTab: {
int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
testcase( eDest==SRT_Table );
testcase( eDest==SRT_EphemTab );
testcase( eDest==SRT_Fifo );
testcase( eDest==SRT_DistFifo );
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
#ifndef SQLITE_OMIT_CTE
if( eDest==SRT_DistFifo ){
/* If the destination is DistFifo, then cursor (iParm+1) is open
** on an ephemeral index. If the current row is already present
** in the index, do not write it to the output. If not, add the
** current row to the index and proceed with writing it to the
** output table as well. */
int addr = sqlite3VdbeCurrentAddr(v) + 4;
sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
VdbeCoverage(v);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
assert( pSort==0 );
}
#endif
if( pSort ){
assert( regResult==regOrig );
pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
}else{
int r2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
sqlite3ReleaseTempReg(pParse, r2);
}
sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
/* If we are creating a set for an "expr IN (SELECT ...)" construct,
** then there should be a single item on the stack. Write this
** item into the set table with bogus data.
*/
case SRT_Set: {
if( pSort ){
/* At first glance you would think we could optimize out the
** ORDER BY in this case since the order of entries in the set
** does not matter. But there might be a LIMIT clause, in which
** case the order does matter */
pushOntoSorter(
pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
}else{
int r1 = sqlite3GetTempReg(pParse);
assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
r1, pDest->zAffSdst, nResultCol);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
sqlite3ReleaseTempReg(pParse, r1);
}
break;
}
/* If any row exist in the result set, record that fact and abort.
*/
case SRT_Exists: {
sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
/* The LIMIT clause will terminate the loop for us */
break;
}
/* If this is a scalar select that is part of an expression, then
** store the results in the appropriate memory cell or array of
** memory cells and break out of the scan loop.
*/
case SRT_Mem: {
if( pSort ){
assert( nResultCol<=pDest->nSdst );
pushOntoSorter(
pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
}else{
assert( nResultCol==pDest->nSdst );
assert( regResult==iParm );
/* The LIMIT clause will jump out of the loop for us */
}
break;
}
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
case SRT_Coroutine: /* Send data to a co-routine */
case SRT_Output: { /* Return the results */
testcase( eDest==SRT_Coroutine );
testcase( eDest==SRT_Output );
if( pSort ){
pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
nPrefixReg);
}else if( eDest==SRT_Coroutine ){
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
}else{
sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
}
break;
}
#ifndef SQLITE_OMIT_CTE
/* Write the results into a priority queue that is order according to
** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
** index with pSO->nExpr+2 columns. Build a key using pSO for the first
** pSO->nExpr columns, then make sure all keys are unique by adding a
** final OP_Sequence column. The last column is the record as a blob.
*/
case SRT_DistQueue:
case SRT_Queue: {
int nKey;
int r1, r2, r3;
int addrTest = 0;
ExprList *pSO;
pSO = pDest->pOrderBy;
assert( pSO );
nKey = pSO->nExpr;
r1 = sqlite3GetTempReg(pParse);
r2 = sqlite3GetTempRange(pParse, nKey+2);
r3 = r2+nKey+1;
if( eDest==SRT_DistQueue ){
/* If the destination is DistQueue, then cursor (iParm+1) is open
** on a second ephemeral index that holds all values every previously
** added to the queue. */
addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
regResult, nResultCol);
VdbeCoverage(v);
}
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
if( eDest==SRT_DistQueue ){
sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
}
for(i=0; i<nKey; i++){
sqlite3VdbeAddOp2(v, OP_SCopy,
regResult + pSO->a[i].u.x.iOrderByCol - 1,
r2+i);
}
sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
sqlite3ReleaseTempReg(pParse, r1);
sqlite3ReleaseTempRange(pParse, r2, nKey+2);
break;
}
#endif /* SQLITE_OMIT_CTE */
#if !defined(SQLITE_OMIT_TRIGGER)
/* Discard the results. This is used for SELECT statements inside
** the body of a TRIGGER. The purpose of such selects is to call
** user-defined functions that have side effects. We do not care
** about the actual results of the select.
*/
default: {
assert( eDest==SRT_Discard );
break;
}
#endif
}
/* Jump to the end of the loop if the LIMIT is reached. Except, if
** there is a sorter, in which case the sorter has already limited
** the output for us.
*/
if( pSort==0 && p->iLimit ){
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
}
}
/*
** Allocate a KeyInfo object sufficient for an index of N key columns and
** X extra columns.
*/
KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
if( p ){
p->aSortFlags = (u8*)&p->aColl[N+X];
p->nKeyField = (u16)N;
p->nAllField = (u16)(N+X);
p->enc = ENC(db);
p->db = db;
p->nRef = 1;
memset(&p[1], 0, nExtra);
}else{
sqlite3OomFault(db);
}
return p;
}
/*
** Deallocate a KeyInfo object
*/
void sqlite3KeyInfoUnref(KeyInfo *p){
if( p ){
assert( p->nRef>0 );
p->nRef--;
if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
}
}
/*
** Make a new pointer to a KeyInfo object
*/
KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
if( p ){
assert( p->nRef>0 );
p->nRef++;
}
return p;
}
#ifdef SQLITE_DEBUG
/*
** Return TRUE if a KeyInfo object can be change. The KeyInfo object
** can only be changed if this is just a single reference to the object.
**
** This routine is used only inside of assert() statements.
*/
int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
#endif /* SQLITE_DEBUG */
/*
** Given an expression list, generate a KeyInfo structure that records
** the collating sequence for each expression in that expression list.
**
** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
** KeyInfo structure is appropriate for initializing a virtual index to
** implement that clause. If the ExprList is the result set of a SELECT
** then the KeyInfo structure is appropriate for initializing a virtual
** index to implement a DISTINCT test.
**
** Space to hold the KeyInfo structure is obtained from malloc. The calling
** function is responsible for seeing that this structure is eventually
** freed.
*/
KeyInfo *sqlite3KeyInfoFromExprList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* Form the KeyInfo object from this ExprList */
int iStart, /* Begin with this column of pList */
int nExtra /* Add this many extra columns to the end */
){
int nExpr;
KeyInfo *pInfo;
struct ExprList_item *pItem;
sqlite3 *db = pParse->db;
int i;
nExpr = pList->nExpr;
pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
if( pInfo ){
assert( sqlite3KeyInfoIsWriteable(pInfo) );
for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
pInfo->aSortFlags[i-iStart] = pItem->sortFlags;
}
}
return pInfo;
}
/*
** Name of the connection operator, used for error messages.
*/
static const char *selectOpName(int id){
char *z;
switch( id ){
case TK_ALL: z = "UNION ALL"; break;
case TK_INTERSECT: z = "INTERSECT"; break;
case TK_EXCEPT: z = "EXCEPT"; break;
default: z = "UNION"; break;
}
return z;
}
#ifndef SQLITE_OMIT_EXPLAIN
/*
** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
** is a no-op. Otherwise, it adds a single row of output to the EQP result,
** where the caption is of the form:
**
** "USE TEMP B-TREE FOR xxx"
**
** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
** is determined by the zUsage argument.
*/
static void explainTempTable(Parse *pParse, const char *zUsage){
ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
}
/*
** Assign expression b to lvalue a. A second, no-op, version of this macro
** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
** in sqlite3Select() to assign values to structure member variables that
** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
** code with #ifndef directives.
*/
# define explainSetInteger(a, b) a = b
#else
/* No-op versions of the explainXXX() functions and macros. */
# define explainTempTable(y,z)
# define explainSetInteger(y,z)
#endif
/*
** If the inner loop was generated using a non-null pOrderBy argument,
** then the results were placed in a sorter. After the loop is terminated
** we need to run the sorter and output the results. The following
** routine generates the code needed to do that.
*/
static void generateSortTail(
Parse *pParse, /* Parsing context */
Select *p, /* The SELECT statement */
SortCtx *pSort, /* Information on the ORDER BY clause */
int nColumn, /* Number of columns of data */
SelectDest *pDest /* Write the sorted results here */
){
Vdbe *v = pParse->pVdbe; /* The prepared statement */
int addrBreak = pSort->labelDone; /* Jump here to exit loop */
int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
int addr; /* Top of output loop. Jump for Next. */
int addrOnce = 0;
int iTab;
ExprList *pOrderBy = pSort->pOrderBy;
int eDest = pDest->eDest;
int iParm = pDest->iSDParm;
int regRow;
int regRowid;
int iCol;
int nKey; /* Number of key columns in sorter record */
int iSortTab; /* Sorter cursor to read from */
int i;
int bSeq; /* True if sorter record includes seq. no. */
int nRefKey = 0;
struct ExprList_item *aOutEx = p->pEList->a;
assert( addrBreak<0 );
if( pSort->labelBkOut ){
sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
sqlite3VdbeGoto(v, addrBreak);
sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
/* Open any cursors needed for sorter-reference expressions */
for(i=0; i<pSort->nDefer; i++){
Table *pTab = pSort->aDefer[i].pTab;
int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
}
#endif
iTab = pSort->iECursor;
if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
regRowid = 0;
regRow = pDest->iSdst;
}else{
regRowid = sqlite3GetTempReg(pParse);
if( eDest==SRT_EphemTab || eDest==SRT_Table ){
regRow = sqlite3GetTempReg(pParse);
nColumn = 0;
}else{
regRow = sqlite3GetTempRange(pParse, nColumn);
}
}
nKey = pOrderBy->nExpr - pSort->nOBSat;
if( pSort->sortFlags & SORTFLAG_UseSorter ){
int regSortOut = ++pParse->nMem;
iSortTab = pParse->nTab++;
if( pSort->labelBkOut ){
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
}
sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
nKey+1+nColumn+nRefKey);
if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
VdbeCoverage(v);
codeOffset(v, p->iOffset, addrContinue);
sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
bSeq = 0;
}else{
addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
codeOffset(v, p->iOffset, addrContinue);
iSortTab = iTab;
bSeq = 1;
}
for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( aOutEx[i].bSorterRef ) continue;
#endif
if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( pSort->nDefer ){
int iKey = iCol+1;
int regKey = sqlite3GetTempRange(pParse, nRefKey);
for(i=0; i<pSort->nDefer; i++){
int iCsr = pSort->aDefer[i].iCsr;
Table *pTab = pSort->aDefer[i].pTab;
int nKey = pSort->aDefer[i].nKey;
sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
if( HasRowid(pTab) ){
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
sqlite3VdbeCurrentAddr(v)+1, regKey);
}else{
int k;
int iJmp;
assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
for(k=0; k<nKey; k++){
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
}
iJmp = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
}
}
sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
}
#endif
for(i=nColumn-1; i>=0; i--){
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( aOutEx[i].bSorterRef ){
sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
}else
#endif
{
int iRead;
if( aOutEx[i].u.x.iOrderByCol ){
iRead = aOutEx[i].u.x.iOrderByCol-1;
}else{
iRead = iCol--;
}
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan));
}
}
switch( eDest ){
case SRT_Table:
case SRT_EphemTab: {
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case SRT_Set: {
assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
pDest->zAffSdst, nColumn);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
break;
}
case SRT_Mem: {
/* The LIMIT clause will terminate the loop for us */
break;
}
#endif
default: {
assert( eDest==SRT_Output || eDest==SRT_Coroutine );
testcase( eDest==SRT_Output );
testcase( eDest==SRT_Coroutine );
if( eDest==SRT_Output ){
sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
}else{
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
}
break;
}
}
if( regRowid ){
if( eDest==SRT_Set ){
sqlite3ReleaseTempRange(pParse, regRow, nColumn);
}else{
sqlite3ReleaseTempReg(pParse, regRow);
}
sqlite3ReleaseTempReg(pParse, regRowid);
}
/* The bottom of the loop
*/
sqlite3VdbeResolveLabel(v, addrContinue);
if( pSort->sortFlags & SORTFLAG_UseSorter ){
sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
}else{
sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
}
if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
sqlite3VdbeResolveLabel(v, addrBreak);
}
/*
** Return a pointer to a string containing the 'declaration type' of the
** expression pExpr. The string may be treated as static by the caller.
**
** Also try to estimate the size of the returned value and return that
** result in *pEstWidth.
**
** The declaration type is the exact datatype definition extracted from the
** original CREATE TABLE statement if the expression is a column. The
** declaration type for a ROWID field is INTEGER. Exactly when an expression
** is considered a column can be complex in the presence of subqueries. The
** result-set expression in all of the following SELECT statements is
** considered a column by this function.
**
** SELECT col FROM tbl;
** SELECT (SELECT col FROM tbl;
** SELECT (SELECT col FROM tbl);
** SELECT abc FROM (SELECT col AS abc FROM tbl);
**
** The declaration type for any expression other than a column is NULL.
**
** This routine has either 3 or 6 parameters depending on whether or not
** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
*/
#ifdef SQLITE_ENABLE_COLUMN_METADATA
# define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
# define columnType(A,B,C,D,E) columnTypeImpl(A,B)
#endif
static const char *columnTypeImpl(
NameContext *pNC,
#ifndef SQLITE_ENABLE_COLUMN_METADATA
Expr *pExpr
#else
Expr *pExpr,
const char **pzOrigDb,
const char **pzOrigTab,
const char **pzOrigCol
#endif
){
char const *zType = 0;
int j;
#ifdef SQLITE_ENABLE_COLUMN_METADATA
char const *zOrigDb = 0;
char const *zOrigTab = 0;
char const *zOrigCol = 0;
#endif
assert( pExpr!=0 );
assert( pNC->pSrcList!=0 );
switch( pExpr->op ){
case TK_COLUMN: {
/* The expression is a column. Locate the table the column is being
** extracted from in NameContext.pSrcList. This table may be real
** database table or a subquery.
*/
Table *pTab = 0; /* Table structure column is extracted from */
Select *pS = 0; /* Select the column is extracted from */
int iCol = pExpr->iColumn; /* Index of column in pTab */
while( pNC && !pTab ){
SrcList *pTabList = pNC->pSrcList;
for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
if( j<pTabList->nSrc ){
pTab = pTabList->a[j].pTab;
pS = pTabList->a[j].pSelect;
}else{
pNC = pNC->pNext;
}
}
if( pTab==0 ){
/* At one time, code such as "SELECT new.x" within a trigger would
** cause this condition to run. Since then, we have restructured how
** trigger code is generated and so this condition is no longer
** possible. However, it can still be true for statements like
** the following:
**
** CREATE TABLE t1(col INTEGER);
** SELECT (SELECT t1.col) FROM FROM t1;
**
** when columnType() is called on the expression "t1.col" in the
** sub-select. In this case, set the column type to NULL, even
** though it should really be "INTEGER".
**
** This is not a problem, as the column type of "t1.col" is never
** used. When columnType() is called on the expression
** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
** branch below. */
break;
}
assert( pTab && pExpr->y.pTab==pTab );
if( pS ){
/* The "table" is actually a sub-select or a view in the FROM clause
** of the SELECT statement. Return the declaration type and origin
** data for the result-set column of the sub-select.
*/
if( iCol>=0 && iCol<pS->pEList->nExpr ){
/* If iCol is less than zero, then the expression requests the
** rowid of the sub-select or view. This expression is legal (see
** test case misc2.2.2) - it always evaluates to NULL.
*/
NameContext sNC;
Expr *p = pS->pEList->a[iCol].pExpr;
sNC.pSrcList = pS->pSrc;
sNC.pNext = pNC;
sNC.pParse = pNC->pParse;
zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
}
}else{
/* A real table or a CTE table */
assert( !pS );
#ifdef SQLITE_ENABLE_COLUMN_METADATA
if( iCol<0 ) iCol = pTab->iPKey;
assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
if( iCol<0 ){
zType = "INTEGER";
zOrigCol = "rowid";
}else{
zOrigCol = pTab->aCol[iCol].zName;
zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
}
zOrigTab = pTab->zName;
if( pNC->pParse && pTab->pSchema ){
int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
}
#else
assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
if( iCol<0 ){
zType = "INTEGER";
}else{
zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
}
#endif
}
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_SELECT: {
/* The expression is a sub-select. Return the declaration type and
** origin info for the single column in the result set of the SELECT
** statement.
*/
NameContext sNC;
Select *pS = pExpr->x.pSelect;
Expr *p = pS->pEList->a[0].pExpr;
assert( ExprHasProperty(pExpr, EP_xIsSelect) );
sNC.pSrcList = pS->pSrc;
sNC.pNext = pNC;
sNC.pParse = pNC->pParse;
zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
break;
}
#endif
}
#ifdef SQLITE_ENABLE_COLUMN_METADATA
if( pzOrigDb ){
assert( pzOrigTab && pzOrigCol );
*pzOrigDb = zOrigDb;
*pzOrigTab = zOrigTab;
*pzOrigCol = zOrigCol;
}
#endif
return zType;
}
/*
** Generate code that will tell the VDBE the declaration types of columns
** in the result set.
*/
static void generateColumnTypes(
Parse *pParse, /* Parser context */
SrcList *pTabList, /* List of tables */
ExprList *pEList /* Expressions defining the result set */
){
#ifndef SQLITE_OMIT_DECLTYPE
Vdbe *v = pParse->pVdbe;
int i;
NameContext sNC;
sNC.pSrcList = pTabList;
sNC.pParse = pParse;
sNC.pNext = 0;
for(i=0; i<pEList->nExpr; i++){
Expr *p = pEList->a[i].pExpr;
const char *zType;
#ifdef SQLITE_ENABLE_COLUMN_METADATA
const char *zOrigDb = 0;
const char *zOrigTab = 0;
const char *zOrigCol = 0;
zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
/* The vdbe must make its own copy of the column-type and other
** column specific strings, in case the schema is reset before this
** virtual machine is deleted.
*/
sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
#else
zType = columnType(&sNC, p, 0, 0, 0);
#endif
sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
}
#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
}
/*
** Compute the column names for a SELECT statement.
**
** The only guarantee that SQLite makes about column names is that if the
** column has an AS clause assigning it a name, that will be the name used.
** That is the only documented guarantee. However, countless applications
** developed over the years have made baseless assumptions about column names
** and will break if those assumptions changes. Hence, use extreme caution
** when modifying this routine to avoid breaking legacy.
**
** See Also: sqlite3ColumnsFromExprList()
**
** The PRAGMA short_column_names and PRAGMA full_column_names settings are
** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
** applications should operate this way. Nevertheless, we need to support the
** other modes for legacy:
**
** short=OFF, full=OFF: Column name is the text of the expression has it
** originally appears in the SELECT statement. In
** other words, the zSpan of the result expression.
**
** short=ON, full=OFF: (This is the default setting). If the result
** refers directly to a table column, then the
** result column name is just the table column
** name: COLUMN. Otherwise use zSpan.
**
** full=ON, short=ANY: If the result refers directly to a table column,
** then the result column name with the table name
** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
*/
static void generateColumnNames(
Parse *pParse, /* Parser context */
Select *pSelect /* Generate column names for this SELECT statement */
){
Vdbe *v = pParse->pVdbe;
int i;
Table *pTab;
SrcList *pTabList;
ExprList *pEList;
sqlite3 *db = pParse->db;
int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
#ifndef SQLITE_OMIT_EXPLAIN
/* If this is an EXPLAIN, skip this step */
if( pParse->explain ){
return;
}
#endif
if( pParse->colNamesSet ) return;
/* Column names are determined by the left-most term of a compound select */
while( pSelect->pPrior ) pSelect = pSelect->pPrior;
SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
pTabList = pSelect->pSrc;
pEList = pSelect->pEList;
assert( v!=0 );
assert( pTabList!=0 );
pParse->colNamesSet = 1;
fullName = (db->flags & SQLITE_FullColNames)!=0;
srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
sqlite3VdbeSetNumCols(v, pEList->nExpr);
for(i=0; i<pEList->nExpr; i++){
Expr *p = pEList->a[i].pExpr;
assert( p!=0 );
assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
if( pEList->a[i].zName ){
/* An AS clause always takes first priority */
char *zName = pEList->a[i].zName;
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
}else if( srcName && p->op==TK_COLUMN ){
char *zCol;
int iCol = p->iColumn;
pTab = p->y.pTab;
assert( pTab!=0 );
if( iCol<0 ) iCol = pTab->iPKey;
assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
if( iCol<0 ){
zCol = "rowid";
}else{
zCol = pTab->aCol[iCol].zName;
}
if( fullName ){
char *zName = 0;
zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
}else{
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
}
}else{
const char *z = pEList->a[i].zSpan;
z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
}
}
generateColumnTypes(pParse, pTabList, pEList);
}
/*
** Given an expression list (which is really the list of expressions
** that form the result set of a SELECT statement) compute appropriate
** column names for a table that would hold the expression list.
**
** All column names will be unique.
**
** Only the column names are computed. Column.zType, Column.zColl,
** and other fields of Column are zeroed.
**
** Return SQLITE_OK on success. If a memory allocation error occurs,
** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
**
** The only guarantee that SQLite makes about column names is that if the
** column has an AS clause assigning it a name, that will be the name used.
** That is the only documented guarantee. However, countless applications
** developed over the years have made baseless assumptions about column names
** and will break if those assumptions changes. Hence, use extreme caution
** when modifying this routine to avoid breaking legacy.
**
** See Also: generateColumnNames()
*/
int sqlite3ColumnsFromExprList(
Parse *pParse, /* Parsing context */
ExprList *pEList, /* Expr list from which to derive column names */
i16 *pnCol, /* Write the number of columns here */
Column **paCol /* Write the new column list here */
){
sqlite3 *db = pParse->db; /* Database connection */
int i, j; /* Loop counters */
u32 cnt; /* Index added to make the name unique */
Column *aCol, *pCol; /* For looping over result columns */
int nCol; /* Number of columns in the result set */
char *zName; /* Column name */
int nName; /* Size of name in zName[] */
Hash ht; /* Hash table of column names */
sqlite3HashInit(&ht);
if( pEList ){
nCol = pEList->nExpr;
aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
testcase( aCol==0 );
if( nCol>32767 ) nCol = 32767;
}else{
nCol = 0;
aCol = 0;
}
assert( nCol==(i16)nCol );
*pnCol = nCol;
*paCol = aCol;
for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
/* Get an appropriate name for the column
*/
if( (zName = pEList->a[i].zName)!=0 ){
/* If the column contains an "AS <name>" phrase, use <name> as the name */
}else{
Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr);
while( pColExpr->op==TK_DOT ){
pColExpr = pColExpr->pRight;
assert( pColExpr!=0 );
}
if( pColExpr->op==TK_COLUMN ){
/* For columns use the column name name */
int iCol = pColExpr->iColumn;
Table *pTab = pColExpr->y.pTab;
assert( pTab!=0 );
if( iCol<0 ) iCol = pTab->iPKey;
zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
}else if( pColExpr->op==TK_ID ){
assert( !ExprHasProperty(pColExpr, EP_IntValue) );
zName = pColExpr->u.zToken;
}else{
/* Use the original text of the column expression as its name */
zName = pEList->a[i].zSpan;
}
}
if( zName ){
zName = sqlite3DbStrDup(db, zName);
}else{
zName = sqlite3MPrintf(db,"column%d",i+1);
}
/* Make sure the column name is unique. If the name is not unique,
** append an integer to the name so that it becomes unique.
*/
cnt = 0;
while( zName && sqlite3HashFind(&ht, zName)!=0 ){
nName = sqlite3Strlen30(zName);
if( nName>0 ){
for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
if( zName[j]==':' ) nName = j;
}
zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
}
pCol->zName = zName;
sqlite3ColumnPropertiesFromName(0, pCol);
if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
sqlite3OomFault(db);
}
}
sqlite3HashClear(&ht);
if( db->mallocFailed ){
for(j=0; j<i; j++){
sqlite3DbFree(db, aCol[j].zName);
}
sqlite3DbFree(db, aCol);
*paCol = 0;
*pnCol = 0;
return SQLITE_NOMEM_BKPT;
}
return SQLITE_OK;
}
/*
** Add type and collation information to a column list based on
** a SELECT statement.
**
** The column list presumably came from selectColumnNamesFromExprList().
** The column list has only names, not types or collations. This
** routine goes through and adds the types and collations.
**
** This routine requires that all identifiers in the SELECT
** statement be resolved.
*/
void sqlite3SelectAddColumnTypeAndCollation(
Parse *pParse, /* Parsing contexts */
Table *pTab, /* Add column type information to this table */
Select *pSelect, /* SELECT used to determine types and collations */
char aff /* Default affinity for columns */
){
sqlite3 *db = pParse->db;
NameContext sNC;
Column *pCol;
CollSeq *pColl;
int i;
Expr *p;
struct ExprList_item *a;
assert( pSelect!=0 );
assert( (pSelect->selFlags & SF_Resolved)!=0 );
assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
if( db->mallocFailed ) return;
memset(&sNC, 0, sizeof(sNC));
sNC.pSrcList = pSelect->pSrc;
a = pSelect->pEList->a;
for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
const char *zType;
int n, m;
p = a[i].pExpr;
zType = columnType(&sNC, p, 0, 0, 0);
/* pCol->szEst = ... // Column size est for SELECT tables never used */
pCol->affinity = sqlite3ExprAffinity(p);
if( zType ){
m = sqlite3Strlen30(zType);
n = sqlite3Strlen30(pCol->zName);
pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
if( pCol->zName ){
memcpy(&pCol->zName[n+1], zType, m+1);
pCol->colFlags |= COLFLAG_HASTYPE;
}
}
if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff;
pColl = sqlite3ExprCollSeq(pParse, p);
if( pColl && pCol->zColl==0 ){
pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
}
}
pTab->szTabRow = 1; /* Any non-zero value works */
}
/*
** Given a SELECT statement, generate a Table structure that describes
** the result set of that SELECT.
*/
Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
Table *pTab;
sqlite3 *db = pParse->db;
u64 savedFlags;
savedFlags = db->flags;
db->flags &= ~(u64)SQLITE_FullColNames;
db->flags |= SQLITE_ShortColNames;
sqlite3SelectPrep(pParse, pSelect, 0);
db->flags = savedFlags;
if( pParse->nErr ) return 0;
while( pSelect->pPrior ) pSelect = pSelect->pPrior;
pTab = sqlite3DbMallocZero(db, sizeof(Table) );
if( pTab==0 ){
return 0;
}
pTab->nTabRef = 1;
pTab->zName = 0;
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff);
pTab->iPKey = -1;
if( db->mallocFailed ){
sqlite3DeleteTable(db, pTab);
return 0;
}
return pTab;
}
/*
** Get a VDBE for the given parser context. Create a new one if necessary.
** If an error occurs, return NULL and leave a message in pParse.
*/
Vdbe *sqlite3GetVdbe(Parse *pParse){
if( pParse->pVdbe ){
return pParse->pVdbe;
}
if( pParse->pToplevel==0
&& OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
){
pParse->okConstFactor = 1;
}
return sqlite3VdbeCreate(pParse);
}
/*
** Compute the iLimit and iOffset fields of the SELECT based on the
** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
** that appear in the original SQL statement after the LIMIT and OFFSET
** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
** are the integer memory register numbers for counters used to compute
** the limit and offset. If there is no limit and/or offset, then
** iLimit and iOffset are negative.
**
** This routine changes the values of iLimit and iOffset only if
** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
** and iOffset should have been preset to appropriate default values (zero)
** prior to calling this routine.
**
** The iOffset register (if it exists) is initialized to the value
** of the OFFSET. The iLimit register is initialized to LIMIT. Register
** iOffset+1 is initialized to LIMIT+OFFSET.
**
** Only if pLimit->pLeft!=0 do the limit registers get
** redefined. The UNION ALL operator uses this property to force
** the reuse of the same limit and offset registers across multiple
** SELECT statements.
*/
static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
Vdbe *v = 0;
int iLimit = 0;
int iOffset;
int n;
Expr *pLimit = p->pLimit;
if( p->iLimit ) return;
/*
** "LIMIT -1" always shows all rows. There is some
** controversy about what the correct behavior should be.
** The current implementation interprets "LIMIT 0" to mean
** no rows.
*/
if( pLimit ){
assert( pLimit->op==TK_LIMIT );
assert( pLimit->pLeft!=0 );
p->iLimit = iLimit = ++pParse->nMem;
v = sqlite3GetVdbe(pParse);
assert( v!=0 );
if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
VdbeComment((v, "LIMIT counter"));
if( n==0 ){
sqlite3VdbeGoto(v, iBreak);
}else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
p->nSelectRow = sqlite3LogEst((u64)n);
p->selFlags |= SF_FixedLimit;
}
}else{
sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
VdbeComment((v, "LIMIT counter"));
sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
}
if( pLimit->pRight ){
p->iOffset = iOffset = ++pParse->nMem;
pParse->nMem++; /* Allocate an extra register for limit+offset */
sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
VdbeComment((v, "OFFSET counter"));
sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
VdbeComment((v, "LIMIT+OFFSET"));
}
}
}
#ifndef SQLITE_OMIT_COMPOUND_SELECT
/*
** Return the appropriate collating sequence for the iCol-th column of
** the result set for the compound-select statement "p". Return NULL if
** the column has no default collating sequence.
**
** The collating sequence for the compound select is taken from the
** left-most term of the select that has a collating sequence.
*/
static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
CollSeq *pRet;
if( p->pPrior ){
pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
}else{
pRet = 0;
}
assert( iCol>=0 );
/* iCol must be less than p->pEList->nExpr. Otherwise an error would
** have been thrown during name resolution and we would not have gotten
** this far */
if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
}
return pRet;
}
/*
** The select statement passed as the second parameter is a compound SELECT
** with an ORDER BY clause. This function allocates and returns a KeyInfo
** structure suitable for implementing the ORDER BY.
**
** Space to hold the KeyInfo structure is obtained from malloc. The calling
** function is responsible for ensuring that this structure is eventually
** freed.
*/
static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
ExprList *pOrderBy = p->pOrderBy;
int nOrderBy = p->pOrderBy->nExpr;
sqlite3 *db = pParse->db;
KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
if( pRet ){
int i;
for(i=0; i<nOrderBy; i++){
struct ExprList_item *pItem = &pOrderBy->a[i];
Expr *pTerm = pItem->pExpr;
CollSeq *pColl;
if( pTerm->flags & EP_Collate ){
pColl = sqlite3ExprCollSeq(pParse, pTerm);
}else{
pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
if( pColl==0 ) pColl = db->pDfltColl;
pOrderBy->a[i].pExpr =
sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
}
assert( sqlite3KeyInfoIsWriteable(pRet) );
pRet->aColl[i] = pColl;
pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags;
}
}
return pRet;
}
#ifndef SQLITE_OMIT_CTE
/*
** This routine generates VDBE code to compute the content of a WITH RECURSIVE
** query of the form:
**
** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
** \___________/ \_______________/
** p->pPrior p
**
**
** There is exactly one reference to the recursive-table in the FROM clause
** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
**
** The setup-query runs once to generate an initial set of rows that go
** into a Queue table. Rows are extracted from the Queue table one by
** one. Each row extracted from Queue is output to pDest. Then the single
** extracted row (now in the iCurrent table) becomes the content of the
** recursive-table for a recursive-query run. The output of the recursive-query
** is added back into the Queue table. Then another row is extracted from Queue
** and the iteration continues until the Queue table is empty.
**
** If the compound query operator is UNION then no duplicate rows are ever
** inserted into the Queue table. The iDistinct table keeps a copy of all rows
** that have ever been inserted into Queue and causes duplicates to be
** discarded. If the operator is UNION ALL, then duplicates are allowed.
**
** If the query has an ORDER BY, then entries in the Queue table are kept in
** ORDER BY order and the first entry is extracted for each cycle. Without
** an ORDER BY, the Queue table is just a FIFO.
**
** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
** have been output to pDest. A LIMIT of zero means to output no rows and a
** negative LIMIT means to output all rows. If there is also an OFFSET clause
** with a positive value, then the first OFFSET outputs are discarded rather
** than being sent to pDest. The LIMIT count does not begin until after OFFSET
** rows have been skipped.
*/
static void generateWithRecursiveQuery(
Parse *pParse, /* Parsing context */
Select *p, /* The recursive SELECT to be coded */
SelectDest *pDest /* What to do with query results */
){
SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
Select *pSetup = p->pPrior; /* The setup query */
int addrTop; /* Top of the loop */
int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
int iCurrent = 0; /* The Current table */
int regCurrent; /* Register holding Current table */
int iQueue; /* The Queue table */
int iDistinct = 0; /* To ensure unique results if UNION */
int eDest = SRT_Fifo; /* How to write to Queue */
SelectDest destQueue; /* SelectDest targetting the Queue table */
int i; /* Loop counter */
int rc; /* Result code */
ExprList *pOrderBy; /* The ORDER BY clause */
Expr *pLimit; /* Saved LIMIT and OFFSET */
int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
#ifndef SQLITE_OMIT_WINDOWFUNC
if( p->pWin ){
sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
return;
}
#endif
/* Obtain authorization to do a recursive query */
if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
/* Process the LIMIT and OFFSET clauses, if they exist */
addrBreak = sqlite3VdbeMakeLabel(pParse);
p->nSelectRow = 320; /* 4 billion rows */
computeLimitRegisters(pParse, p, addrBreak);
pLimit = p->pLimit;
regLimit = p->iLimit;
regOffset = p->iOffset;
p->pLimit = 0;
p->iLimit = p->iOffset = 0;
pOrderBy = p->pOrderBy;
/* Locate the cursor number of the Current table */
for(i=0; ALWAYS(i<pSrc->nSrc); i++){
if( pSrc->a[i].fg.isRecursive ){
iCurrent = pSrc->a[i].iCursor;
break;
}
}
/* Allocate cursors numbers for Queue and Distinct. The cursor number for
** the Distinct table must be exactly one greater than Queue in order
** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
iQueue = pParse->nTab++;
if( p->op==TK_UNION ){
eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
iDistinct = pParse->nTab++;
}else{
eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
}
sqlite3SelectDestInit(&destQueue, eDest, iQueue);
/* Allocate cursors for Current, Queue, and Distinct. */
regCurrent = ++pParse->nMem;
sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
if( pOrderBy ){
KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
(char*)pKeyInfo, P4_KEYINFO);
destQueue.pOrderBy = pOrderBy;
}else{
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
}
VdbeComment((v, "Queue table"));
if( iDistinct ){
p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
p->selFlags |= SF_UsesEphemeral;
}
/* Detach the ORDER BY clause from the compound SELECT */
p->pOrderBy = 0;
/* Store the results of the setup-query in Queue. */
pSetup->pNext = 0;
ExplainQueryPlan((pParse, 1, "SETUP"));
rc = sqlite3Select(pParse, pSetup, &destQueue);
pSetup->pNext = p;
if( rc ) goto end_of_recursive_query;
/* Find the next row in the Queue and output that row */
addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
/* Transfer the next row in Queue over to Current */
sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
if( pOrderBy ){
sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
}else{
sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
}
sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
/* Output the single row in Current */
addrCont = sqlite3VdbeMakeLabel(pParse);
codeOffset(v, regOffset, addrCont);
selectInnerLoop(pParse, p, iCurrent,
0, 0, pDest, addrCont, addrBreak);
if( regLimit ){
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
VdbeCoverage(v);
}
sqlite3VdbeResolveLabel(v, addrCont);
/* Execute the recursive SELECT taking the single row in Current as
** the value for the recursive-table. Store the results in the Queue.
*/
if( p->selFlags & SF_Aggregate ){
sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
}else{
p->pPrior = 0;
ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
sqlite3Select(pParse, p, &destQueue);
assert( p->pPrior==0 );
p->pPrior = pSetup;
}
/* Keep running the loop until the Queue is empty */
sqlite3VdbeGoto(v, addrTop);
sqlite3VdbeResolveLabel(v, addrBreak);
end_of_recursive_query:
sqlite3ExprListDelete(pParse->db, p->pOrderBy);
p->pOrderBy = pOrderBy;
p->pLimit = pLimit;
return;
}
#endif /* SQLITE_OMIT_CTE */
/* Forward references */
static int multiSelectOrderBy(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
);
/*
** Handle the special case of a compound-select that originates from a
** VALUES clause. By handling this as a special case, we avoid deep
** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
** on a VALUES clause.
**
** Because the Select object originates from a VALUES clause:
** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
** (2) All terms are UNION ALL
** (3) There is no ORDER BY clause
**
** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
*/
static int multiSelectValues(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int nRow = 1;
int rc = 0;
int bShowAll = p->pLimit==0;
assert( p->selFlags & SF_MultiValue );
do{
assert( p->selFlags & SF_Values );
assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
if( p->pWin ) return -1;
if( p->pPrior==0 ) break;
assert( p->pPrior->pNext==p );
p = p->pPrior;
nRow += bShowAll;
}while(1);
ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
nRow==1 ? "" : "S"));
while( p ){
selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
if( !bShowAll ) break;
p->nSelectRow = nRow;
p = p->pNext;
}
return rc;
}
/*
** This routine is called to process a compound query form from
** two or more separate queries using UNION, UNION ALL, EXCEPT, or
** INTERSECT
**
** "p" points to the right-most of the two queries. the query on the
** left is p->pPrior. The left query could also be a compound query
** in which case this routine will be called recursively.
**
** The results of the total query are to be written into a destination
** of type eDest with parameter iParm.
**
** Example 1: Consider a three-way compound SQL statement.
**
** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
**
** This statement is parsed up as follows:
**
** SELECT c FROM t3
** |
** `-----> SELECT b FROM t2
** |
** `------> SELECT a FROM t1
**
** The arrows in the diagram above represent the Select.pPrior pointer.
** So if this routine is called with p equal to the t3 query, then
** pPrior will be the t2 query. p->op will be TK_UNION in this case.
**
** Notice that because of the way SQLite parses compound SELECTs, the
** individual selects always group from left to right.
*/
static int multiSelect(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int rc = SQLITE_OK; /* Success code from a subroutine */
Select *pPrior; /* Another SELECT immediately to our left */
Vdbe *v; /* Generate code to this VDBE */
SelectDest dest; /* Alternative data destination */
Select *pDelete = 0; /* Chain of simple selects to delete */
sqlite3 *db; /* Database connection */
/* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
*/
assert( p && p->pPrior ); /* Calling function guarantees this much */
assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
assert( p->selFlags & SF_Compound );
db = pParse->db;
pPrior = p->pPrior;
dest = *pDest;
if( pPrior->pOrderBy || pPrior->pLimit ){
sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
rc = 1;
goto multi_select_end;
}
v = sqlite3GetVdbe(pParse);
assert( v!=0 ); /* The VDBE already created by calling function */
/* Create the destination temporary table if necessary
*/
if( dest.eDest==SRT_EphemTab ){
assert( p->pEList );
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
dest.eDest = SRT_Table;
}
/* Special handling for a compound-select that originates as a VALUES clause.
*/
if( p->selFlags & SF_MultiValue ){
rc = multiSelectValues(pParse, p, &dest);
if( rc>=0 ) goto multi_select_end;
rc = SQLITE_OK;
}
/* Make sure all SELECTs in the statement have the same number of elements
** in their result sets.
*/
assert( p->pEList && pPrior->pEList );
assert( p->pEList->nExpr==pPrior->pEList->nExpr );
#ifndef SQLITE_OMIT_CTE
if( p->selFlags & SF_Recursive ){
generateWithRecursiveQuery(pParse, p, &dest);
}else
#endif
/* Compound SELECTs that have an ORDER BY clause are handled separately.
*/
if( p->pOrderBy ){
return multiSelectOrderBy(pParse, p, pDest);
}else{
#ifndef SQLITE_OMIT_EXPLAIN
if( pPrior->pPrior==0 ){
ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
}
#endif
/* Generate code for the left and right SELECT statements.
*/
switch( p->op ){
case TK_ALL: {
int addr = 0;
int nLimit;
assert( !pPrior->pLimit );
pPrior->iLimit = p->iLimit;
pPrior->iOffset = p->iOffset;
pPrior->pLimit = p->pLimit;
rc = sqlite3Select(pParse, pPrior, &dest);
p->pLimit = 0;
if( rc ){
goto multi_select_end;
}
p->pPrior = 0;
p->iLimit = pPrior->iLimit;
p->iOffset = pPrior->iOffset;
if( p->iLimit ){
addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
VdbeComment((v, "Jump ahead if LIMIT reached"));
if( p->iOffset ){
sqlite3VdbeAddOp3(v, OP_OffsetLimit,
p->iLimit, p->iOffset+1, p->iOffset);
}
}
ExplainQueryPlan((pParse, 1, "UNION ALL"));
rc = sqlite3Select(pParse, p, &dest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
if( pPrior->pLimit
&& sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
&& nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
){
p->nSelectRow = sqlite3LogEst((u64)nLimit);
}
if( addr ){
sqlite3VdbeJumpHere(v, addr);
}
break;
}
case TK_EXCEPT:
case TK_UNION: {
int unionTab; /* Cursor number of the temp table holding result */
u8 op = 0; /* One of the SRT_ operations to apply to self */
int priorOp; /* The SRT_ operation to apply to prior selects */
Expr *pLimit; /* Saved values of p->nLimit */
int addr;
SelectDest uniondest;
testcase( p->op==TK_EXCEPT );
testcase( p->op==TK_UNION );
priorOp = SRT_Union;
if( dest.eDest==priorOp ){
/* We can reuse a temporary table generated by a SELECT to our
** right.
*/
assert( p->pLimit==0 ); /* Not allowed on leftward elements */
unionTab = dest.iSDParm;
}else{
/* We will need to create our own temporary table to hold the
** intermediate results.
*/
unionTab = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
}
/* Code the SELECT statements to our left
*/
assert( !pPrior->pOrderBy );
sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
rc = sqlite3Select(pParse, pPrior, &uniondest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT statement
*/
if( p->op==TK_EXCEPT ){
op = SRT_Except;
}else{
assert( p->op==TK_UNION );
op = SRT_Union;
}
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
uniondest.eDest = op;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &uniondest);
testcase( rc!=SQLITE_OK );
/* Query flattening in sqlite3Select() might refill p->pOrderBy.
** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
sqlite3ExprListDelete(db, p->pOrderBy);
pDelete = p->pPrior;
p->pPrior = pPrior;
p->pOrderBy = 0;
if( p->op==TK_UNION ){
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
p->iLimit = 0;
p->iOffset = 0;
/* Convert the data in the temporary table into whatever form
** it is that we currently need.
*/
assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
if( dest.eDest!=priorOp ){
int iCont, iBreak, iStart;
assert( p->pEList );
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
iStart = sqlite3VdbeCurrentAddr(v);
selectInnerLoop(pParse, p, unionTab,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
}
break;
}
default: assert( p->op==TK_INTERSECT ); {
int tab1, tab2;
int iCont, iBreak, iStart;
Expr *pLimit;
int addr;
SelectDest intersectdest;
int r1;
/* INTERSECT is different from the others since it requires
** two temporary tables. Hence it has its own case. Begin
** by allocating the tables we will need.
*/
tab1 = pParse->nTab++;
tab2 = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
/* Code the SELECTs to our left into temporary table "tab1".
*/
sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
rc = sqlite3Select(pParse, pPrior, &intersectdest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT into temporary table "tab2"
*/
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
assert( p->addrOpenEphm[1] == -1 );
p->addrOpenEphm[1] = addr;
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
intersectdest.iSDParm = tab2;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &intersectdest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
if( p->nSelectRow>pPrior->nSelectRow ){
p->nSelectRow = pPrior->nSelectRow;
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
/* Generate code to take the intersection of the two temporary
** tables.
*/
assert( p->pEList );
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
r1 = sqlite3GetTempReg(pParse);
iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, r1);
selectInnerLoop(pParse, p, tab1,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
break;
}
}
#ifndef SQLITE_OMIT_EXPLAIN
if( p->pNext==0 ){
ExplainQueryPlanPop(pParse);
}
#endif
}
/* Compute collating sequences used by
** temporary tables needed to implement the compound select.
** Attach the KeyInfo structure to all temporary tables.
**
** This section is run by the right-most SELECT statement only.
** SELECT statements to the left always skip this part. The right-most
** SELECT might also skip this part if it has no ORDER BY clause and
** no temp tables are required.
*/
if( p->selFlags & SF_UsesEphemeral ){
int i; /* Loop counter */
KeyInfo *pKeyInfo; /* Collating sequence for the result set */
Select *pLoop; /* For looping through SELECT statements */
CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
int nCol; /* Number of columns in result set */
assert( p->pNext==0 );
nCol = p->pEList->nExpr;
pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
if( !pKeyInfo ){
rc = SQLITE_NOMEM_BKPT;
goto multi_select_end;
}
for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
*apColl = multiSelectCollSeq(pParse, p, i);
if( 0==*apColl ){
*apColl = db->pDfltColl;
}
}
for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
for(i=0; i<2; i++){
int addr = pLoop->addrOpenEphm[i];
if( addr<0 ){
/* If [0] is unused then [1] is also unused. So we can
** always safely abort as soon as the first unused slot is found */
assert( pLoop->addrOpenEphm[1]<0 );
break;
}
sqlite3VdbeChangeP2(v, addr, nCol);
sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
P4_KEYINFO);
pLoop->addrOpenEphm[i] = -1;
}
}
sqlite3KeyInfoUnref(pKeyInfo);
}
multi_select_end:
pDest->iSdst = dest.iSdst;
pDest->nSdst = dest.nSdst;
sqlite3SelectDelete(db, pDelete);
return rc;
}
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
/*
** Error message for when two or more terms of a compound select have different
** size result sets.
*/
void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
if( p->selFlags & SF_Values ){
sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
}else{
sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
" do not have the same number of result columns", selectOpName(p->op));
}
}
/*
** Code an output subroutine for a coroutine implementation of a
** SELECT statment.
**
** The data to be output is contained in pIn->iSdst. There are
** pIn->nSdst columns to be output. pDest is where the output should
** be sent.
**
** regReturn is the number of the register holding the subroutine
** return address.
**
** If regPrev>0 then it is the first register in a vector that
** records the previous output. mem[regPrev] is a flag that is false
** if there has been no previous output. If regPrev>0 then code is
** generated to suppress duplicates. pKeyInfo is used for comparing
** keys.
**
** If the LIMIT found in p->iLimit is reached, jump immediately to
** iBreak.
*/
static int generateOutputSubroutine(
Parse *pParse, /* Parsing context */
Select *p, /* The SELECT statement */
SelectDest *pIn, /* Coroutine supplying data */
SelectDest *pDest, /* Where to send the data */
int regReturn, /* The return address register */
int regPrev, /* Previous result register. No uniqueness if 0 */
KeyInfo *pKeyInfo, /* For comparing with previous entry */
int iBreak /* Jump here if we hit the LIMIT */
){
Vdbe *v = pParse->pVdbe;
int iContinue;
int addr;
addr = sqlite3VdbeCurrentAddr(v);
iContinue = sqlite3VdbeMakeLabel(pParse);
/* Suppress duplicates for UNION, EXCEPT, and INTERSECT
*/
if( regPrev ){
int addr1, addr2;
addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
(char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addr1);
sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
}
if( pParse->db->mallocFailed ) return 0;
/* Suppress the first OFFSET entries if there is an OFFSET clause
*/
codeOffset(v, p->iOffset, iContinue);
assert( pDest->eDest!=SRT_Exists );
assert( pDest->eDest!=SRT_Table );
switch( pDest->eDest ){
/* Store the result as data using a unique key.
*/
case SRT_EphemTab: {
int r1 = sqlite3GetTempReg(pParse);
int r2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
sqlite3ReleaseTempReg(pParse, r2);
sqlite3ReleaseTempReg(pParse, r1);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
/* If we are creating a set for an "expr IN (SELECT ...)".
*/
case SRT_Set: {
int r1;
testcase( pIn->nSdst>1 );
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
r1, pDest->zAffSdst, pIn->nSdst);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
pIn->iSdst, pIn->nSdst);
sqlite3ReleaseTempReg(pParse, r1);
break;
}
/* If this is a scalar select that is part of an expression, then
** store the results in the appropriate memory cell and break out
** of the scan loop. Note that the select might return multiple columns
** if it is the RHS of a row-value IN operator.
*/
case SRT_Mem: {
if( pParse->nErr==0 ){
testcase( pIn->nSdst>1 );
sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
}
/* The LIMIT clause will jump out of the loop for us */
break;
}
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
/* The results are stored in a sequence of registers
** starting at pDest->iSdst. Then the co-routine yields.
*/
case SRT_Coroutine: {
if( pDest->iSdst==0 ){
pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
pDest->nSdst = pIn->nSdst;
}
sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
break;
}
/* If none of the above, then the result destination must be
** SRT_Output. This routine is never called with any other
** destination other than the ones handled above or SRT_Output.
**
** For SRT_Output, results are stored in a sequence of registers.
** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
** return the next row of result.
*/
default: {
assert( pDest->eDest==SRT_Output );
sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
break;
}
}
/* Jump to the end of the loop if the LIMIT is reached.
*/
if( p->iLimit ){
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
}
/* Generate the subroutine return
*/
sqlite3VdbeResolveLabel(v, iContinue);
sqlite3VdbeAddOp1(v, OP_Return, regReturn);
return addr;
}
/*
** Alternative compound select code generator for cases when there
** is an ORDER BY clause.
**
** We assume a query of the following form:
**
** <selectA> <operator> <selectB> ORDER BY <orderbylist>
**
** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
** is to code both <selectA> and <selectB> with the ORDER BY clause as
** co-routines. Then run the co-routines in parallel and merge the results
** into the output. In addition to the two coroutines (called selectA and
** selectB) there are 7 subroutines:
**
** outA: Move the output of the selectA coroutine into the output
** of the compound query.
**
** outB: Move the output of the selectB coroutine into the output
** of the compound query. (Only generated for UNION and
** UNION ALL. EXCEPT and INSERTSECT never output a row that
** appears only in B.)
**
** AltB: Called when there is data from both coroutines and A<B.
**
** AeqB: Called when there is data from both coroutines and A==B.
**
** AgtB: Called when there is data from both coroutines and A>B.
**
** EofA: Called when data is exhausted from selectA.
**
** EofB: Called when data is exhausted from selectB.
**
** The implementation of the latter five subroutines depend on which
** <operator> is used:
**
**
** UNION ALL UNION EXCEPT INTERSECT
** ------------- ----------------- -------------- -----------------
** AltB: outA, nextA outA, nextA outA, nextA nextA
**
** AeqB: outA, nextA nextA nextA outA, nextA
**
** AgtB: outB, nextB outB, nextB nextB nextB
**
** EofA: outB, nextB outB, nextB halt halt
**
** EofB: outA, nextA outA, nextA outA, nextA halt
**
** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
** causes an immediate jump to EofA and an EOF on B following nextB causes
** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
** following nextX causes a jump to the end of the select processing.
**
** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
** within the output subroutine. The regPrev register set holds the previously
** output value. A comparison is made against this value and the output
** is skipped if the next results would be the same as the previous.
**
** The implementation plan is to implement the two coroutines and seven
** subroutines first, then put the control logic at the bottom. Like this:
**
** goto Init
** coA: coroutine for left query (A)
** coB: coroutine for right query (B)
** outA: output one row of A
** outB: output one row of B (UNION and UNION ALL only)
** EofA: ...
** EofB: ...
** AltB: ...
** AeqB: ...
** AgtB: ...
** Init: initialize coroutine registers
** yield coA
** if eof(A) goto EofA
** yield coB
** if eof(B) goto EofB
** Cmpr: Compare A, B
** Jump AltB, AeqB, AgtB
** End: ...
**
** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
** actually called using Gosub and they do not Return. EofA and EofB loop
** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
** and AgtB jump to either L2 or to one of EofA or EofB.
*/
#ifndef SQLITE_OMIT_COMPOUND_SELECT
static int multiSelectOrderBy(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int i, j; /* Loop counters */
Select *pPrior; /* Another SELECT immediately to our left */
Vdbe *v; /* Generate code to this VDBE */
SelectDest destA; /* Destination for coroutine A */
SelectDest destB; /* Destination for coroutine B */
int regAddrA; /* Address register for select-A coroutine */
int regAddrB; /* Address register for select-B coroutine */
int addrSelectA; /* Address of the select-A coroutine */
int addrSelectB; /* Address of the select-B coroutine */
int regOutA; /* Address register for the output-A subroutine */
int regOutB; /* Address register for the output-B subroutine */
int addrOutA; /* Address of the output-A subroutine */
int addrOutB = 0; /* Address of the output-B subroutine */
int addrEofA; /* Address of the select-A-exhausted subroutine */
int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
int addrEofB; /* Address of the select-B-exhausted subroutine */
int addrAltB; /* Address of the A<B subroutine */
int addrAeqB; /* Address of the A==B subroutine */
int addrAgtB; /* Address of the A>B subroutine */
int regLimitA; /* Limit register for select-A */
int regLimitB; /* Limit register for select-A */
int regPrev; /* A range of registers to hold previous output */
int savedLimit; /* Saved value of p->iLimit */
int savedOffset; /* Saved value of p->iOffset */
int labelCmpr; /* Label for the start of the merge algorithm */
int labelEnd; /* Label for the end of the overall SELECT stmt */
int addr1; /* Jump instructions that get retargetted */
int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
KeyInfo *pKeyMerge; /* Comparison information for merging rows */
sqlite3 *db; /* Database connection */
ExprList *pOrderBy; /* The ORDER BY clause */
int nOrderBy; /* Number of terms in the ORDER BY clause */
int *aPermute; /* Mapping from ORDER BY terms to result set columns */
assert( p->pOrderBy!=0 );
assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
db = pParse->db;
v = pParse->pVdbe;
assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
labelEnd = sqlite3VdbeMakeLabel(pParse);
labelCmpr = sqlite3VdbeMakeLabel(pParse);
/* Patch up the ORDER BY clause
*/
op = p->op;
pPrior = p->pPrior;
assert( pPrior->pOrderBy==0 );
pOrderBy = p->pOrderBy;
assert( pOrderBy );
nOrderBy = pOrderBy->nExpr;
/* For operators other than UNION ALL we have to make sure that
** the ORDER BY clause covers every term of the result set. Add
** terms to the ORDER BY clause as necessary.
*/
if( op!=TK_ALL ){
for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
struct ExprList_item *pItem;
for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
assert( pItem->u.x.iOrderByCol>0 );
if( pItem->u.x.iOrderByCol==i ) break;
}
if( j==nOrderBy ){
Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
if( pNew==0 ) return SQLITE_NOMEM_BKPT;
pNew->flags |= EP_IntValue;
pNew->u.iValue = i;
p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
}
}
}
/* Compute the comparison permutation and keyinfo that is used with
** the permutation used to determine if the next
** row of results comes from selectA or selectB. Also add explicit
** collations to the ORDER BY clause terms so that when the subqueries
** to the right and the left are evaluated, they use the correct
** collation.
*/
aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
if( aPermute ){
struct ExprList_item *pItem;
aPermute[0] = nOrderBy;
for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
assert( pItem->u.x.iOrderByCol>0 );
assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
aPermute[i] = pItem->u.x.iOrderByCol - 1;
}
pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
}else{
pKeyMerge = 0;
}
/* Reattach the ORDER BY clause to the query.
*/
p->pOrderBy = pOrderBy;
pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
/* Allocate a range of temporary registers and the KeyInfo needed
** for the logic that removes duplicate result rows when the
** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
*/
if( op==TK_ALL ){
regPrev = 0;
}else{
int nExpr = p->pEList->nExpr;
assert( nOrderBy>=nExpr || db->mallocFailed );
regPrev = pParse->nMem+1;
pParse->nMem += nExpr+1;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
if( pKeyDup ){
assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
for(i=0; i<nExpr; i++){
pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
pKeyDup->aSortFlags[i] = 0;
}
}
}
/* Separate the left and the right query from one another
*/
p->pPrior = 0;
pPrior->pNext = 0;
sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
if( pPrior->pPrior==0 ){
sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
}
/* Compute the limit registers */
computeLimitRegisters(pParse, p, labelEnd);
if( p->iLimit && op==TK_ALL ){
regLimitA = ++pParse->nMem;
regLimitB = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
regLimitA);
sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
}else{
regLimitA = regLimitB = 0;
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = 0;
regAddrA = ++pParse->nMem;
regAddrB = ++pParse->nMem;
regOutA = ++pParse->nMem;
regOutB = ++pParse->nMem;
sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
/* Generate a coroutine to evaluate the SELECT statement to the
** left of the compound operator - the "A" select.
*/
addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
VdbeComment((v, "left SELECT"));
pPrior->iLimit = regLimitA;
ExplainQueryPlan((pParse, 1, "LEFT"));
sqlite3Select(pParse, pPrior, &destA);
sqlite3VdbeEndCoroutine(v, regAddrA);
sqlite3VdbeJumpHere(v, addr1);
/* Generate a coroutine to evaluate the SELECT statement on
** the right - the "B" select
*/
addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
VdbeComment((v, "right SELECT"));
savedLimit = p->iLimit;
savedOffset = p->iOffset;
p->iLimit = regLimitB;
p->iOffset = 0;
ExplainQueryPlan((pParse, 1, "RIGHT"));
sqlite3Select(pParse, p, &destB);
p->iLimit = savedLimit;
p->iOffset = savedOffset;
sqlite3VdbeEndCoroutine(v, regAddrB);
/* Generate a subroutine that outputs the current row of the A
** select as the next output row of the compound select.
*/
VdbeNoopComment((v, "Output routine for A"));
addrOutA = generateOutputSubroutine(pParse,
p, &destA, pDest, regOutA,
regPrev, pKeyDup, labelEnd);
/* Generate a subroutine that outputs the current row of the B
** select as the next output row of the compound select.
*/
if( op==TK_ALL || op==TK_UNION ){
VdbeNoopComment((v, "Output routine for B"));
addrOutB = generateOutputSubroutine(pParse,
p, &destB, pDest, regOutB,
regPrev, pKeyDup, labelEnd);
}
sqlite3KeyInfoUnref(pKeyDup);
/* Generate a subroutine to run when the results from select A
** are exhausted and only data in select B remains.
*/
if( op==TK_EXCEPT || op==TK_INTERSECT ){
addrEofA_noB = addrEofA = labelEnd;
}else{
VdbeNoopComment((v, "eof-A subroutine"));
addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
VdbeCoverage(v);
sqlite3VdbeGoto(v, addrEofA);
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
}
/* Generate a subroutine to run when the results from select B
** are exhausted and only data in select A remains.
*/
if( op==TK_INTERSECT ){
addrEofB = addrEofA;
if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
}else{
VdbeNoopComment((v, "eof-B subroutine"));
addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
sqlite3VdbeGoto(v, addrEofB);
}
/* Generate code to handle the case of A<B
*/
VdbeNoopComment((v, "A-lt-B subroutine"));
addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
sqlite3VdbeGoto(v, labelCmpr);
/* Generate code to handle the case of A==B
*/
if( op==TK_ALL ){
addrAeqB = addrAltB;
}else if( op==TK_INTERSECT ){
addrAeqB = addrAltB;
addrAltB++;
}else{
VdbeNoopComment((v, "A-eq-B subroutine"));
addrAeqB =
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
sqlite3VdbeGoto(v, labelCmpr);
}
/* Generate code to handle the case of A>B
*/
VdbeNoopComment((v, "A-gt-B subroutine"));
addrAgtB = sqlite3VdbeCurrentAddr(v);
if( op==TK_ALL || op==TK_UNION ){
sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
}
sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
sqlite3VdbeGoto(v, labelCmpr);
/* This code runs once to initialize everything.
*/
sqlite3VdbeJumpHere(v, addr1);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
/* Implement the main merge loop
*/
sqlite3VdbeResolveLabel(v, labelCmpr);
sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
(char*)pKeyMerge, P4_KEYINFO);
sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
/* Jump to the this point in order to terminate the query.
*/
sqlite3VdbeResolveLabel(v, labelEnd);
/* Reassembly the compound query so that it will be freed correctly
** by the calling function */
if( p->pPrior ){
sqlite3SelectDelete(db, p->pPrior);
}
p->pPrior = pPrior;
pPrior->pNext = p;
/*** TBD: Insert subroutine calls to close cursors on incomplete
**** subqueries ****/
ExplainQueryPlanPop(pParse);
return pParse->nErr!=0;
}
#endif
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/* An instance of the SubstContext object describes an substitution edit
** to be performed on a parse tree.
**
** All references to columns in table iTable are to be replaced by corresponding
** expressions in pEList.
*/
typedef struct SubstContext {
Parse *pParse; /* The parsing context */
int iTable; /* Replace references to this table */
int iNewTable; /* New table number */
int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
ExprList *pEList; /* Replacement expressions */
} SubstContext;
/* Forward Declarations */
static void substExprList(SubstContext*, ExprList*);
static void substSelect(SubstContext*, Select*, int);
/*
** Scan through the expression pExpr. Replace every reference to
** a column in table number iTable with a copy of the iColumn-th
** entry in pEList. (But leave references to the ROWID column
** unchanged.)
**
** This routine is part of the flattening procedure. A subquery
** whose result set is defined by pEList appears as entry in the
** FROM clause of a SELECT such that the VDBE cursor assigned to that
** FORM clause entry is iTable. This routine makes the necessary
** changes to pExpr so that it refers directly to the source table
** of the subquery rather the result set of the subquery.
*/
static Expr *substExpr(
SubstContext *pSubst, /* Description of the substitution */
Expr *pExpr /* Expr in which substitution occurs */
){
if( pExpr==0 ) return 0;
if( ExprHasProperty(pExpr, EP_FromJoin)
&& pExpr->iRightJoinTable==pSubst->iTable
){
pExpr->iRightJoinTable = pSubst->iNewTable;
}
if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
if( pExpr->iColumn<0 ){
pExpr->op = TK_NULL;
}else{
Expr *pNew;
Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
Expr ifNullRow;
assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
assert( pExpr->pRight==0 );
if( sqlite3ExprIsVector(pCopy) ){
sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
}else{
sqlite3 *db = pSubst->pParse->db;
if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
memset(&ifNullRow, 0, sizeof(ifNullRow));
ifNullRow.op = TK_IF_NULL_ROW;
ifNullRow.pLeft = pCopy;
ifNullRow.iTable = pSubst->iNewTable;
pCopy = &ifNullRow;
}
testcase( ExprHasProperty(pCopy, EP_Subquery) );
pNew = sqlite3ExprDup(db, pCopy, 0);
if( pNew && pSubst->isLeftJoin ){
ExprSetProperty(pNew, EP_CanBeNull);
}
if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
pNew->iRightJoinTable = pExpr->iRightJoinTable;
ExprSetProperty(pNew, EP_FromJoin);
}
sqlite3ExprDelete(db, pExpr);
pExpr = pNew;
/* Ensure that the expression now has an implicit collation sequence,
** just as it did when it was a column of a view or sub-query. */
if( pExpr ){
if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){
CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
(pColl ? pColl->zName : "BINARY")
);
}
ExprClearProperty(pExpr, EP_Collate);
}
}
}
}else{
if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
pExpr->iTable = pSubst->iNewTable;
}
pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
pExpr->pRight = substExpr(pSubst, pExpr->pRight);
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
substSelect(pSubst, pExpr->x.pSelect, 1);
}else{
substExprList(pSubst, pExpr->x.pList);
}
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(pExpr, EP_WinFunc) ){
Window *pWin = pExpr->y.pWin;
pWin->pFilter = substExpr(pSubst, pWin->pFilter);
substExprList(pSubst, pWin->pPartition);
substExprList(pSubst, pWin->pOrderBy);
}
#endif
}
return pExpr;
}
static void substExprList(
SubstContext *pSubst, /* Description of the substitution */
ExprList *pList /* List to scan and in which to make substitutes */
){
int i;
if( pList==0 ) return;
for(i=0; i<pList->nExpr; i++){
pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
}
}
static void substSelect(
SubstContext *pSubst, /* Description of the substitution */
Select *p, /* SELECT statement in which to make substitutions */
int doPrior /* Do substitutes on p->pPrior too */
){
SrcList *pSrc;
struct SrcList_item *pItem;
int i;
if( !p ) return;
do{
substExprList(pSubst, p->pEList);
substExprList(pSubst, p->pGroupBy);
substExprList(pSubst, p->pOrderBy);
p->pHaving = substExpr(pSubst, p->pHaving);
p->pWhere = substExpr(pSubst, p->pWhere);
pSrc = p->pSrc;
assert( pSrc!=0 );
for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
substSelect(pSubst, pItem->pSelect, 1);
if( pItem->fg.isTabFunc ){
substExprList(pSubst, pItem->u1.pFuncArg);
}
}
}while( doPrior && (p = p->pPrior)!=0 );
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/*
** This routine attempts to flatten subqueries as a performance optimization.
** This routine returns 1 if it makes changes and 0 if no flattening occurs.
**
** To understand the concept of flattening, consider the following
** query:
**
** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
**
** The default way of implementing this query is to execute the
** subquery first and store the results in a temporary table, then
** run the outer query on that temporary table. This requires two
** passes over the data. Furthermore, because the temporary table
** has no indices, the WHERE clause on the outer query cannot be
** optimized.
**
** This routine attempts to rewrite queries such as the above into
** a single flat select, like this:
**
** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
**
** The code generated for this simplification gives the same result
** but only has to scan the data once. And because indices might
** exist on the table t1, a complete scan of the data might be
** avoided.
**
** Flattening is subject to the following constraints:
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** The subquery and the outer query cannot both be aggregates.
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** (2) If the subquery is an aggregate then
** (2a) the outer query must not be a join and
** (2b) the outer query must not use subqueries
** other than the one FROM-clause subquery that is a candidate
** for flattening. (This is due to ticket [2f7170d73bf9abf80]
** from 2015-02-09.)
**
** (3) If the subquery is the right operand of a LEFT JOIN then
** (3a) the subquery may not be a join and
** (3b) the FROM clause of the subquery may not contain a virtual
** table and
** (3c) the outer query may not be an aggregate.
** (3d) the outer query may not be DISTINCT.
**
** (4) The subquery can not be DISTINCT.
**
** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
** sub-queries that were excluded from this optimization. Restriction
** (4) has since been expanded to exclude all DISTINCT subqueries.
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** If the subquery is aggregate, the outer query may not be DISTINCT.
**
** (7) The subquery must have a FROM clause. TODO: For subqueries without
** A FROM clause, consider adding a FROM clause with the special
** table sqlite_once that consists of a single row containing a
** single NULL.
**
** (8) If the subquery uses LIMIT then the outer query may not be a join.
**
** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
**
** (**) Restriction (10) was removed from the code on 2005-02-05 but we
** accidently carried the comment forward until 2014-09-15. Original
** constraint: "If the subquery is aggregate then the outer query
** may not use LIMIT."
**
** (11) The subquery and the outer query may not both have ORDER BY clauses.
**
** (**) Not implemented. Subsumed into restriction (3). Was previously
** a separate restriction deriving from ticket #350.
**
** (13) The subquery and outer query may not both use LIMIT.
**
** (14) The subquery may not use OFFSET.
**
** (15) If the outer query is part of a compound select, then the
** subquery may not use LIMIT.
** (See ticket #2339 and ticket [02a8e81d44]).
**
** (16) If the outer query is aggregate, then the subquery may not
** use ORDER BY. (Ticket #2942) This used to not matter
** until we introduced the group_concat() function.
**
** (17) If the subquery is a compound select, then
** (17a) all compound operators must be a UNION ALL, and
** (17b) no terms within the subquery compound may be aggregate
** or DISTINCT, and
** (17c) every term within the subquery compound must have a FROM clause
** (17d) the outer query may not be
** (17d1) aggregate, or
** (17d2) DISTINCT, or
** (17d3) a join.
**
** The parent and sub-query may contain WHERE clauses. Subject to
** rules (11), (13) and (14), they may also contain ORDER BY,
** LIMIT and OFFSET clauses. The subquery cannot use any compound
** operator other than UNION ALL because all the other compound
** operators have an implied DISTINCT which is disallowed by
** restriction (4).
**
** Also, each component of the sub-query must return the same number
** of result columns. This is actually a requirement for any compound
** SELECT statement, but all the code here does is make sure that no
** such (illegal) sub-query is flattened. The caller will detect the
** syntax error and return a detailed message.
**
** (18) If the sub-query is a compound select, then all terms of the
** ORDER BY clause of the parent must be simple references to
** columns of the sub-query.
**
** (19) If the subquery uses LIMIT then the outer query may not
** have a WHERE clause.
**
** (20) If the sub-query is a compound select, then it must not use
** an ORDER BY clause. Ticket #3773. We could relax this constraint
** somewhat by saying that the terms of the ORDER BY clause must
** appear as unmodified result columns in the outer query. But we
** have other optimizations in mind to deal with that case.
**
** (21) If the subquery uses LIMIT then the outer query may not be
** DISTINCT. (See ticket [752e1646fc]).
**
** (22) The subquery may not be a recursive CTE.
**
** (**) Subsumed into restriction (17d3). Was: If the outer query is
** a recursive CTE, then the sub-query may not be a compound query.
** This restriction is because transforming the
** parent to a compound query confuses the code that handles
** recursive queries in multiSelect().
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** The subquery may not be an aggregate that uses the built-in min() or
** or max() functions. (Without this restriction, a query like:
** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
** return the value X for which Y was maximal.)
**
** (25) If either the subquery or the parent query contains a window
** function in the select list or ORDER BY clause, flattening
** is not attempted.
**
**
** In this routine, the "p" parameter is a pointer to the outer query.
** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
** uses aggregates.
**
** If flattening is not attempted, this routine is a no-op and returns 0.
** If flattening is attempted this routine returns 1.
**
** All of the expression analysis must occur on both the outer query and
** the subquery before this routine runs.
*/
static int flattenSubquery(
Parse *pParse, /* Parsing context */
Select *p, /* The parent or outer SELECT statement */
int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
int isAgg /* True if outer SELECT uses aggregate functions */
){
const char *zSavedAuthContext = pParse->zAuthContext;
Select *pParent; /* Current UNION ALL term of the other query */
Select *pSub; /* The inner query or "subquery" */
Select *pSub1; /* Pointer to the rightmost select in sub-query */
SrcList *pSrc; /* The FROM clause of the outer query */
SrcList *pSubSrc; /* The FROM clause of the subquery */
int iParent; /* VDBE cursor number of the pSub result set temp table */
int iNewParent = -1;/* Replacement table for iParent */
int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
int i; /* Loop counter */
Expr *pWhere; /* The WHERE clause */
struct SrcList_item *pSubitem; /* The subquery */
sqlite3 *db = pParse->db;
/* Check to see if flattening is permitted. Return 0 if not.
*/
assert( p!=0 );
assert( p->pPrior==0 );
if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
pSrc = p->pSrc;
assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
pSubitem = &pSrc->a[iFrom];
iParent = pSubitem->iCursor;
pSub = pSubitem->pSelect;
assert( pSub!=0 );
#ifndef SQLITE_OMIT_WINDOWFUNC
if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
#endif
pSubSrc = pSub->pSrc;
assert( pSubSrc );
/* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
** because they could be computed at compile-time. But when LIMIT and OFFSET
** became arbitrary expressions, we were forced to add restrictions (13)
** and (14). */
if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
return 0; /* Restriction (15) */
}
if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
return 0; /* Restrictions (8)(9) */
}
if( p->pOrderBy && pSub->pOrderBy ){
return 0; /* Restriction (11) */
}
if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
return 0; /* Restriction (21) */
}
if( pSub->selFlags & (SF_Recursive) ){
return 0; /* Restrictions (22) */
}
/*
** If the subquery is the right operand of a LEFT JOIN, then the
** subquery may not be a join itself (3a). Example of why this is not
** allowed:
**
** t1 LEFT OUTER JOIN (t2 JOIN t3)
**
** If we flatten the above, we would get
**
** (t1 LEFT OUTER JOIN t2) JOIN t3
**
** which is not at all the same thing.
**
** If the subquery is the right operand of a LEFT JOIN, then the outer
** query cannot be an aggregate. (3c) This is an artifact of the way
** aggregates are processed - there is no mechanism to determine if
** the LEFT JOIN table should be all-NULL.
**
** See also tickets #306, #350, and #3300.
*/
if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
isLeftJoin = 1;
if( pSubSrc->nSrc>1 /* (3a) */
|| isAgg /* (3b) */
|| IsVirtual(pSubSrc->a[0].pTab) /* (3c) */
|| (p->selFlags & SF_Distinct)!=0 /* (3d) */
){
return 0;
}
}
#ifdef SQLITE_EXTRA_IFNULLROW
else if( iFrom>0 && !isAgg ){
/* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
** every reference to any result column from subquery in a join, even
** though they are not necessary. This will stress-test the OP_IfNullRow
** opcode. */
isLeftJoin = -1;
}
#endif
/* Restriction (17): If the sub-query is a compound SELECT, then it must
** use only the UNION ALL operator. And none of the simple select queries
** that make up the compound SELECT are allowed to be aggregate or distinct
** queries.
*/
if( pSub->pPrior ){
if( pSub->pOrderBy ){
return 0; /* Restriction (20) */
}
if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
return 0; /* (17d1), (17d2), or (17d3) */
}
for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
assert( pSub->pSrc!=0 );
assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
|| (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
|| pSub1->pSrc->nSrc<1 /* (17c) */
){
return 0;
}
testcase( pSub1->pSrc->nSrc>1 );
}
/* Restriction (18). */
if( p->pOrderBy ){
int ii;
for(ii=0; ii<p->pOrderBy->nExpr; ii++){
if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
}
}
}
/* Ex-restriction (23):
** The only way that the recursive part of a CTE can contain a compound
** subquery is for the subquery to be one term of a join. But if the
** subquery is a join, then the flattening has already been stopped by
** restriction (17d3)
*/
assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
/***** If we reach this point, flattening is permitted. *****/
SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
pSub->selId, pSub, iFrom));
/* Authorize the subquery */
pParse->zAuthContext = pSubitem->zName;
TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
testcase( i==SQLITE_DENY );
pParse->zAuthContext = zSavedAuthContext;
/* If the sub-query is a compound SELECT statement, then (by restrictions
** 17 and 18 above) it must be a UNION ALL and the parent query must
** be of the form:
**
** SELECT <expr-list> FROM (<sub-query>) <where-clause>
**
** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
** OFFSET clauses and joins them to the left-hand-side of the original
** using UNION ALL operators. In this case N is the number of simple
** select statements in the compound sub-query.
**
** Example:
**
** SELECT a+1 FROM (
** SELECT x FROM tab
** UNION ALL
** SELECT y FROM tab
** UNION ALL
** SELECT abs(z*2) FROM tab2
** ) WHERE a!=5 ORDER BY 1
**
** Transformed into:
**
** SELECT x+1 FROM tab WHERE x+1!=5
** UNION ALL
** SELECT y+1 FROM tab WHERE y+1!=5
** UNION ALL
** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
** ORDER BY 1
**
** We call this the "compound-subquery flattening".
*/
for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
Select *pNew;
ExprList *pOrderBy = p->pOrderBy;
Expr *pLimit = p->pLimit;
Select *pPrior = p->pPrior;
p->pOrderBy = 0;
p->pSrc = 0;
p->pPrior = 0;
p->pLimit = 0;
pNew = sqlite3SelectDup(db, p, 0);
p->pLimit = pLimit;
p->pOrderBy = pOrderBy;
p->pSrc = pSrc;
p->op = TK_ALL;
if( pNew==0 ){
p->pPrior = pPrior;
}else{
pNew->pPrior = pPrior;
if( pPrior ) pPrior->pNext = pNew;
pNew->pNext = p;
p->pPrior = pNew;
SELECTTRACE(2,pParse,p,("compound-subquery flattener"
" creates %u as peer\n",pNew->selId));
}
if( db->mallocFailed ) return 1;
}
/* Begin flattening the iFrom-th entry of the FROM clause
** in the outer query.
*/
pSub = pSub1 = pSubitem->pSelect;
/* Delete the transient table structure associated with the
** subquery
*/
sqlite3DbFree(db, pSubitem->zDatabase);
sqlite3DbFree(db, pSubitem->zName);
sqlite3DbFree(db, pSubitem->zAlias);
pSubitem->zDatabase = 0;
pSubitem->zName = 0;
pSubitem->zAlias = 0;
pSubitem->pSelect = 0;
/* Defer deleting the Table object associated with the
** subquery until code generation is
** complete, since there may still exist Expr.pTab entries that
** refer to the subquery even after flattening. Ticket #3346.
**
** pSubitem->pTab is always non-NULL by test restrictions and tests above.
*/
if( ALWAYS(pSubitem->pTab!=0) ){
Table *pTabToDel = pSubitem->pTab;
if( pTabToDel->nTabRef==1 ){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
pTabToDel->pNextZombie = pToplevel->pZombieTab;
pToplevel->pZombieTab = pTabToDel;
}else{
pTabToDel->nTabRef--;
}
pSubitem->pTab = 0;
}
/* The following loop runs once for each term in a compound-subquery
** flattening (as described above). If we are doing a different kind
** of flattening - a flattening other than a compound-subquery flattening -
** then this loop only runs once.
**
** This loop moves all of the FROM elements of the subquery into the
** the FROM clause of the outer query. Before doing this, remember
** the cursor number for the original outer query FROM element in
** iParent. The iParent cursor will never be used. Subsequent code
** will scan expressions looking for iParent references and replace
** those references with expressions that resolve to the subquery FROM
** elements we are now copying in.
*/
for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
int nSubSrc;
u8 jointype = 0;
assert( pSub!=0 );
pSubSrc = pSub->pSrc; /* FROM clause of subquery */
nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
pSrc = pParent->pSrc; /* FROM clause of the outer query */
if( pSrc ){
assert( pParent==p ); /* First time through the loop */
jointype = pSubitem->fg.jointype;
}else{
assert( pParent!=p ); /* 2nd and subsequent times through the loop */
pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* The subquery uses a single slot of the FROM clause of the outer
** query. If the subquery has more than one element in its FROM clause,
** then expand the outer query to make space for it to hold all elements
** of the subquery.
**
** Example:
**
** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
**
** The outer query has 3 slots in its FROM clause. One slot of the
** outer query (the middle slot) is used by the subquery. The next
** block of code will expand the outer query FROM clause to 4 slots.
** The middle slot is expanded to two slots in order to make space
** for the two elements in the FROM clause of the subquery.
*/
if( nSubSrc>1 ){
pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* Transfer the FROM clause terms from the subquery into the
** outer query.
*/
for(i=0; i<nSubSrc; i++){
sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
pSrc->a[i+iFrom] = pSubSrc->a[i];
iNewParent = pSubSrc->a[i].iCursor;
memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
}
pSrc->a[iFrom].fg.jointype = jointype;
/* Now begin substituting subquery result set expressions for
** references to the iParent in the outer query.
**
** Example:
**
** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
** \ \_____________ subquery __________/ /
** \_____________________ outer query ______________________________/
**
** We look at every expression in the outer query and every place we see
** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
*/
if( pSub->pOrderBy ){
/* At this point, any non-zero iOrderByCol values indicate that the
** ORDER BY column expression is identical to the iOrderByCol'th
** expression returned by SELECT statement pSub. Since these values
** do not necessarily correspond to columns in SELECT statement pParent,
** zero them before transfering the ORDER BY clause.
**
** Not doing this may cause an error if a subsequent call to this
** function attempts to flatten a compound sub-query into pParent
** (the only way this can happen is if the compound sub-query is
** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
ExprList *pOrderBy = pSub->pOrderBy;
for(i=0; i<pOrderBy->nExpr; i++){
pOrderBy->a[i].u.x.iOrderByCol = 0;
}
assert( pParent->pOrderBy==0 );
pParent->pOrderBy = pOrderBy;
pSub->pOrderBy = 0;
}
pWhere = pSub->pWhere;
pSub->pWhere = 0;
if( isLeftJoin>0 ){
sqlite3SetJoinExpr(pWhere, iNewParent);
}
pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere);
if( db->mallocFailed==0 ){
SubstContext x;
x.pParse = pParse;
x.iTable = iParent;
x.iNewTable = iNewParent;
x.isLeftJoin = isLeftJoin;
x.pEList = pSub->pEList;
substSelect(&x, pParent, 0);
}
/* The flattened query is a compound if either the inner or the
** outer query is a compound. */
pParent->selFlags |= pSub->selFlags & SF_Compound;
assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
/*
** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
**
** One is tempted to try to add a and b to combine the limits. But this
** does not work if either limit is negative.
*/
if( pSub->pLimit ){
pParent->pLimit = pSub->pLimit;
pSub->pLimit = 0;
}
}
/* Finially, delete what is left of the subquery and return
** success.
*/
sqlite3SelectDelete(db, pSub1);
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
return 1;
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
/*
** A structure to keep track of all of the column values that are fixed to
** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
*/
typedef struct WhereConst WhereConst;
struct WhereConst {
Parse *pParse; /* Parsing context */
int nConst; /* Number for COLUMN=CONSTANT terms */
int nChng; /* Number of times a constant is propagated */
Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
};
/*
** Add a new entry to the pConst object. Except, do not add duplicate
** pColumn entires.
*/
static void constInsert(
WhereConst *pConst, /* The WhereConst into which we are inserting */
Expr *pColumn, /* The COLUMN part of the constraint */
Expr *pValue /* The VALUE part of the constraint */
){
int i;
assert( pColumn->op==TK_COLUMN );
/* 2018-10-25 ticket [cf5ed20f]
** Make sure the same pColumn is not inserted more than once */
for(i=0; i<pConst->nConst; i++){
const Expr *pExpr = pConst->apExpr[i*2];
assert( pExpr->op==TK_COLUMN );
if( pExpr->iTable==pColumn->iTable
&& pExpr->iColumn==pColumn->iColumn
){
return; /* Already present. Return without doing anything. */
}
}
pConst->nConst++;
pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
pConst->nConst*2*sizeof(Expr*));
if( pConst->apExpr==0 ){
pConst->nConst = 0;
}else{
if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft;
pConst->apExpr[pConst->nConst*2-2] = pColumn;
pConst->apExpr[pConst->nConst*2-1] = pValue;
}
}
/*
** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
** is a constant expression and where the term must be true because it
** is part of the AND-connected terms of the expression. For each term
** found, add it to the pConst structure.
*/
static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
Expr *pRight, *pLeft;
if( pExpr==0 ) return;
if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
if( pExpr->op==TK_AND ){
findConstInWhere(pConst, pExpr->pRight);
findConstInWhere(pConst, pExpr->pLeft);
return;
}
if( pExpr->op!=TK_EQ ) return;
pRight = pExpr->pRight;
pLeft = pExpr->pLeft;
assert( pRight!=0 );
assert( pLeft!=0 );
if( pRight->op==TK_COLUMN
&& !ExprHasProperty(pRight, EP_FixedCol)
&& sqlite3ExprIsConstant(pLeft)
&& sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr))
){
constInsert(pConst, pRight, pLeft);
}else
if( pLeft->op==TK_COLUMN
&& !ExprHasProperty(pLeft, EP_FixedCol)
&& sqlite3ExprIsConstant(pRight)
&& sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr))
){
constInsert(pConst, pLeft, pRight);
}
}
/*
** This is a Walker expression callback. pExpr is a candidate expression
** to be replaced by a value. If pExpr is equivalent to one of the
** columns named in pWalker->u.pConst, then overwrite it with its
** corresponding value.
*/
static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
int i;
WhereConst *pConst;
if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;
pConst = pWalker->u.pConst;
for(i=0; i<pConst->nConst; i++){
Expr *pColumn = pConst->apExpr[i*2];
if( pColumn==pExpr ) continue;
if( pColumn->iTable!=pExpr->iTable ) continue;
if( pColumn->iColumn!=pExpr->iColumn ) continue;
/* A match is found. Add the EP_FixedCol property */
pConst->nChng++;
ExprClearProperty(pExpr, EP_Leaf);
ExprSetProperty(pExpr, EP_FixedCol);
assert( pExpr->pLeft==0 );
pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
break;
}
return WRC_Prune;
}
/*
** The WHERE-clause constant propagation optimization.
**
** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level
** AND-connected terms that are not part of a ON clause from a LEFT JOIN)
** then throughout the query replace all other occurrences of COLUMN
** with CONSTANT within the WHERE clause.
**
** For example, the query:
**
** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
**
** Is transformed into
**
** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
**
** Return true if any transformations where made and false if not.
**
** Implementation note: Constant propagation is tricky due to affinity
** and collating sequence interactions. Consider this example:
**
** CREATE TABLE t1(a INT,b TEXT);
** INSERT INTO t1 VALUES(123,'0123');
** SELECT * FROM t1 WHERE a=123 AND b=a;
** SELECT * FROM t1 WHERE a=123 AND b=123;
**
** The two SELECT statements above should return different answers. b=a
** is alway true because the comparison uses numeric affinity, but b=123
** is false because it uses text affinity and '0123' is not the same as '123'.
** To work around this, the expression tree is not actually changed from
** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
** and the "123" value is hung off of the pLeft pointer. Code generator
** routines know to generate the constant "123" instead of looking up the
** column value. Also, to avoid collation problems, this optimization is
** only attempted if the "a=123" term uses the default BINARY collation.
*/
static int propagateConstants(
Parse *pParse, /* The parsing context */
Select *p /* The query in which to propagate constants */
){
WhereConst x;
Walker w;
int nChng = 0;
x.pParse = pParse;
do{
x.nConst = 0;
x.nChng = 0;
x.apExpr = 0;
findConstInWhere(&x, p->pWhere);
if( x.nConst ){
memset(&w, 0, sizeof(w));
w.pParse = pParse;
w.xExprCallback = propagateConstantExprRewrite;
w.xSelectCallback = sqlite3SelectWalkNoop;
w.xSelectCallback2 = 0;
w.walkerDepth = 0;
w.u.pConst = &x;
sqlite3WalkExpr(&w, p->pWhere);
sqlite3DbFree(x.pParse->db, x.apExpr);
nChng += x.nChng;
}
}while( x.nChng );
return nChng;
}
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/*
** Make copies of relevant WHERE clause terms of the outer query into
** the WHERE clause of subquery. Example:
**
** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
**
** Transformed into:
**
** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
** WHERE x=5 AND y=10;
**
** The hope is that the terms added to the inner query will make it more
** efficient.
**
** Do not attempt this optimization if:
**
** (1) (** This restriction was removed on 2017-09-29. We used to
** disallow this optimization for aggregate subqueries, but now
** it is allowed by putting the extra terms on the HAVING clause.
** The added HAVING clause is pointless if the subquery lacks
** a GROUP BY clause. But such a HAVING clause is also harmless
** so there does not appear to be any reason to add extra logic
** to suppress it. **)
**
** (2) The inner query is the recursive part of a common table expression.
**
** (3) The inner query has a LIMIT clause (since the changes to the WHERE
** clause would change the meaning of the LIMIT).
**
** (4) The inner query is the right operand of a LEFT JOIN and the
** expression to be pushed down does not come from the ON clause
** on that LEFT JOIN.
**
** (5) The WHERE clause expression originates in the ON or USING clause
** of a LEFT JOIN where iCursor is not the right-hand table of that
** left join. An example:
**
** SELECT *
** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
**
** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
** But if the (b2=2) term were to be pushed down into the bb subquery,
** then the (1,1,NULL) row would be suppressed.
**
** (6) The inner query features one or more window-functions (since
** changes to the WHERE clause of the inner query could change the
** window over which window functions are calculated).
**
** Return 0 if no changes are made and non-zero if one or more WHERE clause
** terms are duplicated into the subquery.
*/
static int pushDownWhereTerms(
Parse *pParse, /* Parse context (for malloc() and error reporting) */
Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
Expr *pWhere, /* The WHERE clause of the outer query */
int iCursor, /* Cursor number of the subquery */
int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
){
Expr *pNew;
int nChng = 0;
if( pWhere==0 ) return 0;
if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
#ifndef SQLITE_OMIT_WINDOWFUNC
if( pSubq->pWin ) return 0; /* restriction (6) */
#endif
#ifdef SQLITE_DEBUG
/* Only the first term of a compound can have a WITH clause. But make
** sure no other terms are marked SF_Recursive in case something changes
** in the future.
*/
{
Select *pX;
for(pX=pSubq; pX; pX=pX->pPrior){
assert( (pX->selFlags & (SF_Recursive))==0 );
}
}
#endif
if( pSubq->pLimit!=0 ){
return 0; /* restriction (3) */
}
while( pWhere->op==TK_AND ){
nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
iCursor, isLeftJoin);
pWhere = pWhere->pLeft;
}
if( isLeftJoin
&& (ExprHasProperty(pWhere,EP_FromJoin)==0
|| pWhere->iRightJoinTable!=iCursor)
){
return 0; /* restriction (4) */
}
if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
return 0; /* restriction (5) */
}
if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
nChng++;
while( pSubq ){
SubstContext x;
pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
unsetJoinExpr(pNew, -1);
x.pParse = pParse;
x.iTable = iCursor;
x.iNewTable = iCursor;
x.isLeftJoin = 0;
x.pEList = pSubq->pEList;
pNew = substExpr(&x, pNew);
if( pSubq->selFlags & SF_Aggregate ){
pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
}else{
pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
}
pSubq = pSubq->pPrior;
}
}
return nChng;
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
/*
** The pFunc is the only aggregate function in the query. Check to see
** if the query is a candidate for the min/max optimization.
**
** If the query is a candidate for the min/max optimization, then set
** *ppMinMax to be an ORDER BY clause to be used for the optimization
** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
** whether pFunc is a min() or max() function.
**
** If the query is not a candidate for the min/max optimization, return
** WHERE_ORDERBY_NORMAL (which must be zero).
**
** This routine must be called after aggregate functions have been
** located but before their arguments have been subjected to aggregate
** analysis.
*/
static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
const char *zFunc; /* Name of aggregate function pFunc */
ExprList *pOrderBy;
u8 sortFlags;
assert( *ppMinMax==0 );
assert( pFunc->op==TK_AGG_FUNCTION );
assert( !IsWindowFunc(pFunc) );
if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){
return eRet;
}
zFunc = pFunc->u.zToken;
if( sqlite3StrICmp(zFunc, "min")==0 ){
eRet = WHERE_ORDERBY_MIN;
sortFlags = KEYINFO_ORDER_BIGNULL;
}else if( sqlite3StrICmp(zFunc, "max")==0 ){
eRet = WHERE_ORDERBY_MAX;
sortFlags = KEYINFO_ORDER_DESC;
}else{
return eRet;
}
*ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
assert( pOrderBy!=0 || db->mallocFailed );
if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags;
return eRet;
}
/*
** The select statement passed as the first argument is an aggregate query.
** The second argument is the associated aggregate-info object. This
** function tests if the SELECT is of the form:
**
** SELECT count(*) FROM <tbl>
**
** where table is a database table, not a sub-select or view. If the query
** does match this pattern, then a pointer to the Table object representing
** <tbl> is returned. Otherwise, 0 is returned.
*/
static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
Table *pTab;
Expr *pExpr;
assert( !p->pGroupBy );
if( p->pWhere || p->pEList->nExpr!=1
|| p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
){
return 0;
}
pTab = p->pSrc->a[0].pTab;
pExpr = p->pEList->a[0].pExpr;
assert( pTab && !pTab->pSelect && pExpr );
if( IsVirtual(pTab) ) return 0;
if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
if( NEVER(pAggInfo->nFunc==0) ) return 0;
if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
return pTab;
}
/*
** If the source-list item passed as an argument was augmented with an
** INDEXED BY clause, then try to locate the specified index. If there
** was such a clause and the named index cannot be found, return
** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
** pFrom->pIndex and return SQLITE_OK.
*/
int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
if( pFrom->pTab && pFrom->fg.isIndexedBy ){
Table *pTab = pFrom->pTab;
char *zIndexedBy = pFrom->u1.zIndexedBy;
Index *pIdx;
for(pIdx=pTab->pIndex;
pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
pIdx=pIdx->pNext
);
if( !pIdx ){
sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
pParse->checkSchema = 1;
return SQLITE_ERROR;
}
pFrom->pIBIndex = pIdx;
}
return SQLITE_OK;
}
/*
** Detect compound SELECT statements that use an ORDER BY clause with
** an alternative collating sequence.
**
** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
**
** These are rewritten as a subquery:
**
** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
** ORDER BY ... COLLATE ...
**
** This transformation is necessary because the multiSelectOrderBy() routine
** above that generates the code for a compound SELECT with an ORDER BY clause
** uses a merge algorithm that requires the same collating sequence on the
** result columns as on the ORDER BY clause. See ticket
** http://www.sqlite.org/src/info/6709574d2a
**
** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
** The UNION ALL operator works fine with multiSelectOrderBy() even when
** there are COLLATE terms in the ORDER BY.
*/
static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
int i;
Select *pNew;
Select *pX;
sqlite3 *db;
struct ExprList_item *a;
SrcList *pNewSrc;
Parse *pParse;
Token dummy;
if( p->pPrior==0 ) return WRC_Continue;
if( p->pOrderBy==0 ) return WRC_Continue;
for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
if( pX==0 ) return WRC_Continue;
a = p->pOrderBy->a;
for(i=p->pOrderBy->nExpr-1; i>=0; i--){
if( a[i].pExpr->flags & EP_Collate ) break;
}
if( i<0 ) return WRC_Continue;
/* If we reach this point, that means the transformation is required. */
pParse = pWalker->pParse;
db = pParse->db;
pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
if( pNew==0 ) return WRC_Abort;
memset(&dummy, 0, sizeof(dummy));
pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
if( pNewSrc==0 ) return WRC_Abort;
*pNew = *p;
p->pSrc = pNewSrc;
p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
p->op = TK_SELECT;
p->pWhere = 0;
pNew->pGroupBy = 0;
pNew->pHaving = 0;
pNew->pOrderBy = 0;
p->pPrior = 0;
p->pNext = 0;
p->pWith = 0;
#ifndef SQLITE_OMIT_WINDOWFUNC
p->pWinDefn = 0;
#endif
p->selFlags &= ~SF_Compound;
assert( (p->selFlags & SF_Converted)==0 );
p->selFlags |= SF_Converted;
assert( pNew->pPrior!=0 );
pNew->pPrior->pNext = pNew;
pNew->pLimit = 0;
return WRC_Continue;
}
/*
** Check to see if the FROM clause term pFrom has table-valued function
** arguments. If it does, leave an error message in pParse and return
** non-zero, since pFrom is not allowed to be a table-valued function.
*/
static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
if( pFrom->fg.isTabFunc ){
sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
return 1;
}
return 0;
}
#ifndef SQLITE_OMIT_CTE
/*
** Argument pWith (which may be NULL) points to a linked list of nested
** WITH contexts, from inner to outermost. If the table identified by
** FROM clause element pItem is really a common-table-expression (CTE)
** then return a pointer to the CTE definition for that table. Otherwise
** return NULL.
**
** If a non-NULL value is returned, set *ppContext to point to the With
** object that the returned CTE belongs to.
*/
static struct Cte *searchWith(
With *pWith, /* Current innermost WITH clause */
struct SrcList_item *pItem, /* FROM clause element to resolve */
With **ppContext /* OUT: WITH clause return value belongs to */
){
const char *zName;
if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
With *p;
for(p=pWith; p; p=p->pOuter){
int i;
for(i=0; i<p->nCte; i++){
if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
*ppContext = p;
return &p->a[i];
}
}
}
}
return 0;
}
/* The code generator maintains a stack of active WITH clauses
** with the inner-most WITH clause being at the top of the stack.
**
** This routine pushes the WITH clause passed as the second argument
** onto the top of the stack. If argument bFree is true, then this
** WITH clause will never be popped from the stack. In this case it
** should be freed along with the Parse object. In other cases, when
** bFree==0, the With object will be freed along with the SELECT
** statement with which it is associated.
*/
void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
if( pWith ){
assert( pParse->pWith!=pWith );
pWith->pOuter = pParse->pWith;
pParse->pWith = pWith;
if( bFree ) pParse->pWithToFree = pWith;
}
}
/*
** This function checks if argument pFrom refers to a CTE declared by
** a WITH clause on the stack currently maintained by the parser. And,
** if currently processing a CTE expression, if it is a recursive
** reference to the current CTE.
**
** If pFrom falls into either of the two categories above, pFrom->pTab
** and other fields are populated accordingly. The caller should check
** (pFrom->pTab!=0) to determine whether or not a successful match
** was found.
**
** Whether or not a match is found, SQLITE_OK is returned if no error
** occurs. If an error does occur, an error message is stored in the
** parser and some error code other than SQLITE_OK returned.
*/
static int withExpand(
Walker *pWalker,
struct SrcList_item *pFrom
){
Parse *pParse = pWalker->pParse;
sqlite3 *db = pParse->db;
struct Cte *pCte; /* Matched CTE (or NULL if no match) */
With *pWith; /* WITH clause that pCte belongs to */
assert( pFrom->pTab==0 );
if( pParse->nErr ){
return SQLITE_ERROR;
}
pCte = searchWith(pParse->pWith, pFrom, &pWith);
if( pCte ){
Table *pTab;
ExprList *pEList;
Select *pSel;
Select *pLeft; /* Left-most SELECT statement */
int bMayRecursive; /* True if compound joined by UNION [ALL] */
With *pSavedWith; /* Initial value of pParse->pWith */
/* If pCte->zCteErr is non-NULL at this point, then this is an illegal
** recursive reference to CTE pCte. Leave an error in pParse and return
** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
** In this case, proceed. */
if( pCte->zCteErr ){
sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
return SQLITE_ERROR;
}
if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
assert( pFrom->pTab==0 );
pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
if( pTab==0 ) return WRC_Abort;
pTab->nTabRef = 1;
pTab->zName = sqlite3DbStrDup(db, pCte->zName);
pTab->iPKey = -1;
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
assert( pFrom->pSelect );
/* Check if this is a recursive CTE. */
pSel = pFrom->pSelect;
bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
if( bMayRecursive ){
int i;
SrcList *pSrc = pFrom->pSelect->pSrc;
for(i=0; i<pSrc->nSrc; i++){
struct SrcList_item *pItem = &pSrc->a[i];
if( pItem->zDatabase==0
&& pItem->zName!=0
&& 0==sqlite3StrICmp(pItem->zName, pCte->zName)
){
pItem->pTab = pTab;
pItem->fg.isRecursive = 1;
pTab->nTabRef++;
pSel->selFlags |= SF_Recursive;
}
}
}
/* Only one recursive reference is permitted. */
if( pTab->nTabRef>2 ){
sqlite3ErrorMsg(
pParse, "multiple references to recursive table: %s", pCte->zName
);
return SQLITE_ERROR;
}
assert( pTab->nTabRef==1 ||
((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
pCte->zCteErr = "circular reference: %s";
pSavedWith = pParse->pWith;
pParse->pWith = pWith;
if( bMayRecursive ){
Select *pPrior = pSel->pPrior;
assert( pPrior->pWith==0 );
pPrior->pWith = pSel->pWith;
sqlite3WalkSelect(pWalker, pPrior);
pPrior->pWith = 0;
}else{
sqlite3WalkSelect(pWalker, pSel);
}
pParse->pWith = pWith;
for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
pEList = pLeft->pEList;
if( pCte->pCols ){
if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
pCte->zName, pEList->nExpr, pCte->pCols->nExpr
);
pParse->pWith = pSavedWith;
return SQLITE_ERROR;
}
pEList = pCte->pCols;
}
sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
if( bMayRecursive ){
if( pSel->selFlags & SF_Recursive ){
pCte->zCteErr = "multiple recursive references: %s";
}else{
pCte->zCteErr = "recursive reference in a subquery: %s";
}
sqlite3WalkSelect(pWalker, pSel);
}
pCte->zCteErr = 0;
pParse->pWith = pSavedWith;
}
return SQLITE_OK;
}
#endif
#ifndef SQLITE_OMIT_CTE
/*
** If the SELECT passed as the second argument has an associated WITH
** clause, pop it from the stack stored as part of the Parse object.
**
** This function is used as the xSelectCallback2() callback by
** sqlite3SelectExpand() when walking a SELECT tree to resolve table
** names and other FROM clause elements.
*/
static void selectPopWith(Walker *pWalker, Select *p){
Parse *pParse = pWalker->pParse;
if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
With *pWith = findRightmost(p)->pWith;
if( pWith!=0 ){
assert( pParse->pWith==pWith );
pParse->pWith = pWith->pOuter;
}
}
}
#else
#define selectPopWith 0
#endif
/*
** The SrcList_item structure passed as the second argument represents a
** sub-query in the FROM clause of a SELECT statement. This function
** allocates and populates the SrcList_item.pTab object. If successful,
** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
** SQLITE_NOMEM.
*/
int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
Select *pSel = pFrom->pSelect;
Table *pTab;
assert( pSel );
pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
if( pTab==0 ) return SQLITE_NOMEM;
pTab->nTabRef = 1;
if( pFrom->zAlias ){
pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
}else{
pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId);
}
while( pSel->pPrior ){ pSel = pSel->pPrior; }
sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
pTab->iPKey = -1;
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
pTab->tabFlags |= TF_Ephemeral;
return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
}
/*
** This routine is a Walker callback for "expanding" a SELECT statement.
** "Expanding" means to do the following:
**
** (1) Make sure VDBE cursor numbers have been assigned to every
** element of the FROM clause.
**
** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
** defines FROM clause. When views appear in the FROM clause,
** fill pTabList->a[].pSelect with a copy of the SELECT statement
** that implements the view. A copy is made of the view's SELECT
** statement so that we can freely modify or delete that statement
** without worrying about messing up the persistent representation
** of the view.
**
** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
** on joins and the ON and USING clause of joins.
**
** (4) Scan the list of columns in the result set (pEList) looking
** for instances of the "*" operator or the TABLE.* operator.
** If found, expand each "*" to be every column in every table
** and TABLE.* to be every column in TABLE.
**
*/
static int selectExpander(Walker *pWalker, Select *p){
Parse *pParse = pWalker->pParse;
int i, j, k;
SrcList *pTabList;
ExprList *pEList;
struct SrcList_item *pFrom;
sqlite3 *db = pParse->db;
Expr *pE, *pRight, *pExpr;
u16 selFlags = p->selFlags;
u32 elistFlags = 0;
p->selFlags |= SF_Expanded;
if( db->mallocFailed ){
return WRC_Abort;
}
assert( p->pSrc!=0 );
if( (selFlags & SF_Expanded)!=0 ){
return WRC_Prune;
}
if( pWalker->eCode ){
/* Renumber selId because it has been copied from a view */
p->selId = ++pParse->nSelect;
}
pTabList = p->pSrc;
pEList = p->pEList;
sqlite3WithPush(pParse, p->pWith, 0);
/* Make sure cursor numbers have been assigned to all entries in
** the FROM clause of the SELECT statement.
*/
sqlite3SrcListAssignCursors(pParse, pTabList);
/* Look up every table named in the FROM clause of the select. If
** an entry of the FROM clause is a subquery instead of a table or view,
** then create a transient table structure to describe the subquery.
*/
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
Table *pTab;
assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
if( pFrom->fg.isRecursive ) continue;
assert( pFrom->pTab==0 );
#ifndef SQLITE_OMIT_CTE
if( withExpand(pWalker, pFrom) ) return WRC_Abort;
if( pFrom->pTab ) {} else
#endif
if( pFrom->zName==0 ){
#ifndef SQLITE_OMIT_SUBQUERY
Select *pSel = pFrom->pSelect;
/* A sub-query in the FROM clause of a SELECT */
assert( pSel!=0 );
assert( pFrom->pTab==0 );
if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
#endif
}else{
/* An ordinary table or view name in the FROM clause */
assert( pFrom->pTab==0 );
pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
if( pTab==0 ) return WRC_Abort;
if( pTab->nTabRef>=0xffff ){
sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
pTab->zName);
pFrom->pTab = 0;
return WRC_Abort;
}
pTab->nTabRef++;
if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
return WRC_Abort;
}
#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
if( IsVirtual(pTab) || pTab->pSelect ){
i16 nCol;
u8 eCodeOrig = pWalker->eCode;
if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
assert( pFrom->pSelect==0 );
if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){
sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
pTab->zName);
}
pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
nCol = pTab->nCol;
pTab->nCol = -1;
pWalker->eCode = 1; /* Turn on Select.selId renumbering */
sqlite3WalkSelect(pWalker, pFrom->pSelect);
pWalker->eCode = eCodeOrig;
pTab->nCol = nCol;
}
#endif
}
/* Locate the index named by the INDEXED BY clause, if any. */
if( sqlite3IndexedByLookup(pParse, pFrom) ){
return WRC_Abort;
}
}
/* Process NATURAL keywords, and ON and USING clauses of joins.
*/
if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
return WRC_Abort;
}
/* For every "*" that occurs in the column list, insert the names of
** all columns in all tables. And for every TABLE.* insert the names
** of all columns in TABLE. The parser inserted a special expression
** with the TK_ASTERISK operator for each "*" that it found in the column
** list. The following code just has to locate the TK_ASTERISK
** expressions and expand each one to the list of all columns in
** all tables.
**
** The first loop just checks to see if there are any "*" operators
** that need expanding.
*/
for(k=0; k<pEList->nExpr; k++){
pE = pEList->a[k].pExpr;
if( pE->op==TK_ASTERISK ) break;
assert( pE->op!=TK_DOT || pE->pRight!=0 );
assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
elistFlags |= pE->flags;
}
if( k<pEList->nExpr ){
/*
** If we get here it means the result set contains one or more "*"
** operators that need to be expanded. Loop through each expression
** in the result set and expand them one by one.
*/
struct ExprList_item *a = pEList->a;
ExprList *pNew = 0;
int flags = pParse->db->flags;
int longNames = (flags & SQLITE_FullColNames)!=0
&& (flags & SQLITE_ShortColNames)==0;
for(k=0; k<pEList->nExpr; k++){
pE = a[k].pExpr;
elistFlags |= pE->flags;
pRight = pE->pRight;
assert( pE->op!=TK_DOT || pRight!=0 );
if( pE->op!=TK_ASTERISK
&& (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
){
/* This particular expression does not need to be expanded.
*/
pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
if( pNew ){
pNew->a[pNew->nExpr-1].zName = a[k].zName;
pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
a[k].zName = 0;
a[k].zSpan = 0;
}
a[k].pExpr = 0;
}else{
/* This expression is a "*" or a "TABLE.*" and needs to be
** expanded. */
int tableSeen = 0; /* Set to 1 when TABLE matches */
char *zTName = 0; /* text of name of TABLE */
if( pE->op==TK_DOT ){
assert( pE->pLeft!=0 );
assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
zTName = pE->pLeft->u.zToken;
}
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
Table *pTab = pFrom->pTab;
Select *pSub = pFrom->pSelect;
char *zTabName = pFrom->zAlias;
const char *zSchemaName = 0;
int iDb;
if( zTabName==0 ){
zTabName = pTab->zName;
}
if( db->mallocFailed ) break;
if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
pSub = 0;
if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
continue;
}
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
}
for(j=0; j<pTab->nCol; j++){
char *zName = pTab->aCol[j].zName;
char *zColname; /* The computed column name */
char *zToFree; /* Malloced string that needs to be freed */
Token sColname; /* Computed column name as a token */
assert( zName );
if( zTName && pSub
&& sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
){
continue;
}
/* If a column is marked as 'hidden', omit it from the expanded
** result-set list unless the SELECT has the SF_IncludeHidden
** bit set.
*/
if( (p->selFlags & SF_IncludeHidden)==0
&& IsHiddenColumn(&pTab->aCol[j])
){
continue;
}
tableSeen = 1;
if( i>0 && zTName==0 ){
if( (pFrom->fg.jointype & JT_NATURAL)!=0
&& tableAndColumnIndex(pTabList, i, zName, 0, 0)
){
/* In a NATURAL join, omit the join columns from the
** table to the right of the join */
continue;
}
if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
/* In a join with a USING clause, omit columns in the
** using clause from the table on the right. */
continue;
}
}
pRight = sqlite3Expr(db, TK_ID, zName);
zColname = zName;
zToFree = 0;
if( longNames || pTabList->nSrc>1 ){
Expr *pLeft;
pLeft = sqlite3Expr(db, TK_ID, zTabName);
pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
if( zSchemaName ){
pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
}
if( longNames ){
zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
zToFree = zColname;
}
}else{
pExpr = pRight;
}
pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
sqlite3TokenInit(&sColname, zColname);
sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
if( pSub ){
pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
testcase( pX->zSpan==0 );
}else{
pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
zSchemaName, zTabName, zColname);
testcase( pX->zSpan==0 );
}
pX->bSpanIsTab = 1;
}
sqlite3DbFree(db, zToFree);
}
}
if( !tableSeen ){
if( zTName ){
sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
}else{
sqlite3ErrorMsg(pParse, "no tables specified");
}
}
}
}
sqlite3ExprListDelete(db, pEList);
p->pEList = pNew;
}
if( p->pEList ){
if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
sqlite3ErrorMsg(pParse, "too many columns in result set");
return WRC_Abort;
}
if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
p->selFlags |= SF_ComplexResult;
}
}
return WRC_Continue;
}
/*
** No-op routine for the parse-tree walker.
**
** When this routine is the Walker.xExprCallback then expression trees
** are walked without any actions being taken at each node. Presumably,
** when this routine is used for Walker.xExprCallback then
** Walker.xSelectCallback is set to do something useful for every
** subquery in the parser tree.
*/
int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
return WRC_Continue;
}
/*
** No-op routine for the parse-tree walker for SELECT statements.
** subquery in the parser tree.
*/
int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
return WRC_Continue;
}
#if SQLITE_DEBUG
/*
** Always assert. This xSelectCallback2 implementation proves that the
** xSelectCallback2 is never invoked.
*/
void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
assert( 0 );
}
#endif
/*
** This routine "expands" a SELECT statement and all of its subqueries.
** For additional information on what it means to "expand" a SELECT
** statement, see the comment on the selectExpand worker callback above.
**
** Expanding a SELECT statement is the first step in processing a
** SELECT statement. The SELECT statement must be expanded before
** name resolution is performed.
**
** If anything goes wrong, an error message is written into pParse.
** The calling function can detect the problem by looking at pParse->nErr
** and/or pParse->db->mallocFailed.
*/
static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
Walker w;
w.xExprCallback = sqlite3ExprWalkNoop;
w.pParse = pParse;
if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
w.xSelectCallback = convertCompoundSelectToSubquery;
w.xSelectCallback2 = 0;
sqlite3WalkSelect(&w, pSelect);
}
w.xSelectCallback = selectExpander;
w.xSelectCallback2 = selectPopWith;
w.eCode = 0;
sqlite3WalkSelect(&w, pSelect);
}
#ifndef SQLITE_OMIT_SUBQUERY
/*
** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
** interface.
**
** For each FROM-clause subquery, add Column.zType and Column.zColl
** information to the Table structure that represents the result set
** of that subquery.
**
** The Table structure that represents the result set was constructed
** by selectExpander() but the type and collation information was omitted
** at that point because identifiers had not yet been resolved. This
** routine is called after identifier resolution.
*/
static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
Parse *pParse;
int i;
SrcList *pTabList;
struct SrcList_item *pFrom;
assert( p->selFlags & SF_Resolved );
if( p->selFlags & SF_HasTypeInfo ) return;
p->selFlags |= SF_HasTypeInfo;
pParse = pWalker->pParse;
pTabList = p->pSrc;
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
Table *pTab = pFrom->pTab;
assert( pTab!=0 );
if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
/* A sub-query in the FROM clause of a SELECT */
Select *pSel = pFrom->pSelect;
if( pSel ){
while( pSel->pPrior ) pSel = pSel->pPrior;
sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel,
SQLITE_AFF_NONE);
}
}
}
}
#endif
/*
** This routine adds datatype and collating sequence information to
** the Table structures of all FROM-clause subqueries in a
** SELECT statement.
**
** Use this routine after name resolution.
*/
static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
#ifndef SQLITE_OMIT_SUBQUERY
Walker w;
w.xSelectCallback = sqlite3SelectWalkNoop;
w.xSelectCallback2 = selectAddSubqueryTypeInfo;
w.xExprCallback = sqlite3ExprWalkNoop;
w.pParse = pParse;
sqlite3WalkSelect(&w, pSelect);
#endif
}
/*
** This routine sets up a SELECT statement for processing. The
** following is accomplished:
**
** * VDBE Cursor numbers are assigned to all FROM-clause terms.
** * Ephemeral Table objects are created for all FROM-clause subqueries.
** * ON and USING clauses are shifted into WHERE statements
** * Wildcards "*" and "TABLE.*" in result sets are expanded.
** * Identifiers in expression are matched to tables.
**
** This routine acts recursively on all subqueries within the SELECT.
*/
void sqlite3SelectPrep(
Parse *pParse, /* The parser context */
Select *p, /* The SELECT statement being coded. */
NameContext *pOuterNC /* Name context for container */
){
assert( p!=0 || pParse->db->mallocFailed );
if( pParse->db->mallocFailed ) return;
if( p->selFlags & SF_HasTypeInfo ) return;
sqlite3SelectExpand(pParse, p);
if( pParse->nErr || pParse->db->mallocFailed ) return;
sqlite3ResolveSelectNames(pParse, p, pOuterNC);
if( pParse->nErr || pParse->db->mallocFailed ) return;
sqlite3SelectAddTypeInfo(pParse, p);
}
/*
** Reset the aggregate accumulator.
**
** The aggregate accumulator is a set of memory cells that hold
** intermediate results while calculating an aggregate. This
** routine generates code that stores NULLs in all of those memory
** cells.
*/
static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
Vdbe *v = pParse->pVdbe;
int i;
struct AggInfo_func *pFunc;
int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
if( nReg==0 ) return;
#ifdef SQLITE_DEBUG
/* Verify that all AggInfo registers are within the range specified by
** AggInfo.mnReg..AggInfo.mxReg */
assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
for(i=0; i<pAggInfo->nColumn; i++){
assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
&& pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
}
for(i=0; i<pAggInfo->nFunc; i++){
assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
&& pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
}
#endif
sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
if( pFunc->iDistinct>=0 ){
Expr *pE = pFunc->pExpr;
assert( !ExprHasProperty(pE, EP_xIsSelect) );
if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
"argument");
pFunc->iDistinct = -1;
}else{
KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
(char*)pKeyInfo, P4_KEYINFO);
}
}
}
}
/*
** Invoke the OP_AggFinalize opcode for every aggregate function
** in the AggInfo structure.
*/
static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
Vdbe *v = pParse->pVdbe;
int i;
struct AggInfo_func *pF;
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
ExprList *pList = pF->pExpr->x.pList;
assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
}
}
/*
** Update the accumulator memory cells for an aggregate based on
** the current cursor position.
**
** If regAcc is non-zero and there are no min() or max() aggregates
** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
** registers if register regAcc contains 0. The caller will take care
** of setting and clearing regAcc.
*/
static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
Vdbe *v = pParse->pVdbe;
int i;
int regHit = 0;
int addrHitTest = 0;
struct AggInfo_func *pF;
struct AggInfo_col *pC;
pAggInfo->directMode = 1;
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
int nArg;
int addrNext = 0;
int regAgg;
ExprList *pList = pF->pExpr->x.pList;
assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
assert( !IsWindowFunc(pF->pExpr) );
if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){
Expr *pFilter = pF->pExpr->y.pWin->pFilter;
if( pAggInfo->nAccumulator
&& (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
){
if( regHit==0 ) regHit = ++pParse->nMem;
/* If this is the first row of the group (regAcc==0), clear the
** "magnet" register regHit so that the accumulator registers
** are populated if the FILTER clause jumps over the the
** invocation of min() or max() altogether. Or, if this is not
** the first row (regAcc==1), set the magnet register so that the
** accumulators are not populated unless the min()/max() is invoked and
** indicates that they should be. */
sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
}
addrNext = sqlite3VdbeMakeLabel(pParse);
sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
}
if( pList ){
nArg = pList->nExpr;
regAgg = sqlite3GetTempRange(pParse, nArg);
sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
}else{
nArg = 0;
regAgg = 0;
}
if( pF->iDistinct>=0 ){
if( addrNext==0 ){
addrNext = sqlite3VdbeMakeLabel(pParse);
}
testcase( nArg==0 ); /* Error condition */
testcase( nArg>1 ); /* Also an error */
codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
}
if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
CollSeq *pColl = 0;
struct ExprList_item *pItem;
int j;
assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
}
if( !pColl ){
pColl = pParse->db->pDfltColl;
}
if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
}
sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
sqlite3VdbeChangeP5(v, (u8)nArg);
sqlite3ReleaseTempRange(pParse, regAgg, nArg);
if( addrNext ){
sqlite3VdbeResolveLabel(v, addrNext);
}
}
if( regHit==0 && pAggInfo->nAccumulator ){
regHit = regAcc;
}
if( regHit ){
addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
}
for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
}
pAggInfo->directMode = 0;
if( addrHitTest ){
sqlite3VdbeJumpHere(v, addrHitTest);
}
}
/*
** Add a single OP_Explain instruction to the VDBE to explain a simple
** count(*) query ("SELECT count(*) FROM pTab").
*/
#ifndef SQLITE_OMIT_EXPLAIN
static void explainSimpleCount(
Parse *pParse, /* Parse context */
Table *pTab, /* Table being queried */
Index *pIdx /* Index used to optimize scan, or NULL */
){
if( pParse->explain==2 ){
int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
pTab->zName,
bCover ? " USING COVERING INDEX " : "",
bCover ? pIdx->zName : ""
);
}
}
#else
# define explainSimpleCount(a,b,c)
#endif
/*
** sqlite3WalkExpr() callback used by havingToWhere().
**
** If the node passed to the callback is a TK_AND node, return
** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
**
** Otherwise, return WRC_Prune. In this case, also check if the
** sub-expression matches the criteria for being moved to the WHERE
** clause. If so, add it to the WHERE clause and replace the sub-expression
** within the HAVING expression with a constant "1".
*/
static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
if( pExpr->op!=TK_AND ){
Select *pS = pWalker->u.pSelect;
if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
sqlite3 *db = pWalker->pParse->db;
Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
if( pNew ){
Expr *pWhere = pS->pWhere;
SWAP(Expr, *pNew, *pExpr);
pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
pS->pWhere = pNew;
pWalker->eCode = 1;
}
}
return WRC_Prune;
}
return WRC_Continue;
}
/*
** Transfer eligible terms from the HAVING clause of a query, which is
** processed after grouping, to the WHERE clause, which is processed before
** grouping. For example, the query:
**
** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
**
** can be rewritten as:
**
** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
**
** A term of the HAVING expression is eligible for transfer if it consists
** entirely of constants and expressions that are also GROUP BY terms that
** use the "BINARY" collation sequence.
*/
static void havingToWhere(Parse *pParse, Select *p){
Walker sWalker;
memset(&sWalker, 0, sizeof(sWalker));
sWalker.pParse = pParse;
sWalker.xExprCallback = havingToWhereExprCb;
sWalker.u.pSelect = p;
sqlite3WalkExpr(&sWalker, p->pHaving);
#if SELECTTRACE_ENABLED
if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}
/*
** Check to see if the pThis entry of pTabList is a self-join of a prior view.
** If it is, then return the SrcList_item for the prior view. If it is not,
** then return 0.
*/
static struct SrcList_item *isSelfJoinView(
SrcList *pTabList, /* Search for self-joins in this FROM clause */
struct SrcList_item *pThis /* Search for prior reference to this subquery */
){
struct SrcList_item *pItem;
for(pItem = pTabList->a; pItem<pThis; pItem++){
Select *pS1;
if( pItem->pSelect==0 ) continue;
if( pItem->fg.viaCoroutine ) continue;
if( pItem->zName==0 ) continue;
assert( pItem->pTab!=0 );
assert( pThis->pTab!=0 );
if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
pS1 = pItem->pSelect;
if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
/* The query flattener left two different CTE tables with identical
** names in the same FROM clause. */
continue;
}
if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1)
|| sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1)
){
/* The view was modified by some other optimization such as
** pushDownWhereTerms() */
continue;
}
return pItem;
}
return 0;
}
#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
/*
** Attempt to transform a query of the form
**
** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
**
** Into this:
**
** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
**
** The transformation only works if all of the following are true:
**
** * The subquery is a UNION ALL of two or more terms
** * The subquery does not have a LIMIT clause
** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
** * The outer query is a simple count(*) with no WHERE clause or other
** extraneous syntax.
**
** Return TRUE if the optimization is undertaken.
*/
static int countOfViewOptimization(Parse *pParse, Select *p){
Select *pSub, *pPrior;
Expr *pExpr;
Expr *pCount;
sqlite3 *db;
if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
if( p->pWhere ) return 0;
if( p->pGroupBy ) return 0;
pExpr = p->pEList->a[0].pExpr;
if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
pSub = p->pSrc->a[0].pSelect;
if( pSub==0 ) return 0; /* The FROM is a subquery */
if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
do{
if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
if( pSub->pWhere ) return 0; /* No WHERE clause */
if( pSub->pLimit ) return 0; /* No LIMIT clause */
if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
pSub = pSub->pPrior; /* Repeat over compound */
}while( pSub );
/* If we reach this point then it is OK to perform the transformation */
db = pParse->db;
pCount = pExpr;
pExpr = 0;
pSub = p->pSrc->a[0].pSelect;
p->pSrc->a[0].pSelect = 0;
sqlite3SrcListDelete(db, p->pSrc);
p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
while( pSub ){
Expr *pTerm;
pPrior = pSub->pPrior;
pSub->pPrior = 0;
pSub->pNext = 0;
pSub->selFlags |= SF_Aggregate;
pSub->selFlags &= ~SF_Compound;
pSub->nSelectRow = 0;
sqlite3ExprListDelete(db, pSub->pEList);
pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
sqlite3PExprAddSelect(pParse, pTerm, pSub);
if( pExpr==0 ){
pExpr = pTerm;
}else{
pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
}
pSub = pPrior;
}
p->pEList->a[0].pExpr = pExpr;
p->selFlags &= ~SF_Aggregate;
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
return 1;
}
#endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
/*
** Generate code for the SELECT statement given in the p argument.
**
** The results are returned according to the SelectDest structure.
** See comments in sqliteInt.h for further information.
**
** This routine returns the number of errors. If any errors are
** encountered, then an appropriate error message is left in
** pParse->zErrMsg.
**
** This routine does NOT free the Select structure passed in. The
** calling function needs to do that.
*/
int sqlite3Select(
Parse *pParse, /* The parser context */
Select *p, /* The SELECT statement being coded. */
SelectDest *pDest /* What to do with the query results */
){
int i, j; /* Loop counters */
WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
Vdbe *v; /* The virtual machine under construction */
int isAgg; /* True for select lists like "count(*)" */
ExprList *pEList = 0; /* List of columns to extract. */
SrcList *pTabList; /* List of tables to select from */
Expr *pWhere; /* The WHERE clause. May be NULL */
ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
Expr *pHaving; /* The HAVING clause. May be NULL */
int rc = 1; /* Value to return from this function */
DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
SortCtx sSort; /* Info on how to code the ORDER BY clause */
AggInfo sAggInfo; /* Information used by aggregate queries */
int iEnd; /* Address of the end of the query */
sqlite3 *db; /* The database connection */
ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
u8 minMaxFlag; /* Flag for min/max queries */
db = pParse->db;
v = sqlite3GetVdbe(pParse);
if( p==0 || db->mallocFailed || pParse->nErr ){
return 1;
}
if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
memset(&sAggInfo, 0, sizeof(sAggInfo));
#if SELECTTRACE_ENABLED
SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
if( sqlite3SelectTrace & 0x100 ){
sqlite3TreeViewSelect(0, p, 0);
}
#endif
assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
if( IgnorableOrderby(pDest) ){
assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
/* If ORDER BY makes no difference in the output then neither does
** DISTINCT so it can be removed too. */
sqlite3ExprListDelete(db, p->pOrderBy);
p->pOrderBy = 0;
p->selFlags &= ~SF_Distinct;
}
sqlite3SelectPrep(pParse, p, 0);
if( pParse->nErr || db->mallocFailed ){
goto select_end;
}
assert( p->pEList!=0 );
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x104 ){
SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
if( pDest->eDest==SRT_Output ){
generateColumnNames(pParse, p);
}
#ifndef SQLITE_OMIT_WINDOWFUNC
if( sqlite3WindowRewrite(pParse, p) ){
goto select_end;
}
#if SELECTTRACE_ENABLED
if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){
SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
#endif /* SQLITE_OMIT_WINDOWFUNC */
pTabList = p->pSrc;
isAgg = (p->selFlags & SF_Aggregate)!=0;
memset(&sSort, 0, sizeof(sSort));
sSort.pOrderBy = p->pOrderBy;
/* Try to various optimizations (flattening subqueries, and strength
** reduction of join operators) in the FROM clause up into the main query
*/
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
struct SrcList_item *pItem = &pTabList->a[i];
Select *pSub = pItem->pSelect;
Table *pTab = pItem->pTab;
/* Convert LEFT JOIN into JOIN if there are terms of the right table
** of the LEFT JOIN used in the WHERE clause.
*/
if( (pItem->fg.jointype & JT_LEFT)!=0
&& sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
&& OptimizationEnabled(db, SQLITE_SimplifyJoin)
){
SELECTTRACE(0x100,pParse,p,
("LEFT-JOIN simplifies to JOIN on term %d\n",i));
pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
unsetJoinExpr(p->pWhere, pItem->iCursor);
}
/* No futher action if this term of the FROM clause is no a subquery */
if( pSub==0 ) continue;
/* Catch mismatch in the declared columns of a view and the number of
** columns in the SELECT on the RHS */
if( pTab->nCol!=pSub->pEList->nExpr ){
sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
pTab->nCol, pTab->zName, pSub->pEList->nExpr);
goto select_end;
}
/* Do not try to flatten an aggregate subquery.
**
** Flattening an aggregate subquery is only possible if the outer query
** is not a join. But if the outer query is not a join, then the subquery
** will be implemented as a co-routine and there is no advantage to
** flattening in that case.
*/
if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
assert( pSub->pGroupBy==0 );
/* If the outer query contains a "complex" result set (that is,
** if the result set of the outer query uses functions or subqueries)
** and if the subquery contains an ORDER BY clause and if
** it will be implemented as a co-routine, then do not flatten. This
** restriction allows SQL constructs like this:
**
** SELECT expensive_function(x)
** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
**
** The expensive_function() is only computed on the 10 rows that
** are output, rather than every row of the table.
**
** The requirement that the outer query have a complex result set
** means that flattening does occur on simpler SQL constraints without
** the expensive_function() like:
**
** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
*/
if( pSub->pOrderBy!=0
&& i==0
&& (p->selFlags & SF_ComplexResult)!=0
&& (pTabList->nSrc==1
|| (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
){
continue;
}
if( flattenSubquery(pParse, p, i, isAgg) ){
if( pParse->nErr ) goto select_end;
/* This subquery can be absorbed into its parent. */
i = -1;
}
pTabList = p->pSrc;
if( db->mallocFailed ) goto select_end;
if( !IgnorableOrderby(pDest) ){
sSort.pOrderBy = p->pOrderBy;
}
}
#endif
#ifndef SQLITE_OMIT_COMPOUND_SELECT
/* Handle compound SELECT statements using the separate multiSelect()
** procedure.
*/
if( p->pPrior ){
rc = multiSelect(pParse, p, pDest);
#if SELECTTRACE_ENABLED
SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
sqlite3TreeViewSelect(0, p, 0);
}
#endif
if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
return rc;
}
#endif
/* Do the WHERE-clause constant propagation optimization if this is
** a join. No need to speed time on this operation for non-join queries
** as the equivalent optimization will be handled by query planner in
** sqlite3WhereBegin().
*/
if( pTabList->nSrc>1
&& OptimizationEnabled(db, SQLITE_PropagateConst)
&& propagateConstants(pParse, p)
){
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}else{
SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
}
#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
&& countOfViewOptimization(pParse, p)
){
if( db->mallocFailed ) goto select_end;
pEList = p->pEList;
pTabList = p->pSrc;
}
#endif
/* For each term in the FROM clause, do two things:
** (1) Authorized unreferenced tables
** (2) Generate code for all sub-queries
*/
for(i=0; i<pTabList->nSrc; i++){
struct SrcList_item *pItem = &pTabList->a[i];
SelectDest dest;
Select *pSub;
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
const char *zSavedAuthContext;
#endif
/* Issue SQLITE_READ authorizations with a fake column name for any
** tables that are referenced but from which no values are extracted.
** Examples of where these kinds of null SQLITE_READ authorizations
** would occur:
**
** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
**
** The fake column name is an empty string. It is possible for a table to
** have a column named by the empty string, in which case there is no way to
** distinguish between an unreferenced table and an actual reference to the
** "" column. The original design was for the fake column name to be a NULL,
** which would be unambiguous. But legacy authorization callbacks might
** assume the column name is non-NULL and segfault. The use of an empty
** string for the fake column name seems safer.
*/
if( pItem->colUsed==0 && pItem->zName!=0 ){
sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
}
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/* Generate code for all sub-queries in the FROM clause
*/
pSub = pItem->pSelect;
if( pSub==0 ) continue;
/* The code for a subquery should only be generated once, though it is
** technically harmless for it to be generated multiple times. The
** following assert() will detect if something changes to cause
** the same subquery to be coded multiple times, as a signal to the
** developers to try to optimize the situation.
**
** Update 2019-07-24:
** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40.
** The dbsqlfuzz fuzzer found a case where the same subquery gets
** coded twice. So this assert() now becomes a testcase(). It should
** be very rare, though.
*/
testcase( pItem->addrFillSub!=0 );
/* Increment Parse.nHeight by the height of the largest expression
** tree referred to by this, the parent select. The child select
** may contain expression trees of at most
** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
** more conservative than necessary, but much easier than enforcing
** an exact limit.
*/
pParse->nHeight += sqlite3SelectExprHeight(p);
/* Make copies of constant WHERE-clause terms in the outer query down
** inside the subquery. This can help the subquery to run more efficiently.
*/
if( OptimizationEnabled(db, SQLITE_PushDown)
&& pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
(pItem->fg.jointype & JT_OUTER)!=0)
){
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,
("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}else{
SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
}
zSavedAuthContext = pParse->zAuthContext;
pParse->zAuthContext = pItem->zName;
/* Generate code to implement the subquery
**
** The subquery is implemented as a co-routine if the subquery is
** guaranteed to be the outer loop (so that it does not need to be
** computed more than once)
**
** TODO: Are there other reasons beside (1) to use a co-routine
** implementation?
*/
if( i==0
&& (pTabList->nSrc==1
|| (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
){
/* Implement a co-routine that will return a single row of the result
** set on each invocation.
*/
int addrTop = sqlite3VdbeCurrentAddr(v)+1;
pItem->regReturn = ++pParse->nMem;
sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
VdbeComment((v, "%s", pItem->pTab->zName));
pItem->addrFillSub = addrTop;
sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
sqlite3Select(pParse, pSub, &dest);
pItem->pTab->nRowLogEst = pSub->nSelectRow;
pItem->fg.viaCoroutine = 1;
pItem->regResult = dest.iSdst;
sqlite3VdbeEndCoroutine(v, pItem->regReturn);
sqlite3VdbeJumpHere(v, addrTop-1);
sqlite3ClearTempRegCache(pParse);
}else{
/* Generate a subroutine that will fill an ephemeral table with
** the content of this subquery. pItem->addrFillSub will point
** to the address of the generated subroutine. pItem->regReturn
** is a register allocated to hold the subroutine return address
*/
int topAddr;
int onceAddr = 0;
int retAddr;
struct SrcList_item *pPrior;
testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */
pItem->regReturn = ++pParse->nMem;
topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
pItem->addrFillSub = topAddr+1;
if( pItem->fg.isCorrelated==0 ){
/* If the subquery is not correlated and if we are not inside of
** a trigger, then we only need to compute the value of the subquery
** once. */
onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
}else{
VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
}
pPrior = isSelfJoinView(pTabList, pItem);
if( pPrior ){
sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
assert( pPrior->pSelect!=0 );
pSub->nSelectRow = pPrior->pSelect->nSelectRow;
}else{
sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
sqlite3Select(pParse, pSub, &dest);
}
pItem->pTab->nRowLogEst = pSub->nSelectRow;
if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
VdbeComment((v, "end %s", pItem->pTab->zName));
sqlite3VdbeChangeP1(v, topAddr, retAddr);
sqlite3ClearTempRegCache(pParse);
}
if( db->mallocFailed ) goto select_end;
pParse->nHeight -= sqlite3SelectExprHeight(p);
pParse->zAuthContext = zSavedAuthContext;
#endif
}
/* Various elements of the SELECT copied into local variables for
** convenience */
pEList = p->pEList;
pWhere = p->pWhere;
pGroupBy = p->pGroupBy;
pHaving = p->pHaving;
sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
/* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
** if the select-list is the same as the ORDER BY list, then this query
** can be rewritten as a GROUP BY. In other words, this:
**
** SELECT DISTINCT xyz FROM ... ORDER BY xyz
**
** is transformed to:
**
** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
**
** The second form is preferred as a single index (or temp-table) may be
** used for both the ORDER BY and DISTINCT processing. As originally
** written the query must use a temp-table for at least one of the ORDER
** BY and DISTINCT, and an index or separate temp-table for the other.
*/
if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
&& sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
&& p->pWin==0
){
p->selFlags &= ~SF_Distinct;
pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
/* Notice that even thought SF_Distinct has been cleared from p->selFlags,
** the sDistinct.isTnct is still set. Hence, isTnct represents the
** original setting of the SF_Distinct flag, not the current setting */
assert( sDistinct.isTnct );
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}
/* If there is an ORDER BY clause, then create an ephemeral index to
** do the sorting. But this sorting ephemeral index might end up
** being unused if the data can be extracted in pre-sorted order.
** If that is the case, then the OP_OpenEphemeral instruction will be
** changed to an OP_Noop once we figure out that the sorting index is
** not needed. The sSort.addrSortIndex variable is used to facilitate
** that change.
*/
if( sSort.pOrderBy ){
KeyInfo *pKeyInfo;
pKeyInfo = sqlite3KeyInfoFromExprList(
pParse, sSort.pOrderBy, 0, pEList->nExpr);
sSort.iECursor = pParse->nTab++;
sSort.addrSortIndex =
sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
(char*)pKeyInfo, P4_KEYINFO
);
}else{
sSort.addrSortIndex = -1;
}
/* If the output is destined for a temporary table, open that table.
*/
if( pDest->eDest==SRT_EphemTab ){
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
}
/* Set the limiter.
*/
iEnd = sqlite3VdbeMakeLabel(pParse);
if( (p->selFlags & SF_FixedLimit)==0 ){
p->nSelectRow = 320; /* 4 billion rows */
}
computeLimitRegisters(pParse, p, iEnd);
if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
sSort.sortFlags |= SORTFLAG_UseSorter;
}
/* Open an ephemeral index to use for the distinct set.
*/
if( p->selFlags & SF_Distinct ){
sDistinct.tabTnct = pParse->nTab++;
sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
sDistinct.tabTnct, 0, 0,
(char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
P4_KEYINFO);
sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
}else{
sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
}
if( !isAgg && pGroupBy==0 ){
/* No aggregate functions and no GROUP BY clause */
u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
| (p->selFlags & SF_FixedLimit);
#ifndef SQLITE_OMIT_WINDOWFUNC
Window *pWin = p->pWin; /* Master window object (or NULL) */
if( pWin ){
sqlite3WindowCodeInit(pParse, pWin);
}
#endif
assert( WHERE_USE_LIMIT==SF_FixedLimit );
/* Begin the database scan. */
SELECTTRACE(1,pParse,p,("WhereBegin\n"));
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
p->pEList, wctrlFlags, p->nSelectRow);
if( pWInfo==0 ) goto select_end;
if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
}
if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
}
if( sSort.pOrderBy ){
sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
sSort.pOrderBy = 0;
}
}
/* If sorting index that was created by a prior OP_OpenEphemeral
** instruction ended up not being needed, then change the OP_OpenEphemeral
** into an OP_Noop.
*/
if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
}
assert( p->pEList==pEList );
#ifndef SQLITE_OMIT_WINDOWFUNC
if( pWin ){
int addrGosub = sqlite3VdbeMakeLabel(pParse);
int iCont = sqlite3VdbeMakeLabel(pParse);
int iBreak = sqlite3VdbeMakeLabel(pParse);
int regGosub = ++pParse->nMem;
sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
sqlite3VdbeResolveLabel(v, addrGosub);
VdbeNoopComment((v, "inner-loop subroutine"));
sSort.labelOBLopt = 0;
selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp1(v, OP_Return, regGosub);
VdbeComment((v, "end inner-loop subroutine"));
sqlite3VdbeResolveLabel(v, iBreak);
}else
#endif /* SQLITE_OMIT_WINDOWFUNC */
{
/* Use the standard inner loop. */
selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
sqlite3WhereContinueLabel(pWInfo),
sqlite3WhereBreakLabel(pWInfo));
/* End the database scan loop.
*/
sqlite3WhereEnd(pWInfo);
}
}else{
/* This case when there exist aggregate functions or a GROUP BY clause
** or both */
NameContext sNC; /* Name context for processing aggregate information */
int iAMem; /* First Mem address for storing current GROUP BY */
int iBMem; /* First Mem address for previous GROUP BY */
int iUseFlag; /* Mem address holding flag indicating that at least
** one row of the input to the aggregator has been
** processed */
int iAbortFlag; /* Mem address which causes query abort if positive */
int groupBySort; /* Rows come from source in GROUP BY order */
int addrEnd; /* End of processing for this SELECT */
int sortPTab = 0; /* Pseudotable used to decode sorting results */
int sortOut = 0; /* Output register from the sorter */
int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
/* Remove any and all aliases between the result set and the
** GROUP BY clause.
*/
if( pGroupBy ){
int k; /* Loop counter */
struct ExprList_item *pItem; /* For looping over expression in a list */
for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
pItem->u.x.iAlias = 0;
}
for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
pItem->u.x.iAlias = 0;
}
assert( 66==sqlite3LogEst(100) );
if( p->nSelectRow>66 ) p->nSelectRow = 66;
/* If there is both a GROUP BY and an ORDER BY clause and they are
** identical, then it may be possible to disable the ORDER BY clause
** on the grounds that the GROUP BY will cause elements to come out
** in the correct order. It also may not - the GROUP BY might use a
** database index that causes rows to be grouped together as required
** but not actually sorted. Either way, record the fact that the
** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
** variable. */
if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
int ii;
/* The GROUP BY processing doesn't care whether rows are delivered in
** ASC or DESC order - only that each group is returned contiguously.
** So set the ASC/DESC flags in the GROUP BY to match those in the
** ORDER BY to maximize the chances of rows being delivered in an
** order that makes the ORDER BY redundant. */
for(ii=0; ii<pGroupBy->nExpr; ii++){
u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC;
pGroupBy->a[ii].sortFlags = sortFlags;
}
if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
orderByGrp = 1;
}
}
}else{
assert( 0==sqlite3LogEst(1) );
p->nSelectRow = 0;
}
/* Create a label to jump to when we want to abort the query */
addrEnd = sqlite3VdbeMakeLabel(pParse);
/* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
** SELECT statement.
*/
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pParse;
sNC.pSrcList = pTabList;
sNC.uNC.pAggInfo = &sAggInfo;
VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
sAggInfo.mnReg = pParse->nMem+1;
sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
sAggInfo.pGroupBy = pGroupBy;
sqlite3ExprAnalyzeAggList(&sNC, pEList);
sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
if( pHaving ){
if( pGroupBy ){
assert( pWhere==p->pWhere );
assert( pHaving==p->pHaving );
assert( pGroupBy==p->pGroupBy );
havingToWhere(pParse, p);
pWhere = p->pWhere;
}
sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
}
sAggInfo.nAccumulator = sAggInfo.nColumn;
if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
}else{
minMaxFlag = WHERE_ORDERBY_NORMAL;
}
for(i=0; i<sAggInfo.nFunc; i++){
Expr *pExpr = sAggInfo.aFunc[i].pExpr;
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
sNC.ncFlags |= NC_InAggFunc;
sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
#ifndef SQLITE_OMIT_WINDOWFUNC
assert( !IsWindowFunc(pExpr) );
if( ExprHasProperty(pExpr, EP_WinFunc) ){
sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);
}
#endif
sNC.ncFlags &= ~NC_InAggFunc;
}
sAggInfo.mxReg = pParse->nMem;
if( db->mallocFailed ) goto select_end;
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
int ii;
SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
sqlite3TreeViewSelect(0, p, 0);
for(ii=0; ii<sAggInfo.nColumn; ii++){
sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
ii, sAggInfo.aCol[ii].iMem);
sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
}
for(ii=0; ii<sAggInfo.nFunc; ii++){
sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
ii, sAggInfo.aFunc[ii].iMem);
sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
}
}
#endif
/* Processing for aggregates with GROUP BY is very different and
** much more complex than aggregates without a GROUP BY.
*/
if( pGroupBy ){
KeyInfo *pKeyInfo; /* Keying information for the group by clause */
int addr1; /* A-vs-B comparision jump */
int addrOutputRow; /* Start of subroutine that outputs a result row */
int regOutputRow; /* Return address register for output subroutine */
int addrSetAbort; /* Set the abort flag and return */
int addrTopOfLoop; /* Top of the input loop */
int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
int addrReset; /* Subroutine for resetting the accumulator */
int regReset; /* Return address register for reset subroutine */
/* If there is a GROUP BY clause we might need a sorting index to
** implement it. Allocate that sorting index now. If it turns out
** that we do not need it after all, the OP_SorterOpen instruction
** will be converted into a Noop.
*/
sAggInfo.sortingIdx = pParse->nTab++;
pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);
addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
0, (char*)pKeyInfo, P4_KEYINFO);
/* Initialize memory locations used by GROUP BY aggregate processing
*/
iUseFlag = ++pParse->nMem;
iAbortFlag = ++pParse->nMem;
regOutputRow = ++pParse->nMem;
addrOutputRow = sqlite3VdbeMakeLabel(pParse);
regReset = ++pParse->nMem;
addrReset = sqlite3VdbeMakeLabel(pParse);
iAMem = pParse->nMem + 1;
pParse->nMem += pGroupBy->nExpr;
iBMem = pParse->nMem + 1;
pParse->nMem += pGroupBy->nExpr;
sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
VdbeComment((v, "clear abort flag"));
sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
/* Begin a loop that will extract all source rows in GROUP BY order.
** This might involve two separate loops with an OP_Sort in between, or
** it might be a single loop that uses an index to extract information
** in the right order to begin with.
*/
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
SELECTTRACE(1,pParse,p,("WhereBegin\n"));
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
);
if( pWInfo==0 ) goto select_end;
if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
/* The optimizer is able to deliver rows in group by order so
** we do not have to sort. The OP_OpenEphemeral table will be
** cancelled later because we still need to use the pKeyInfo
*/
groupBySort = 0;
}else{
/* Rows are coming out in undetermined order. We have to push
** each row into a sorting index, terminate the first loop,
** then loop over the sorting index in order to get the output
** in sorted order
*/
int regBase;
int regRecord;
int nCol;
int nGroupBy;
explainTempTable(pParse,
(sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
"DISTINCT" : "GROUP BY");
groupBySort = 1;
nGroupBy = pGroupBy->nExpr;
nCol = nGroupBy;
j = nGroupBy;
for(i=0; i<sAggInfo.nColumn; i++){
if( sAggInfo.aCol[i].iSorterColumn>=j ){
nCol++;
j++;
}
}
regBase = sqlite3GetTempRange(pParse, nCol);
sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
j = nGroupBy;
for(i=0; i<sAggInfo.nColumn; i++){
struct AggInfo_col *pCol = &sAggInfo.aCol[i];
if( pCol->iSorterColumn>=j ){
int r1 = j + regBase;
sqlite3ExprCodeGetColumnOfTable(v,
pCol->pTab, pCol->iTable, pCol->iColumn, r1);
j++;
}
}
regRecord = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
sqlite3ReleaseTempReg(pParse, regRecord);
sqlite3ReleaseTempRange(pParse, regBase, nCol);
sqlite3WhereEnd(pWInfo);
sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
sortOut = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
sAggInfo.useSortingIdx = 1;
}
/* If the index or temporary table used by the GROUP BY sort
** will naturally deliver rows in the order required by the ORDER BY
** clause, cancel the ephemeral table open coded earlier.
**
** This is an optimization - the correct answer should result regardless.
** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
** disable this optimization for testing purposes. */
if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
&& (groupBySort || sqlite3WhereIsSorted(pWInfo))
){
sSort.pOrderBy = 0;
sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
}
/* Evaluate the current GROUP BY terms and store in b0, b1, b2...
** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
** Then compare the current GROUP BY terms against the GROUP BY terms
** from the previous row currently stored in a0, a1, a2...
*/
addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
if( groupBySort ){
sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
sortOut, sortPTab);
}
for(j=0; j<pGroupBy->nExpr; j++){
if( groupBySort ){
sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
}else{
sAggInfo.directMode = 1;
sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
}
}
sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
(char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
addr1 = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
/* Generate code that runs whenever the GROUP BY changes.
** Changes in the GROUP BY are detected by the previous code
** block. If there were no changes, this block is skipped.
**
** This code copies current group by terms in b0,b1,b2,...
** over to a0,a1,a2. It then calls the output subroutine
** and resets the aggregate accumulator registers in preparation
** for the next GROUP BY batch.
*/
sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
VdbeComment((v, "output one row"));
sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
VdbeComment((v, "check abort flag"));
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
VdbeComment((v, "reset accumulator"));
/* Update the aggregate accumulators based on the content of
** the current row
*/
sqlite3VdbeJumpHere(v, addr1);
updateAccumulator(pParse, iUseFlag, &sAggInfo);
sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
VdbeComment((v, "indicate data in accumulator"));
/* End of the loop
*/
if( groupBySort ){
sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
VdbeCoverage(v);
}else{
sqlite3WhereEnd(pWInfo);
sqlite3VdbeChangeToNoop(v, addrSortingIdx);
}
/* Output the final row of result
*/
sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
VdbeComment((v, "output final row"));
/* Jump over the subroutines
*/
sqlite3VdbeGoto(v, addrEnd);
/* Generate a subroutine that outputs a single row of the result
** set. This subroutine first looks at the iUseFlag. If iUseFlag
** is less than or equal to zero, the subroutine is a no-op. If
** the processing calls for the query to abort, this subroutine
** increments the iAbortFlag memory location before returning in
** order to signal the caller to abort.
*/
addrSetAbort = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
VdbeComment((v, "set abort flag"));
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
sqlite3VdbeResolveLabel(v, addrOutputRow);
addrOutputRow = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
VdbeCoverage(v);
VdbeComment((v, "Groupby result generator entry point"));
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
finalizeAggFunctions(pParse, &sAggInfo);
sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
selectInnerLoop(pParse, p, -1, &sSort,
&sDistinct, pDest,
addrOutputRow+1, addrSetAbort);
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
VdbeComment((v, "end groupby result generator"));
/* Generate a subroutine that will reset the group-by accumulator
*/
sqlite3VdbeResolveLabel(v, addrReset);
resetAccumulator(pParse, &sAggInfo);
sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
VdbeComment((v, "indicate accumulator empty"));
sqlite3VdbeAddOp1(v, OP_Return, regReset);
} /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
else {
#ifndef SQLITE_OMIT_BTREECOUNT
Table *pTab;
if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
/* If isSimpleCount() returns a pointer to a Table structure, then
** the SQL statement is of the form:
**
** SELECT count(*) FROM <tbl>
**
** where the Table structure returned represents table <tbl>.
**
** This statement is so common that it is optimized specially. The
** OP_Count instruction is executed either on the intkey table that
** contains the data for table <tbl> or on one of its indexes. It
** is better to execute the op on an index, as indexes are almost
** always spread across less pages than their corresponding tables.
*/
const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
Index *pIdx; /* Iterator variable */
KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
Index *pBest = 0; /* Best index found so far */
int iRoot = pTab->tnum; /* Root page of scanned b-tree */
sqlite3CodeVerifySchema(pParse, iDb);
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
/* Search for the index that has the lowest scan cost.
**
** (2011-04-15) Do not do a full scan of an unordered index.
**
** (2013-10-03) Do not count the entries in a partial index.
**
** In practice the KeyInfo structure will not be used. It is only
** passed to keep OP_OpenRead happy.
*/
if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
if( pIdx->bUnordered==0
&& pIdx->szIdxRow<pTab->szTabRow
&& pIdx->pPartIdxWhere==0
&& (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
){
pBest = pIdx;
}
}
if( pBest ){
iRoot = pBest->tnum;
pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
}
/* Open a read-only cursor, execute the OP_Count, close the cursor. */
sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
if( pKeyInfo ){
sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
}
sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
sqlite3VdbeAddOp1(v, OP_Close, iCsr);
explainSimpleCount(pParse, pTab, pBest);
}else
#endif /* SQLITE_OMIT_BTREECOUNT */
{
int regAcc = 0; /* "populate accumulators" flag */
/* If there are accumulator registers but no min() or max() functions
** without FILTER clauses, allocate register regAcc. Register regAcc
** will contain 0 the first time the inner loop runs, and 1 thereafter.
** The code generated by updateAccumulator() uses this to ensure
** that the accumulator registers are (a) updated only once if
** there are no min() or max functions or (b) always updated for the
** first row visited by the aggregate, so that they are updated at
** least once even if the FILTER clause means the min() or max()
** function visits zero rows. */
if( sAggInfo.nAccumulator ){
for(i=0; i<sAggInfo.nFunc; i++){
if( ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_WinFunc) ) continue;
if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break;
}
if( i==sAggInfo.nFunc ){
regAcc = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
}
}
/* This case runs if the aggregate has no GROUP BY clause. The
** processing is much simpler since there is only a single row
** of output.
*/
assert( p->pGroupBy==0 );
resetAccumulator(pParse, &sAggInfo);
/* If this query is a candidate for the min/max optimization, then
** minMaxFlag will have been previously set to either
** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
** be an appropriate ORDER BY expression for the optimization.
*/
assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
SELECTTRACE(1,pParse,p,("WhereBegin\n"));
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
0, minMaxFlag, 0);
if( pWInfo==0 ){
goto select_end;
}
updateAccumulator(pParse, regAcc, &sAggInfo);
if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
if( sqlite3WhereIsOrdered(pWInfo)>0 ){
sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
VdbeComment((v, "%s() by index",
(minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
}
sqlite3WhereEnd(pWInfo);
finalizeAggFunctions(pParse, &sAggInfo);
}
sSort.pOrderBy = 0;
sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
selectInnerLoop(pParse, p, -1, 0, 0,
pDest, addrEnd, addrEnd);
}
sqlite3VdbeResolveLabel(v, addrEnd);
} /* endif aggregate query */
if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
explainTempTable(pParse, "DISTINCT");
}
/* If there is an ORDER BY clause, then we need to sort the results
** and send them to the callback one by one.
*/
if( sSort.pOrderBy ){
explainTempTable(pParse,
sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
assert( p->pEList==pEList );
generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
}
/* Jump here to skip this query
*/
sqlite3VdbeResolveLabel(v, iEnd);
/* The SELECT has been coded. If there is an error in the Parse structure,
** set the return code to 1. Otherwise 0. */
rc = (pParse->nErr>0);
/* Control jumps to here if an error is encountered above, or upon
** successful coding of the SELECT.
*/
select_end:
sqlite3ExprListDelete(db, pMinMaxOrderBy);
sqlite3DbFree(db, sAggInfo.aCol);
sqlite3DbFree(db, sAggInfo.aFunc);
#if SELECTTRACE_ENABLED
SELECTTRACE(0x1,pParse,p,("end processing\n"));
if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
sqlite3TreeViewSelect(0, p, 0);
}
#endif
ExplainQueryPlanPop(pParse);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_1324_2 |
crossvul-cpp_data_bad_5337_0 | /* Generic associative array implementation.
*
* See Documentation/assoc_array.txt for information.
*
* Copyright (C) 2013 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.
*/
//#define DEBUG
#include <linux/rcupdate.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/assoc_array_priv.h>
/*
* Iterate over an associative array. The caller must hold the RCU read lock
* or better.
*/
static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root,
const struct assoc_array_ptr *stop,
int (*iterator)(const void *leaf,
void *iterator_data),
void *iterator_data)
{
const struct assoc_array_shortcut *shortcut;
const struct assoc_array_node *node;
const struct assoc_array_ptr *cursor, *ptr, *parent;
unsigned long has_meta;
int slot, ret;
cursor = root;
begin_node:
if (assoc_array_ptr_is_shortcut(cursor)) {
/* Descend through a shortcut */
shortcut = assoc_array_ptr_to_shortcut(cursor);
smp_read_barrier_depends();
cursor = ACCESS_ONCE(shortcut->next_node);
}
node = assoc_array_ptr_to_node(cursor);
smp_read_barrier_depends();
slot = 0;
/* We perform two passes of each node.
*
* The first pass does all the leaves in this node. This means we
* don't miss any leaves if the node is split up by insertion whilst
* we're iterating over the branches rooted here (we may, however, see
* some leaves twice).
*/
has_meta = 0;
for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = ACCESS_ONCE(node->slots[slot]);
has_meta |= (unsigned long)ptr;
if (ptr && assoc_array_ptr_is_leaf(ptr)) {
/* We need a barrier between the read of the pointer
* and dereferencing the pointer - but only if we are
* actually going to dereference it.
*/
smp_read_barrier_depends();
/* Invoke the callback */
ret = iterator(assoc_array_ptr_to_leaf(ptr),
iterator_data);
if (ret)
return ret;
}
}
/* The second pass attends to all the metadata pointers. If we follow
* one of these we may find that we don't come back here, but rather go
* back to a replacement node with the leaves in a different layout.
*
* We are guaranteed to make progress, however, as the slot number for
* a particular portion of the key space cannot change - and we
* continue at the back pointer + 1.
*/
if (!(has_meta & ASSOC_ARRAY_PTR_META_TYPE))
goto finished_node;
slot = 0;
continue_node:
node = assoc_array_ptr_to_node(cursor);
smp_read_barrier_depends();
for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = ACCESS_ONCE(node->slots[slot]);
if (assoc_array_ptr_is_meta(ptr)) {
cursor = ptr;
goto begin_node;
}
}
finished_node:
/* Move up to the parent (may need to skip back over a shortcut) */
parent = ACCESS_ONCE(node->back_pointer);
slot = node->parent_slot;
if (parent == stop)
return 0;
if (assoc_array_ptr_is_shortcut(parent)) {
shortcut = assoc_array_ptr_to_shortcut(parent);
smp_read_barrier_depends();
cursor = parent;
parent = ACCESS_ONCE(shortcut->back_pointer);
slot = shortcut->parent_slot;
if (parent == stop)
return 0;
}
/* Ascend to next slot in parent node */
cursor = parent;
slot++;
goto continue_node;
}
/**
* assoc_array_iterate - Pass all objects in the array to a callback
* @array: The array to iterate over.
* @iterator: The callback function.
* @iterator_data: Private data for the callback function.
*
* Iterate over all the objects in an associative array. Each one will be
* presented to the iterator function.
*
* If the array is being modified concurrently with the iteration then it is
* possible that some objects in the array will be passed to the iterator
* callback more than once - though every object should be passed at least
* once. If this is undesirable then the caller must lock against modification
* for the duration of this function.
*
* The function will return 0 if no objects were in the array or else it will
* return the result of the last iterator function called. Iteration stops
* immediately if any call to the iteration function results in a non-zero
* return.
*
* The caller should hold the RCU read lock or better if concurrent
* modification is possible.
*/
int assoc_array_iterate(const struct assoc_array *array,
int (*iterator)(const void *object,
void *iterator_data),
void *iterator_data)
{
struct assoc_array_ptr *root = ACCESS_ONCE(array->root);
if (!root)
return 0;
return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data);
}
enum assoc_array_walk_status {
assoc_array_walk_tree_empty,
assoc_array_walk_found_terminal_node,
assoc_array_walk_found_wrong_shortcut,
};
struct assoc_array_walk_result {
struct {
struct assoc_array_node *node; /* Node in which leaf might be found */
int level;
int slot;
} terminal_node;
struct {
struct assoc_array_shortcut *shortcut;
int level;
int sc_level;
unsigned long sc_segments;
unsigned long dissimilarity;
} wrong_shortcut;
};
/*
* Navigate through the internal tree looking for the closest node to the key.
*/
static enum assoc_array_walk_status
assoc_array_walk(const struct assoc_array *array,
const struct assoc_array_ops *ops,
const void *index_key,
struct assoc_array_walk_result *result)
{
struct assoc_array_shortcut *shortcut;
struct assoc_array_node *node;
struct assoc_array_ptr *cursor, *ptr;
unsigned long sc_segments, dissimilarity;
unsigned long segments;
int level, sc_level, next_sc_level;
int slot;
pr_devel("-->%s()\n", __func__);
cursor = ACCESS_ONCE(array->root);
if (!cursor)
return assoc_array_walk_tree_empty;
level = 0;
/* Use segments from the key for the new leaf to navigate through the
* internal tree, skipping through nodes and shortcuts that are on
* route to the destination. Eventually we'll come to a slot that is
* either empty or contains a leaf at which point we've found a node in
* which the leaf we're looking for might be found or into which it
* should be inserted.
*/
jumped:
segments = ops->get_key_chunk(index_key, level);
pr_devel("segments[%d]: %lx\n", level, segments);
if (assoc_array_ptr_is_shortcut(cursor))
goto follow_shortcut;
consider_node:
node = assoc_array_ptr_to_node(cursor);
smp_read_barrier_depends();
slot = segments >> (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
slot &= ASSOC_ARRAY_FAN_MASK;
ptr = ACCESS_ONCE(node->slots[slot]);
pr_devel("consider slot %x [ix=%d type=%lu]\n",
slot, level, (unsigned long)ptr & 3);
if (!assoc_array_ptr_is_meta(ptr)) {
/* The node doesn't have a node/shortcut pointer in the slot
* corresponding to the index key that we have to follow.
*/
result->terminal_node.node = node;
result->terminal_node.level = level;
result->terminal_node.slot = slot;
pr_devel("<--%s() = terminal_node\n", __func__);
return assoc_array_walk_found_terminal_node;
}
if (assoc_array_ptr_is_node(ptr)) {
/* There is a pointer to a node in the slot corresponding to
* this index key segment, so we need to follow it.
*/
cursor = ptr;
level += ASSOC_ARRAY_LEVEL_STEP;
if ((level & ASSOC_ARRAY_KEY_CHUNK_MASK) != 0)
goto consider_node;
goto jumped;
}
/* There is a shortcut in the slot corresponding to the index key
* segment. We follow the shortcut if its partial index key matches
* this leaf's. Otherwise we need to split the shortcut.
*/
cursor = ptr;
follow_shortcut:
shortcut = assoc_array_ptr_to_shortcut(cursor);
smp_read_barrier_depends();
pr_devel("shortcut to %d\n", shortcut->skip_to_level);
sc_level = level + ASSOC_ARRAY_LEVEL_STEP;
BUG_ON(sc_level > shortcut->skip_to_level);
do {
/* Check the leaf against the shortcut's index key a word at a
* time, trimming the final word (the shortcut stores the index
* key completely from the root to the shortcut's target).
*/
if ((sc_level & ASSOC_ARRAY_KEY_CHUNK_MASK) == 0)
segments = ops->get_key_chunk(index_key, sc_level);
sc_segments = shortcut->index_key[sc_level >> ASSOC_ARRAY_KEY_CHUNK_SHIFT];
dissimilarity = segments ^ sc_segments;
if (round_up(sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE) > shortcut->skip_to_level) {
/* Trim segments that are beyond the shortcut */
int shift = shortcut->skip_to_level & ASSOC_ARRAY_KEY_CHUNK_MASK;
dissimilarity &= ~(ULONG_MAX << shift);
next_sc_level = shortcut->skip_to_level;
} else {
next_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE;
next_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
}
if (dissimilarity != 0) {
/* This shortcut points elsewhere */
result->wrong_shortcut.shortcut = shortcut;
result->wrong_shortcut.level = level;
result->wrong_shortcut.sc_level = sc_level;
result->wrong_shortcut.sc_segments = sc_segments;
result->wrong_shortcut.dissimilarity = dissimilarity;
return assoc_array_walk_found_wrong_shortcut;
}
sc_level = next_sc_level;
} while (sc_level < shortcut->skip_to_level);
/* The shortcut matches the leaf's index to this point. */
cursor = ACCESS_ONCE(shortcut->next_node);
if (((level ^ sc_level) & ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) {
level = sc_level;
goto jumped;
} else {
level = sc_level;
goto consider_node;
}
}
/**
* assoc_array_find - Find an object by index key
* @array: The associative array to search.
* @ops: The operations to use.
* @index_key: The key to the object.
*
* Find an object in an associative array by walking through the internal tree
* to the node that should contain the object and then searching the leaves
* there. NULL is returned if the requested object was not found in the array.
*
* The caller must hold the RCU read lock or better.
*/
void *assoc_array_find(const struct assoc_array *array,
const struct assoc_array_ops *ops,
const void *index_key)
{
struct assoc_array_walk_result result;
const struct assoc_array_node *node;
const struct assoc_array_ptr *ptr;
const void *leaf;
int slot;
if (assoc_array_walk(array, ops, index_key, &result) !=
assoc_array_walk_found_terminal_node)
return NULL;
node = result.terminal_node.node;
smp_read_barrier_depends();
/* If the target key is available to us, it's has to be pointed to by
* the terminal node.
*/
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = ACCESS_ONCE(node->slots[slot]);
if (ptr && assoc_array_ptr_is_leaf(ptr)) {
/* We need a barrier between the read of the pointer
* and dereferencing the pointer - but only if we are
* actually going to dereference it.
*/
leaf = assoc_array_ptr_to_leaf(ptr);
smp_read_barrier_depends();
if (ops->compare_object(leaf, index_key))
return (void *)leaf;
}
}
return NULL;
}
/*
* Destructively iterate over an associative array. The caller must prevent
* other simultaneous accesses.
*/
static void assoc_array_destroy_subtree(struct assoc_array_ptr *root,
const struct assoc_array_ops *ops)
{
struct assoc_array_shortcut *shortcut;
struct assoc_array_node *node;
struct assoc_array_ptr *cursor, *parent = NULL;
int slot = -1;
pr_devel("-->%s()\n", __func__);
cursor = root;
if (!cursor) {
pr_devel("empty\n");
return;
}
move_to_meta:
if (assoc_array_ptr_is_shortcut(cursor)) {
/* Descend through a shortcut */
pr_devel("[%d] shortcut\n", slot);
BUG_ON(!assoc_array_ptr_is_shortcut(cursor));
shortcut = assoc_array_ptr_to_shortcut(cursor);
BUG_ON(shortcut->back_pointer != parent);
BUG_ON(slot != -1 && shortcut->parent_slot != slot);
parent = cursor;
cursor = shortcut->next_node;
slot = -1;
BUG_ON(!assoc_array_ptr_is_node(cursor));
}
pr_devel("[%d] node\n", slot);
node = assoc_array_ptr_to_node(cursor);
BUG_ON(node->back_pointer != parent);
BUG_ON(slot != -1 && node->parent_slot != slot);
slot = 0;
continue_node:
pr_devel("Node %p [back=%p]\n", node, node->back_pointer);
for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
struct assoc_array_ptr *ptr = node->slots[slot];
if (!ptr)
continue;
if (assoc_array_ptr_is_meta(ptr)) {
parent = cursor;
cursor = ptr;
goto move_to_meta;
}
if (ops) {
pr_devel("[%d] free leaf\n", slot);
ops->free_object(assoc_array_ptr_to_leaf(ptr));
}
}
parent = node->back_pointer;
slot = node->parent_slot;
pr_devel("free node\n");
kfree(node);
if (!parent)
return; /* Done */
/* Move back up to the parent (may need to free a shortcut on
* the way up) */
if (assoc_array_ptr_is_shortcut(parent)) {
shortcut = assoc_array_ptr_to_shortcut(parent);
BUG_ON(shortcut->next_node != cursor);
cursor = parent;
parent = shortcut->back_pointer;
slot = shortcut->parent_slot;
pr_devel("free shortcut\n");
kfree(shortcut);
if (!parent)
return;
BUG_ON(!assoc_array_ptr_is_node(parent));
}
/* Ascend to next slot in parent node */
pr_devel("ascend to %p[%d]\n", parent, slot);
cursor = parent;
node = assoc_array_ptr_to_node(cursor);
slot++;
goto continue_node;
}
/**
* assoc_array_destroy - Destroy an associative array
* @array: The array to destroy.
* @ops: The operations to use.
*
* Discard all metadata and free all objects in an associative array. The
* array will be empty and ready to use again upon completion. This function
* cannot fail.
*
* The caller must prevent all other accesses whilst this takes place as no
* attempt is made to adjust pointers gracefully to permit RCU readlock-holding
* accesses to continue. On the other hand, no memory allocation is required.
*/
void assoc_array_destroy(struct assoc_array *array,
const struct assoc_array_ops *ops)
{
assoc_array_destroy_subtree(array->root, ops);
array->root = NULL;
}
/*
* Handle insertion into an empty tree.
*/
static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit)
{
struct assoc_array_node *new_n0;
pr_devel("-->%s()\n", __func__);
new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n0)
return false;
edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
edit->leaf_p = &new_n0->slots[0];
edit->adjust_count_on = new_n0;
edit->set[0].ptr = &edit->array->root;
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
pr_devel("<--%s() = ok [no root]\n", __func__);
return true;
}
/*
* Handle insertion into a terminal node.
*/
static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
const struct assoc_array_ops *ops,
const void *index_key,
struct assoc_array_walk_result *result)
{
struct assoc_array_shortcut *shortcut, *new_s0;
struct assoc_array_node *node, *new_n0, *new_n1, *side;
struct assoc_array_ptr *ptr;
unsigned long dissimilarity, base_seg, blank;
size_t keylen;
bool have_meta;
int level, diff;
int slot, next_slot, free_slot, i, j;
node = result->terminal_node.node;
level = result->terminal_node.level;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
pr_devel("-->%s()\n", __func__);
/* We arrived at a node which doesn't have an onward node or shortcut
* pointer that we have to follow. This means that (a) the leaf we
* want must go here (either by insertion or replacement) or (b) we
* need to split this node and insert in one of the fragments.
*/
free_slot = -1;
/* Firstly, we have to check the leaves in this node to see if there's
* a matching one we should replace in place.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (!ptr) {
free_slot = i;
continue;
}
if (ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) {
pr_devel("replace in slot %d\n", i);
edit->leaf_p = &node->slots[i];
edit->dead_leaf = node->slots[i];
pr_devel("<--%s() = ok [replace]\n", __func__);
return true;
}
}
/* If there is a free slot in this node then we can just insert the
* leaf here.
*/
if (free_slot >= 0) {
pr_devel("insert in free slot %d\n", free_slot);
edit->leaf_p = &node->slots[free_slot];
edit->adjust_count_on = node;
pr_devel("<--%s() = ok [insert]\n", __func__);
return true;
}
/* The node has no spare slots - so we're either going to have to split
* it or insert another node before it.
*
* Whatever, we're going to need at least two new nodes - so allocate
* those now. We may also need a new shortcut, but we deal with that
* when we need it.
*/
new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n0)
return false;
edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n1)
return false;
edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
/* We need to find out how similar the leaves are. */
pr_devel("no spare slots\n");
have_meta = false;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (assoc_array_ptr_is_meta(ptr)) {
edit->segment_cache[i] = 0xff;
have_meta = true;
continue;
}
base_seg = ops->get_object_key_chunk(
assoc_array_ptr_to_leaf(ptr), level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
if (have_meta) {
pr_devel("have meta\n");
goto split_node;
}
/* The node contains only leaves */
dissimilarity = 0;
base_seg = edit->segment_cache[0];
for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
dissimilarity |= edit->segment_cache[i] ^ base_seg;
pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
/* The old leaves all cluster in the same slot. We will need
* to insert a shortcut if the new node wants to cluster with them.
*/
if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
goto all_leaves_cluster_together;
/* Otherwise we can just insert a new node ahead of the old
* one.
*/
goto present_leaves_cluster_but_not_new_leaf;
}
split_node:
pr_devel("split node\n");
/* We need to split the current node; we know that the node doesn't
* simply contain a full set of leaves that cluster together (it
* contains meta pointers and/or non-clustering leaves).
*
* We need to expel at least two leaves out of a set consisting of the
* leaves in the node and the new leaf.
*
* We need a new node (n0) to replace the current one and a new node to
* take the expelled nodes (n1).
*/
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
do_split_node:
pr_devel("do_split_node\n");
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->nr_leaves_on_branch = 0;
/* Begin by finding two matching leaves. There have to be at least two
* that match - even if there are meta pointers - because any leaf that
* would match a slot with a meta pointer in it must be somewhere
* behind that meta pointer and cannot be here. Further, given N
* remaining leaf slots, we now have N+1 leaves to go in them.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
slot = edit->segment_cache[i];
if (slot != 0xff)
for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
if (edit->segment_cache[j] == slot)
goto found_slot_for_multiple_occupancy;
}
found_slot_for_multiple_occupancy:
pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
new_n1->parent_slot = slot;
/* Metadata pointers cannot change slot */
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
if (assoc_array_ptr_is_meta(node->slots[i]))
new_n0->slots[i] = node->slots[i];
else
new_n0->slots[i] = NULL;
BUG_ON(new_n0->slots[slot] != NULL);
new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
/* Filter the leaf pointers between the new nodes */
free_slot = -1;
next_slot = 0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (assoc_array_ptr_is_meta(node->slots[i]))
continue;
if (edit->segment_cache[i] == slot) {
new_n1->slots[next_slot++] = node->slots[i];
new_n1->nr_leaves_on_branch++;
} else {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
new_n0->slots[free_slot] = node->slots[i];
}
}
pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
edit->leaf_p = &new_n0->slots[free_slot];
edit->adjust_count_on = new_n0;
} else {
edit->leaf_p = &new_n1->slots[next_slot++];
edit->adjust_count_on = new_n1;
}
BUG_ON(next_slot <= 1);
edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (edit->segment_cache[i] == 0xff) {
ptr = node->slots[i];
BUG_ON(assoc_array_ptr_is_leaf(ptr));
if (assoc_array_ptr_is_node(ptr)) {
side = assoc_array_ptr_to_node(ptr);
edit->set_backpointers[i] = &side->back_pointer;
} else {
shortcut = assoc_array_ptr_to_shortcut(ptr);
edit->set_backpointers[i] = &shortcut->back_pointer;
}
}
}
ptr = node->back_pointer;
if (!ptr)
edit->set[0].ptr = &edit->array->root;
else if (assoc_array_ptr_is_node(ptr))
edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
else
edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [split node]\n", __func__);
return true;
present_leaves_cluster_but_not_new_leaf:
/* All the old leaves cluster in the same slot, but the new leaf wants
* to go into a different slot, so we create a new node to hold the new
* leaf and a pointer to a new node holding all the old leaves.
*/
pr_devel("present leaves cluster but not new leaf\n");
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = edit->segment_cache[0];
new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch;
edit->adjust_count_on = new_n0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
new_n1->slots[i] = node->slots[i];
new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0);
edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]];
edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot];
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [insert node before]\n", __func__);
return true;
all_leaves_cluster_together:
/* All the leaves, new and old, want to cluster together in this node
* in the same slot, so we have to replace this node with a shortcut to
* skip over the identical parts of the key and then place a pair of
* nodes, one inside the other, at the end of the shortcut and
* distribute the keys between them.
*
* Firstly we need to work out where the leaves start diverging as a
* bit position into their keys so that we know how big the shortcut
* needs to be.
*
* We only need to make a single pass of N of the N+1 leaves because if
* any keys differ between themselves at bit X then at least one of
* them must also differ with the base key at bit X or before.
*/
pr_devel("all leaves cluster together\n");
diff = INT_MAX;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
index_key);
if (x < diff) {
BUG_ON(x < 0);
diff = x;
}
}
BUG_ON(diff == INT_MAX);
BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s0)
return false;
edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
new_s0->back_pointer = node->back_pointer;
new_s0->parent_slot = node->parent_slot;
new_s0->next_node = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
new_n0->parent_slot = 0;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
BUG_ON(level <= 0);
for (i = 0; i < keylen; i++)
new_s0->index_key[i] =
ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
new_s0->index_key[keylen - 1] &= ~blank;
/* This now reduces to a node splitting exercise for which we'll need
* to regenerate the disparity table.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
base_seg = ops->get_key_chunk(index_key, level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
goto do_split_node;
}
/*
* Handle insertion into the middle of a shortcut.
*/
static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit,
const struct assoc_array_ops *ops,
struct assoc_array_walk_result *result)
{
struct assoc_array_shortcut *shortcut, *new_s0, *new_s1;
struct assoc_array_node *node, *new_n0, *side;
unsigned long sc_segments, dissimilarity, blank;
size_t keylen;
int level, sc_level, diff;
int sc_slot;
shortcut = result->wrong_shortcut.shortcut;
level = result->wrong_shortcut.level;
sc_level = result->wrong_shortcut.sc_level;
sc_segments = result->wrong_shortcut.sc_segments;
dissimilarity = result->wrong_shortcut.dissimilarity;
pr_devel("-->%s(ix=%d dis=%lx scix=%d)\n",
__func__, level, dissimilarity, sc_level);
/* We need to split a shortcut and insert a node between the two
* pieces. Zero-length pieces will be dispensed with entirely.
*
* First of all, we need to find out in which level the first
* difference was.
*/
diff = __ffs(dissimilarity);
diff &= ~ASSOC_ARRAY_LEVEL_STEP_MASK;
diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK;
pr_devel("diff=%d\n", diff);
if (!shortcut->back_pointer) {
edit->set[0].ptr = &edit->array->root;
} else if (assoc_array_ptr_is_node(shortcut->back_pointer)) {
node = assoc_array_ptr_to_node(shortcut->back_pointer);
edit->set[0].ptr = &node->slots[shortcut->parent_slot];
} else {
BUG();
}
edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut);
/* Create a new node now since we're going to need it anyway */
new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n0)
return false;
edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
edit->adjust_count_on = new_n0;
/* Insert a new shortcut before the new node if this segment isn't of
* zero length - otherwise we just connect the new node directly to the
* parent.
*/
level += ASSOC_ARRAY_LEVEL_STEP;
if (diff > level) {
pr_devel("pre-shortcut %d...%d\n", level, diff);
keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s0)
return false;
edit->new_meta[1] = assoc_array_shortcut_to_ptr(new_s0);
edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
new_s0->back_pointer = shortcut->back_pointer;
new_s0->parent_slot = shortcut->parent_slot;
new_s0->next_node = assoc_array_node_to_ptr(new_n0);
new_s0->skip_to_level = diff;
new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
new_n0->parent_slot = 0;
memcpy(new_s0->index_key, shortcut->index_key,
keylen * sizeof(unsigned long));
blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank);
new_s0->index_key[keylen - 1] &= ~blank;
} else {
pr_devel("no pre-shortcut\n");
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = shortcut->back_pointer;
new_n0->parent_slot = shortcut->parent_slot;
}
side = assoc_array_ptr_to_node(shortcut->next_node);
new_n0->nr_leaves_on_branch = side->nr_leaves_on_branch;
/* We need to know which slot in the new node is going to take a
* metadata pointer.
*/
sc_slot = sc_segments >> (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
sc_slot &= ASSOC_ARRAY_FAN_MASK;
pr_devel("new slot %lx >> %d -> %d\n",
sc_segments, diff & ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot);
/* Determine whether we need to follow the new node with a replacement
* for the current shortcut. We could in theory reuse the current
* shortcut if its parent slot number doesn't change - but that's a
* 1-in-16 chance so not worth expending the code upon.
*/
level = diff + ASSOC_ARRAY_LEVEL_STEP;
if (level < shortcut->skip_to_level) {
pr_devel("post-shortcut %d...%d\n", level, shortcut->skip_to_level);
keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s1 = kzalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s1)
return false;
edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s1);
new_s1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_s1->parent_slot = sc_slot;
new_s1->next_node = shortcut->next_node;
new_s1->skip_to_level = shortcut->skip_to_level;
new_n0->slots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1);
memcpy(new_s1->index_key, shortcut->index_key,
keylen * sizeof(unsigned long));
edit->set[1].ptr = &side->back_pointer;
edit->set[1].to = assoc_array_shortcut_to_ptr(new_s1);
} else {
pr_devel("no post-shortcut\n");
/* We don't have to replace the pointed-to node as long as we
* use memory barriers to make sure the parent slot number is
* changed before the back pointer (the parent slot number is
* irrelevant to the old parent shortcut).
*/
new_n0->slots[sc_slot] = shortcut->next_node;
edit->set_parent_slot[0].p = &side->parent_slot;
edit->set_parent_slot[0].to = sc_slot;
edit->set[1].ptr = &side->back_pointer;
edit->set[1].to = assoc_array_node_to_ptr(new_n0);
}
/* Install the new leaf in a spare slot in the new node. */
if (sc_slot == 0)
edit->leaf_p = &new_n0->slots[1];
else
edit->leaf_p = &new_n0->slots[0];
pr_devel("<--%s() = ok [split shortcut]\n", __func__);
return edit;
}
/**
* assoc_array_insert - Script insertion of an object into an associative array
* @array: The array to insert into.
* @ops: The operations to use.
* @index_key: The key to insert at.
* @object: The object to insert.
*
* Precalculate and preallocate a script for the insertion or replacement of an
* object in an associative array. This results in an edit script that can
* either be applied or cancelled.
*
* The function returns a pointer to an edit script or -ENOMEM.
*
* The caller should lock against other modifications and must continue to hold
* the lock until assoc_array_apply_edit() has been called.
*
* Accesses to the tree may take place concurrently with this function,
* provided they hold the RCU read lock.
*/
struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
const struct assoc_array_ops *ops,
const void *index_key,
void *object)
{
struct assoc_array_walk_result result;
struct assoc_array_edit *edit;
pr_devel("-->%s()\n", __func__);
/* The leaf pointer we're given must not have the bottom bit set as we
* use those for type-marking the pointer. NULL pointers are also not
* allowed as they indicate an empty slot but we have to allow them
* here as they can be updated later.
*/
BUG_ON(assoc_array_ptr_is_meta(object));
edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
if (!edit)
return ERR_PTR(-ENOMEM);
edit->array = array;
edit->ops = ops;
edit->leaf = assoc_array_leaf_to_ptr(object);
edit->adjust_count_by = 1;
switch (assoc_array_walk(array, ops, index_key, &result)) {
case assoc_array_walk_tree_empty:
/* Allocate a root node if there isn't one yet */
if (!assoc_array_insert_in_empty_tree(edit))
goto enomem;
return edit;
case assoc_array_walk_found_terminal_node:
/* We found a node that doesn't have a node/shortcut pointer in
* the slot corresponding to the index key that we have to
* follow.
*/
if (!assoc_array_insert_into_terminal_node(edit, ops, index_key,
&result))
goto enomem;
return edit;
case assoc_array_walk_found_wrong_shortcut:
/* We found a shortcut that didn't match our key in a slot we
* needed to follow.
*/
if (!assoc_array_insert_mid_shortcut(edit, ops, &result))
goto enomem;
return edit;
}
enomem:
/* Clean up after an out of memory error */
pr_devel("enomem\n");
assoc_array_cancel_edit(edit);
return ERR_PTR(-ENOMEM);
}
/**
* assoc_array_insert_set_object - Set the new object pointer in an edit script
* @edit: The edit script to modify.
* @object: The object pointer to set.
*
* Change the object to be inserted in an edit script. The object pointed to
* by the old object is not freed. This must be done prior to applying the
* script.
*/
void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object)
{
BUG_ON(!object);
edit->leaf = assoc_array_leaf_to_ptr(object);
}
struct assoc_array_delete_collapse_context {
struct assoc_array_node *node;
const void *skip_leaf;
int slot;
};
/*
* Subtree collapse to node iterator.
*/
static int assoc_array_delete_collapse_iterator(const void *leaf,
void *iterator_data)
{
struct assoc_array_delete_collapse_context *collapse = iterator_data;
if (leaf == collapse->skip_leaf)
return 0;
BUG_ON(collapse->slot >= ASSOC_ARRAY_FAN_OUT);
collapse->node->slots[collapse->slot++] = assoc_array_leaf_to_ptr(leaf);
return 0;
}
/**
* assoc_array_delete - Script deletion of an object from an associative array
* @array: The array to search.
* @ops: The operations to use.
* @index_key: The key to the object.
*
* Precalculate and preallocate a script for the deletion of an object from an
* associative array. This results in an edit script that can either be
* applied or cancelled.
*
* The function returns a pointer to an edit script if the object was found,
* NULL if the object was not found or -ENOMEM.
*
* The caller should lock against other modifications and must continue to hold
* the lock until assoc_array_apply_edit() has been called.
*
* Accesses to the tree may take place concurrently with this function,
* provided they hold the RCU read lock.
*/
struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
const struct assoc_array_ops *ops,
const void *index_key)
{
struct assoc_array_delete_collapse_context collapse;
struct assoc_array_walk_result result;
struct assoc_array_node *node, *new_n0;
struct assoc_array_edit *edit;
struct assoc_array_ptr *ptr;
bool has_meta;
int slot, i;
pr_devel("-->%s()\n", __func__);
edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
if (!edit)
return ERR_PTR(-ENOMEM);
edit->array = array;
edit->ops = ops;
edit->adjust_count_by = -1;
switch (assoc_array_walk(array, ops, index_key, &result)) {
case assoc_array_walk_found_terminal_node:
/* We found a node that should contain the leaf we've been
* asked to remove - *if* it's in the tree.
*/
pr_devel("terminal_node\n");
node = result.terminal_node.node;
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = node->slots[slot];
if (ptr &&
assoc_array_ptr_is_leaf(ptr) &&
ops->compare_object(assoc_array_ptr_to_leaf(ptr),
index_key))
goto found_leaf;
}
case assoc_array_walk_tree_empty:
case assoc_array_walk_found_wrong_shortcut:
default:
assoc_array_cancel_edit(edit);
pr_devel("not found\n");
return NULL;
}
found_leaf:
BUG_ON(array->nr_leaves_on_tree <= 0);
/* In the simplest form of deletion we just clear the slot and release
* the leaf after a suitable interval.
*/
edit->dead_leaf = node->slots[slot];
edit->set[0].ptr = &node->slots[slot];
edit->set[0].to = NULL;
edit->adjust_count_on = node;
/* If that concludes erasure of the last leaf, then delete the entire
* internal array.
*/
if (array->nr_leaves_on_tree == 1) {
edit->set[1].ptr = &array->root;
edit->set[1].to = NULL;
edit->adjust_count_on = NULL;
edit->excised_subtree = array->root;
pr_devel("all gone\n");
return edit;
}
/* However, we'd also like to clear up some metadata blocks if we
* possibly can.
*
* We go for a simple algorithm of: if this node has FAN_OUT or fewer
* leaves in it, then attempt to collapse it - and attempt to
* recursively collapse up the tree.
*
* We could also try and collapse in partially filled subtrees to take
* up space in this node.
*/
if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
struct assoc_array_node *parent, *grandparent;
struct assoc_array_ptr *ptr;
/* First of all, we need to know if this node has metadata so
* that we don't try collapsing if all the leaves are already
* here.
*/
has_meta = false;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (assoc_array_ptr_is_meta(ptr)) {
has_meta = true;
break;
}
}
pr_devel("leaves: %ld [m=%d]\n",
node->nr_leaves_on_branch - 1, has_meta);
/* Look further up the tree to see if we can collapse this node
* into a more proximal node too.
*/
parent = node;
collapse_up:
pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch);
ptr = parent->back_pointer;
if (!ptr)
goto do_collapse;
if (assoc_array_ptr_is_shortcut(ptr)) {
struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr);
ptr = s->back_pointer;
if (!ptr)
goto do_collapse;
}
grandparent = assoc_array_ptr_to_node(ptr);
if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
parent = grandparent;
goto collapse_up;
}
do_collapse:
/* There's no point collapsing if the original node has no meta
* pointers to discard and if we didn't merge into one of that
* node's ancestry.
*/
if (has_meta || parent != node) {
node = parent;
/* Create a new node to collapse into */
new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n0)
goto enomem;
edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
edit->adjust_count_on = new_n0;
collapse.node = new_n0;
collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf);
collapse.slot = 0;
assoc_array_subtree_iterate(assoc_array_node_to_ptr(node),
node->back_pointer,
assoc_array_delete_collapse_iterator,
&collapse);
pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch);
BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1);
if (!node->back_pointer) {
edit->set[1].ptr = &array->root;
} else if (assoc_array_ptr_is_leaf(node->back_pointer)) {
BUG();
} else if (assoc_array_ptr_is_node(node->back_pointer)) {
struct assoc_array_node *p =
assoc_array_ptr_to_node(node->back_pointer);
edit->set[1].ptr = &p->slots[node->parent_slot];
} else if (assoc_array_ptr_is_shortcut(node->back_pointer)) {
struct assoc_array_shortcut *s =
assoc_array_ptr_to_shortcut(node->back_pointer);
edit->set[1].ptr = &s->next_node;
}
edit->set[1].to = assoc_array_node_to_ptr(new_n0);
edit->excised_subtree = assoc_array_node_to_ptr(node);
}
}
return edit;
enomem:
/* Clean up after an out of memory error */
pr_devel("enomem\n");
assoc_array_cancel_edit(edit);
return ERR_PTR(-ENOMEM);
}
/**
* assoc_array_clear - Script deletion of all objects from an associative array
* @array: The array to clear.
* @ops: The operations to use.
*
* Precalculate and preallocate a script for the deletion of all the objects
* from an associative array. This results in an edit script that can either
* be applied or cancelled.
*
* The function returns a pointer to an edit script if there are objects to be
* deleted, NULL if there are no objects in the array or -ENOMEM.
*
* The caller should lock against other modifications and must continue to hold
* the lock until assoc_array_apply_edit() has been called.
*
* Accesses to the tree may take place concurrently with this function,
* provided they hold the RCU read lock.
*/
struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
const struct assoc_array_ops *ops)
{
struct assoc_array_edit *edit;
pr_devel("-->%s()\n", __func__);
if (!array->root)
return NULL;
edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
if (!edit)
return ERR_PTR(-ENOMEM);
edit->array = array;
edit->ops = ops;
edit->set[1].ptr = &array->root;
edit->set[1].to = NULL;
edit->excised_subtree = array->root;
edit->ops_for_excised_subtree = ops;
pr_devel("all gone\n");
return edit;
}
/*
* Handle the deferred destruction after an applied edit.
*/
static void assoc_array_rcu_cleanup(struct rcu_head *head)
{
struct assoc_array_edit *edit =
container_of(head, struct assoc_array_edit, rcu);
int i;
pr_devel("-->%s()\n", __func__);
if (edit->dead_leaf)
edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf));
for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++)
if (edit->excised_meta[i])
kfree(assoc_array_ptr_to_node(edit->excised_meta[i]));
if (edit->excised_subtree) {
BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree));
if (assoc_array_ptr_is_node(edit->excised_subtree)) {
struct assoc_array_node *n =
assoc_array_ptr_to_node(edit->excised_subtree);
n->back_pointer = NULL;
} else {
struct assoc_array_shortcut *s =
assoc_array_ptr_to_shortcut(edit->excised_subtree);
s->back_pointer = NULL;
}
assoc_array_destroy_subtree(edit->excised_subtree,
edit->ops_for_excised_subtree);
}
kfree(edit);
}
/**
* assoc_array_apply_edit - Apply an edit script to an associative array
* @edit: The script to apply.
*
* Apply an edit script to an associative array to effect an insertion,
* deletion or clearance. As the edit script includes preallocated memory,
* this is guaranteed not to fail.
*
* The edit script, dead objects and dead metadata will be scheduled for
* destruction after an RCU grace period to permit those doing read-only
* accesses on the array to continue to do so under the RCU read lock whilst
* the edit is taking place.
*/
void assoc_array_apply_edit(struct assoc_array_edit *edit)
{
struct assoc_array_shortcut *shortcut;
struct assoc_array_node *node;
struct assoc_array_ptr *ptr;
int i;
pr_devel("-->%s()\n", __func__);
smp_wmb();
if (edit->leaf_p)
*edit->leaf_p = edit->leaf;
smp_wmb();
for (i = 0; i < ARRAY_SIZE(edit->set_parent_slot); i++)
if (edit->set_parent_slot[i].p)
*edit->set_parent_slot[i].p = edit->set_parent_slot[i].to;
smp_wmb();
for (i = 0; i < ARRAY_SIZE(edit->set_backpointers); i++)
if (edit->set_backpointers[i])
*edit->set_backpointers[i] = edit->set_backpointers_to;
smp_wmb();
for (i = 0; i < ARRAY_SIZE(edit->set); i++)
if (edit->set[i].ptr)
*edit->set[i].ptr = edit->set[i].to;
if (edit->array->root == NULL) {
edit->array->nr_leaves_on_tree = 0;
} else if (edit->adjust_count_on) {
node = edit->adjust_count_on;
for (;;) {
node->nr_leaves_on_branch += edit->adjust_count_by;
ptr = node->back_pointer;
if (!ptr)
break;
if (assoc_array_ptr_is_shortcut(ptr)) {
shortcut = assoc_array_ptr_to_shortcut(ptr);
ptr = shortcut->back_pointer;
if (!ptr)
break;
}
BUG_ON(!assoc_array_ptr_is_node(ptr));
node = assoc_array_ptr_to_node(ptr);
}
edit->array->nr_leaves_on_tree += edit->adjust_count_by;
}
call_rcu(&edit->rcu, assoc_array_rcu_cleanup);
}
/**
* assoc_array_cancel_edit - Discard an edit script.
* @edit: The script to discard.
*
* Free an edit script and all the preallocated data it holds without making
* any changes to the associative array it was intended for.
*
* NOTE! In the case of an insertion script, this does _not_ release the leaf
* that was to be inserted. That is left to the caller.
*/
void assoc_array_cancel_edit(struct assoc_array_edit *edit)
{
struct assoc_array_ptr *ptr;
int i;
pr_devel("-->%s()\n", __func__);
/* Clean up after an out of memory error */
for (i = 0; i < ARRAY_SIZE(edit->new_meta); i++) {
ptr = edit->new_meta[i];
if (ptr) {
if (assoc_array_ptr_is_node(ptr))
kfree(assoc_array_ptr_to_node(ptr));
else
kfree(assoc_array_ptr_to_shortcut(ptr));
}
}
kfree(edit);
}
/**
* assoc_array_gc - Garbage collect an associative array.
* @array: The array to clean.
* @ops: The operations to use.
* @iterator: A callback function to pass judgement on each object.
* @iterator_data: Private data for the callback function.
*
* Collect garbage from an associative array and pack down the internal tree to
* save memory.
*
* The iterator function is asked to pass judgement upon each object in the
* array. If it returns false, the object is discard and if it returns true,
* the object is kept. If it returns true, it must increment the object's
* usage count (or whatever it needs to do to retain it) before returning.
*
* This function returns 0 if successful or -ENOMEM if out of memory. In the
* latter case, the array is not changed.
*
* The caller should lock against other modifications and must continue to hold
* the lock until assoc_array_apply_edit() has been called.
*
* Accesses to the tree may take place concurrently with this function,
* provided they hold the RCU read lock.
*/
int assoc_array_gc(struct assoc_array *array,
const struct assoc_array_ops *ops,
bool (*iterator)(void *object, void *iterator_data),
void *iterator_data)
{
struct assoc_array_shortcut *shortcut, *new_s;
struct assoc_array_node *node, *new_n;
struct assoc_array_edit *edit;
struct assoc_array_ptr *cursor, *ptr;
struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp;
unsigned long nr_leaves_on_tree;
int keylen, slot, nr_free, next_slot, i;
pr_devel("-->%s()\n", __func__);
if (!array->root)
return 0;
edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
if (!edit)
return -ENOMEM;
edit->array = array;
edit->ops = ops;
edit->ops_for_excised_subtree = ops;
edit->set[0].ptr = &array->root;
edit->excised_subtree = array->root;
new_root = new_parent = NULL;
new_ptr_pp = &new_root;
cursor = array->root;
descend:
/* If this point is a shortcut, then we need to duplicate it and
* advance the target cursor.
*/
if (assoc_array_ptr_is_shortcut(cursor)) {
shortcut = assoc_array_ptr_to_shortcut(cursor);
keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s = kmalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s)
goto enomem;
pr_devel("dup shortcut %p -> %p\n", shortcut, new_s);
memcpy(new_s, shortcut, (sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long)));
new_s->back_pointer = new_parent;
new_s->parent_slot = shortcut->parent_slot;
*new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s);
new_ptr_pp = &new_s->next_node;
cursor = shortcut->next_node;
}
/* Duplicate the node at this position */
node = assoc_array_ptr_to_node(cursor);
new_n = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n)
goto enomem;
pr_devel("dup node %p -> %p\n", node, new_n);
new_n->back_pointer = new_parent;
new_n->parent_slot = node->parent_slot;
*new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n);
new_ptr_pp = NULL;
slot = 0;
continue_node:
/* Filter across any leaves and gc any subtrees */
for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = node->slots[slot];
if (!ptr)
continue;
if (assoc_array_ptr_is_leaf(ptr)) {
if (iterator(assoc_array_ptr_to_leaf(ptr),
iterator_data))
/* The iterator will have done any reference
* counting on the object for us.
*/
new_n->slots[slot] = ptr;
continue;
}
new_ptr_pp = &new_n->slots[slot];
cursor = ptr;
goto descend;
}
pr_devel("-- compress node %p --\n", new_n);
/* Count up the number of empty slots in this node and work out the
* subtree leaf count.
*/
new_n->nr_leaves_on_branch = 0;
nr_free = 0;
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = new_n->slots[slot];
if (!ptr)
nr_free++;
else if (assoc_array_ptr_is_leaf(ptr))
new_n->nr_leaves_on_branch++;
}
pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch);
/* See what we can fold in */
next_slot = 0;
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
struct assoc_array_shortcut *s;
struct assoc_array_node *child;
ptr = new_n->slots[slot];
if (!ptr || assoc_array_ptr_is_leaf(ptr))
continue;
s = NULL;
if (assoc_array_ptr_is_shortcut(ptr)) {
s = assoc_array_ptr_to_shortcut(ptr);
ptr = s->next_node;
}
child = assoc_array_ptr_to_node(ptr);
new_n->nr_leaves_on_branch += child->nr_leaves_on_branch;
if (child->nr_leaves_on_branch <= nr_free + 1) {
/* Fold the child node into this one */
pr_devel("[%d] fold node %lu/%d [nx %d]\n",
slot, child->nr_leaves_on_branch, nr_free + 1,
next_slot);
/* We would already have reaped an intervening shortcut
* on the way back up the tree.
*/
BUG_ON(s);
new_n->slots[slot] = NULL;
nr_free++;
if (slot < next_slot)
next_slot = slot;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
struct assoc_array_ptr *p = child->slots[i];
if (!p)
continue;
BUG_ON(assoc_array_ptr_is_meta(p));
while (new_n->slots[next_slot])
next_slot++;
BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT);
new_n->slots[next_slot++] = p;
nr_free--;
}
kfree(child);
} else {
pr_devel("[%d] retain node %lu/%d [nx %d]\n",
slot, child->nr_leaves_on_branch, nr_free + 1,
next_slot);
}
}
pr_devel("after: %lu\n", new_n->nr_leaves_on_branch);
nr_leaves_on_tree = new_n->nr_leaves_on_branch;
/* Excise this node if it is singly occupied by a shortcut */
if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) {
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++)
if ((ptr = new_n->slots[slot]))
break;
if (assoc_array_ptr_is_meta(ptr) &&
assoc_array_ptr_is_shortcut(ptr)) {
pr_devel("excise node %p with 1 shortcut\n", new_n);
new_s = assoc_array_ptr_to_shortcut(ptr);
new_parent = new_n->back_pointer;
slot = new_n->parent_slot;
kfree(new_n);
if (!new_parent) {
new_s->back_pointer = NULL;
new_s->parent_slot = 0;
new_root = ptr;
goto gc_complete;
}
if (assoc_array_ptr_is_shortcut(new_parent)) {
/* We can discard any preceding shortcut also */
struct assoc_array_shortcut *s =
assoc_array_ptr_to_shortcut(new_parent);
pr_devel("excise preceding shortcut\n");
new_parent = new_s->back_pointer = s->back_pointer;
slot = new_s->parent_slot = s->parent_slot;
kfree(s);
if (!new_parent) {
new_s->back_pointer = NULL;
new_s->parent_slot = 0;
new_root = ptr;
goto gc_complete;
}
}
new_s->back_pointer = new_parent;
new_s->parent_slot = slot;
new_n = assoc_array_ptr_to_node(new_parent);
new_n->slots[slot] = ptr;
goto ascend_old_tree;
}
}
/* Excise any shortcuts we might encounter that point to nodes that
* only contain leaves.
*/
ptr = new_n->back_pointer;
if (!ptr)
goto gc_complete;
if (assoc_array_ptr_is_shortcut(ptr)) {
new_s = assoc_array_ptr_to_shortcut(ptr);
new_parent = new_s->back_pointer;
slot = new_s->parent_slot;
if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
struct assoc_array_node *n;
pr_devel("excise shortcut\n");
new_n->back_pointer = new_parent;
new_n->parent_slot = slot;
kfree(new_s);
if (!new_parent) {
new_root = assoc_array_node_to_ptr(new_n);
goto gc_complete;
}
n = assoc_array_ptr_to_node(new_parent);
n->slots[slot] = assoc_array_node_to_ptr(new_n);
}
} else {
new_parent = ptr;
}
new_n = assoc_array_ptr_to_node(new_parent);
ascend_old_tree:
ptr = node->back_pointer;
if (assoc_array_ptr_is_shortcut(ptr)) {
shortcut = assoc_array_ptr_to_shortcut(ptr);
slot = shortcut->parent_slot;
cursor = shortcut->back_pointer;
if (!cursor)
goto gc_complete;
} else {
slot = node->parent_slot;
cursor = ptr;
}
BUG_ON(!cursor);
node = assoc_array_ptr_to_node(cursor);
slot++;
goto continue_node;
gc_complete:
edit->set[0].to = new_root;
assoc_array_apply_edit(edit);
array->nr_leaves_on_tree = nr_leaves_on_tree;
return 0;
enomem:
pr_devel("enomem\n");
assoc_array_destroy_subtree(new_root, edit->ops);
kfree(edit);
return -ENOMEM;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_5337_0 |
crossvul-cpp_data_good_3378_0 | /**********************************************************************
regexec.c - Oniguruma (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2017 K.Kosako <sndgk393 AT ybb DOT ne DOT jp>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "regint.h"
#define USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
#ifdef USE_CRNL_AS_LINE_TERMINATOR
#define ONIGENC_IS_MBC_CRNL(enc,p,end) \
(ONIGENC_MBC_TO_CODE(enc,p,end) == 13 && \
ONIGENC_IS_MBC_NEWLINE(enc,(p+enclen(enc,p)),end))
#endif
#ifdef USE_CAPTURE_HISTORY
static void history_tree_free(OnigCaptureTreeNode* node);
static void
history_tree_clear(OnigCaptureTreeNode* node)
{
int i;
if (IS_NOT_NULL(node)) {
for (i = 0; i < node->num_childs; i++) {
if (IS_NOT_NULL(node->childs[i])) {
history_tree_free(node->childs[i]);
}
}
for (i = 0; i < node->allocated; i++) {
node->childs[i] = (OnigCaptureTreeNode* )0;
}
node->num_childs = 0;
node->beg = ONIG_REGION_NOTPOS;
node->end = ONIG_REGION_NOTPOS;
node->group = -1;
}
}
static void
history_tree_free(OnigCaptureTreeNode* node)
{
history_tree_clear(node);
xfree(node);
}
static void
history_root_free(OnigRegion* r)
{
if (IS_NOT_NULL(r->history_root)) {
history_tree_free(r->history_root);
r->history_root = (OnigCaptureTreeNode* )0;
}
}
static OnigCaptureTreeNode*
history_node_new(void)
{
OnigCaptureTreeNode* node;
node = (OnigCaptureTreeNode* )xmalloc(sizeof(OnigCaptureTreeNode));
CHECK_NULL_RETURN(node);
node->childs = (OnigCaptureTreeNode** )0;
node->allocated = 0;
node->num_childs = 0;
node->group = -1;
node->beg = ONIG_REGION_NOTPOS;
node->end = ONIG_REGION_NOTPOS;
return node;
}
static int
history_tree_add_child(OnigCaptureTreeNode* parent, OnigCaptureTreeNode* child)
{
#define HISTORY_TREE_INIT_ALLOC_SIZE 8
if (parent->num_childs >= parent->allocated) {
int n, i;
if (IS_NULL(parent->childs)) {
n = HISTORY_TREE_INIT_ALLOC_SIZE;
parent->childs =
(OnigCaptureTreeNode** )xmalloc(sizeof(OnigCaptureTreeNode*) * n);
}
else {
n = parent->allocated * 2;
parent->childs =
(OnigCaptureTreeNode** )xrealloc(parent->childs,
sizeof(OnigCaptureTreeNode*) * n);
}
CHECK_NULL_RETURN_MEMERR(parent->childs);
for (i = parent->allocated; i < n; i++) {
parent->childs[i] = (OnigCaptureTreeNode* )0;
}
parent->allocated = n;
}
parent->childs[parent->num_childs] = child;
parent->num_childs++;
return 0;
}
static OnigCaptureTreeNode*
history_tree_clone(OnigCaptureTreeNode* node)
{
int i;
OnigCaptureTreeNode *clone, *child;
clone = history_node_new();
CHECK_NULL_RETURN(clone);
clone->beg = node->beg;
clone->end = node->end;
for (i = 0; i < node->num_childs; i++) {
child = history_tree_clone(node->childs[i]);
if (IS_NULL(child)) {
history_tree_free(clone);
return (OnigCaptureTreeNode* )0;
}
history_tree_add_child(clone, child);
}
return clone;
}
extern OnigCaptureTreeNode*
onig_get_capture_tree(OnigRegion* region)
{
return region->history_root;
}
#endif /* USE_CAPTURE_HISTORY */
extern void
onig_region_clear(OnigRegion* region)
{
int i;
for (i = 0; i < region->num_regs; i++) {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
#ifdef USE_CAPTURE_HISTORY
history_root_free(region);
#endif
}
extern int
onig_region_resize(OnigRegion* region, int n)
{
region->num_regs = n;
if (n < ONIG_NREGION)
n = ONIG_NREGION;
if (region->allocated == 0) {
region->beg = (int* )xmalloc(n * sizeof(int));
region->end = (int* )xmalloc(n * sizeof(int));
if (region->beg == 0 || region->end == 0)
return ONIGERR_MEMORY;
region->allocated = n;
}
else if (region->allocated < n) {
region->beg = (int* )xrealloc(region->beg, n * sizeof(int));
region->end = (int* )xrealloc(region->end, n * sizeof(int));
if (region->beg == 0 || region->end == 0)
return ONIGERR_MEMORY;
region->allocated = n;
}
return 0;
}
static int
onig_region_resize_clear(OnigRegion* region, int n)
{
int r;
r = onig_region_resize(region, n);
if (r != 0) return r;
onig_region_clear(region);
return 0;
}
extern int
onig_region_set(OnigRegion* region, int at, int beg, int end)
{
if (at < 0) return ONIGERR_INVALID_ARGUMENT;
if (at >= region->allocated) {
int r = onig_region_resize(region, at + 1);
if (r < 0) return r;
}
region->beg[at] = beg;
region->end[at] = end;
return 0;
}
extern void
onig_region_init(OnigRegion* region)
{
region->num_regs = 0;
region->allocated = 0;
region->beg = (int* )0;
region->end = (int* )0;
region->history_root = (OnigCaptureTreeNode* )0;
}
extern OnigRegion*
onig_region_new(void)
{
OnigRegion* r;
r = (OnigRegion* )xmalloc(sizeof(OnigRegion));
onig_region_init(r);
return r;
}
extern void
onig_region_free(OnigRegion* r, int free_self)
{
if (r) {
if (r->allocated > 0) {
if (r->beg) xfree(r->beg);
if (r->end) xfree(r->end);
r->allocated = 0;
}
#ifdef USE_CAPTURE_HISTORY
history_root_free(r);
#endif
if (free_self) xfree(r);
}
}
extern void
onig_region_copy(OnigRegion* to, OnigRegion* from)
{
#define RREGC_SIZE (sizeof(int) * from->num_regs)
int i;
if (to == from) return;
if (to->allocated == 0) {
if (from->num_regs > 0) {
to->beg = (int* )xmalloc(RREGC_SIZE);
to->end = (int* )xmalloc(RREGC_SIZE);
to->allocated = from->num_regs;
}
}
else if (to->allocated < from->num_regs) {
to->beg = (int* )xrealloc(to->beg, RREGC_SIZE);
to->end = (int* )xrealloc(to->end, RREGC_SIZE);
to->allocated = from->num_regs;
}
for (i = 0; i < from->num_regs; i++) {
to->beg[i] = from->beg[i];
to->end[i] = from->end[i];
}
to->num_regs = from->num_regs;
#ifdef USE_CAPTURE_HISTORY
history_root_free(to);
if (IS_NOT_NULL(from->history_root)) {
to->history_root = history_tree_clone(from->history_root);
}
#endif
}
/** stack **/
#define INVALID_STACK_INDEX -1
/* stack type */
/* used by normal-POP */
#define STK_ALT 0x0001
#define STK_LOOK_BEHIND_NOT 0x0002
#define STK_POS_NOT 0x0003
/* handled by normal-POP */
#define STK_MEM_START 0x0100
#define STK_MEM_END 0x8200
#define STK_REPEAT_INC 0x0300
#define STK_STATE_CHECK_MARK 0x1000
/* avoided by normal-POP */
#define STK_NULL_CHECK_START 0x3000
#define STK_NULL_CHECK_END 0x5000 /* for recursive call */
#define STK_MEM_END_MARK 0x8400
#define STK_POS 0x0500 /* used when POP-POS */
#define STK_STOP_BT 0x0600 /* mark for "(?>...)" */
#define STK_REPEAT 0x0700
#define STK_CALL_FRAME 0x0800
#define STK_RETURN 0x0900
#define STK_VOID 0x0a00 /* for fill a blank */
/* stack type check mask */
#define STK_MASK_POP_USED 0x00ff
#define STK_MASK_TO_VOID_TARGET 0x10ff
#define STK_MASK_MEM_END_OR_MARK 0x8000 /* MEM_END or MEM_END_MARK */
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start) do {\
(msa).stack_p = (void* )0;\
(msa).options = (arg_option);\
(msa).region = (arg_region);\
(msa).start = (arg_start);\
(msa).best_len = ONIG_MISMATCH;\
(msa).ptr_num = (reg)->num_repeat + (reg)->num_mem * 2;\
} while(0)
#else
#define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start) do {\
(msa).stack_p = (void* )0;\
(msa).options = (arg_option);\
(msa).region = (arg_region);\
(msa).start = (arg_start);\
(msa).ptr_num = (reg)->num_repeat + (reg)->num_mem * 2;\
} while(0)
#endif
#ifdef USE_COMBINATION_EXPLOSION_CHECK
#define STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE 16
#define STATE_CHECK_BUFF_INIT(msa, str_len, offset, state_num) do { \
if ((state_num) > 0 && str_len >= STATE_CHECK_STRING_THRESHOLD_LEN) {\
unsigned int size = (unsigned int )(((str_len) + 1) * (state_num) + 7) >> 3;\
offset = ((offset) * (state_num)) >> 3;\
if (size > 0 && offset < size && size < STATE_CHECK_BUFF_MAX_SIZE) {\
if (size >= STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE) \
(msa).state_check_buff = (void* )xmalloc(size);\
else \
(msa).state_check_buff = (void* )xalloca(size);\
xmemset(((char* )((msa).state_check_buff)+(offset)), 0, \
(size_t )(size - (offset))); \
(msa).state_check_buff_size = size;\
}\
else {\
(msa).state_check_buff = (void* )0;\
(msa).state_check_buff_size = 0;\
}\
}\
else {\
(msa).state_check_buff = (void* )0;\
(msa).state_check_buff_size = 0;\
}\
} while(0)
#define MATCH_ARG_FREE(msa) do {\
if ((msa).stack_p) xfree((msa).stack_p);\
if ((msa).state_check_buff_size >= STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE) { \
if ((msa).state_check_buff) xfree((msa).state_check_buff);\
}\
} while(0)
#else
#define STATE_CHECK_BUFF_INIT(msa, str_len, offset, state_num)
#define MATCH_ARG_FREE(msa) if ((msa).stack_p) xfree((msa).stack_p)
#endif
#define ALLOCA_PTR_NUM_LIMIT 50
#define STACK_INIT(stack_num) do {\
if (msa->stack_p) {\
is_alloca = 0;\
alloc_base = msa->stack_p;\
stk_base = (OnigStackType* )(alloc_base\
+ (sizeof(OnigStackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + msa->stack_n;\
}\
else if (msa->ptr_num > ALLOCA_PTR_NUM_LIMIT) {\
is_alloca = 0;\
alloc_base = (char* )xmalloc(sizeof(OnigStackIndex) * msa->ptr_num\
+ sizeof(OnigStackType) * (stack_num));\
stk_base = (OnigStackType* )(alloc_base\
+ (sizeof(OnigStackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + (stack_num);\
}\
else {\
is_alloca = 1;\
alloc_base = (char* )xalloca(sizeof(OnigStackIndex) * msa->ptr_num\
+ sizeof(OnigStackType) * (stack_num));\
stk_base = (OnigStackType* )(alloc_base\
+ (sizeof(OnigStackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + (stack_num);\
}\
} while(0);
#define STACK_SAVE do{\
msa->stack_n = stk_end - stk_base;\
if (is_alloca != 0) {\
size_t size = sizeof(OnigStackIndex) * msa->ptr_num \
+ sizeof(OnigStackType) * msa->stack_n;\
msa->stack_p = xmalloc(size);\
xmemcpy(msa->stack_p, alloc_base, size);\
}\
else {\
msa->stack_p = alloc_base;\
};\
} while(0)
#define UPDATE_FOR_STACK_REALLOC do{\
repeat_stk = (OnigStackIndex* )alloc_base;\
mem_start_stk = (OnigStackIndex* )(repeat_stk + reg->num_repeat);\
mem_end_stk = mem_start_stk + num_mem;\
mem_start_stk--; /* for index start from 1 */\
mem_end_stk--; /* for index start from 1 */\
} while(0)
static unsigned int MatchStackLimitSize = DEFAULT_MATCH_STACK_LIMIT_SIZE;
extern unsigned int
onig_get_match_stack_limit_size(void)
{
return MatchStackLimitSize;
}
extern int
onig_set_match_stack_limit_size(unsigned int size)
{
MatchStackLimitSize = size;
return 0;
}
static int
stack_double(int is_alloca, char** arg_alloc_base,
OnigStackType** arg_stk_base,
OnigStackType** arg_stk_end, OnigStackType** arg_stk,
OnigMatchArg* msa)
{
unsigned int n;
int used;
size_t size;
size_t new_size;
char* alloc_base;
char* new_alloc_base;
OnigStackType *stk_base, *stk_end, *stk;
alloc_base = *arg_alloc_base;
stk_base = *arg_stk_base;
stk_end = *arg_stk_end;
stk = *arg_stk;
n = stk_end - stk_base;
size = sizeof(OnigStackIndex) * msa->ptr_num + sizeof(OnigStackType) * n;
n *= 2;
new_size = sizeof(OnigStackIndex) * msa->ptr_num + sizeof(OnigStackType) * n;
if (is_alloca != 0) {
new_alloc_base = (char* )xmalloc(new_size);
if (IS_NULL(new_alloc_base)) {
STACK_SAVE;
return ONIGERR_MEMORY;
}
xmemcpy(new_alloc_base, alloc_base, size);
}
else {
if (MatchStackLimitSize != 0 && n > MatchStackLimitSize) {
if ((unsigned int )(stk_end - stk_base) == MatchStackLimitSize)
return ONIGERR_MATCH_STACK_LIMIT_OVER;
else
n = MatchStackLimitSize;
}
new_alloc_base = (char* )xrealloc(alloc_base, new_size);
if (IS_NULL(new_alloc_base)) {
STACK_SAVE;
return ONIGERR_MEMORY;
}
}
alloc_base = new_alloc_base;
used = stk - stk_base;
*arg_alloc_base = alloc_base;
*arg_stk_base = (OnigStackType* )(alloc_base
+ (sizeof(OnigStackIndex) * msa->ptr_num));
*arg_stk = *arg_stk_base + used;
*arg_stk_end = *arg_stk_base + n;
return 0;
}
#define STACK_ENSURE(n) do {\
if (stk_end - stk < (n)) {\
int r = stack_double(is_alloca, &alloc_base, &stk_base, &stk_end, &stk,\
msa);\
if (r != 0) { STACK_SAVE; return r; } \
is_alloca = 0;\
UPDATE_FOR_STACK_REALLOC;\
}\
} while(0)
#define STACK_AT(index) (stk_base + (index))
#define GET_STACK_INDEX(stk) ((stk) - stk_base)
#define STACK_PUSH_TYPE(stack_type) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
STACK_INC;\
} while(0)
#define IS_TO_VOID_TARGET(stk) (((stk)->type & STK_MASK_TO_VOID_TARGET) != 0)
#ifdef USE_COMBINATION_EXPLOSION_CHECK
#define STATE_CHECK_POS(s,snum) \
(((s) - str) * num_comb_exp_check + ((snum) - 1))
#define STATE_CHECK_VAL(v,snum) do {\
if (state_check_buff != NULL) {\
int x = STATE_CHECK_POS(s,snum);\
(v) = state_check_buff[x/8] & (1<<(x%8));\
}\
else (v) = 0;\
} while(0)
#define ELSE_IF_STATE_CHECK_MARK(stk) \
else if ((stk)->type == STK_STATE_CHECK_MARK) { \
int x = STATE_CHECK_POS(stk->u.state.pstr, stk->u.state.state_check);\
state_check_buff[x/8] |= (1<<(x%8)); \
}
#define STACK_PUSH(stack_type,pat,s,sprev) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = (s);\
stk->u.state.pstr_prev = (sprev);\
stk->u.state.state_check = 0;\
STACK_INC;\
} while(0)
#define STACK_PUSH_ENSURED(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.state_check = 0;\
STACK_INC;\
} while(0)
#define STACK_PUSH_ALT_WITH_STATE_CHECK(pat,s,sprev,snum) do {\
STACK_ENSURE(1);\
stk->type = STK_ALT;\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = (s);\
stk->u.state.pstr_prev = (sprev);\
stk->u.state.state_check = ((state_check_buff != NULL) ? (snum) : 0);\
STACK_INC;\
} while(0)
#define STACK_PUSH_STATE_CHECK(s,snum) do {\
if (state_check_buff != NULL) {\
STACK_ENSURE(1);\
stk->type = STK_STATE_CHECK_MARK;\
stk->u.state.pstr = (s);\
stk->u.state.state_check = (snum);\
STACK_INC;\
}\
} while(0)
#else /* USE_COMBINATION_EXPLOSION_CHECK */
#define ELSE_IF_STATE_CHECK_MARK(stk)
#define STACK_PUSH(stack_type,pat,s,sprev) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = (s);\
stk->u.state.pstr_prev = (sprev);\
STACK_INC;\
} while(0)
#define STACK_PUSH_ENSURED(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
STACK_INC;\
} while(0)
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
#define STACK_PUSH_ALT(pat,s,sprev) STACK_PUSH(STK_ALT,pat,s,sprev)
#define STACK_PUSH_POS(s,sprev) STACK_PUSH(STK_POS,NULL_UCHARP,s,sprev)
#define STACK_PUSH_POS_NOT(pat,s,sprev) STACK_PUSH(STK_POS_NOT,pat,s,sprev)
#define STACK_PUSH_STOP_BT STACK_PUSH_TYPE(STK_STOP_BT)
#define STACK_PUSH_LOOK_BEHIND_NOT(pat,s,sprev) \
STACK_PUSH(STK_LOOK_BEHIND_NOT,pat,s,sprev)
#define STACK_PUSH_REPEAT(id, pat) do {\
STACK_ENSURE(1);\
stk->type = STK_REPEAT;\
stk->u.repeat.num = (id);\
stk->u.repeat.pcode = (pat);\
stk->u.repeat.count = 0;\
STACK_INC;\
} while(0)
#define STACK_PUSH_REPEAT_INC(sindex) do {\
STACK_ENSURE(1);\
stk->type = STK_REPEAT_INC;\
stk->u.repeat_inc.si = (sindex);\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_START(mnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_START;\
stk->u.mem.num = (mnum);\
stk->u.mem.pstr = (s);\
stk->u.mem.start = mem_start_stk[mnum];\
stk->u.mem.end = mem_end_stk[mnum];\
mem_start_stk[mnum] = GET_STACK_INDEX(stk);\
mem_end_stk[mnum] = INVALID_STACK_INDEX;\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_END(mnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_END;\
stk->u.mem.num = (mnum);\
stk->u.mem.pstr = (s);\
stk->u.mem.start = mem_start_stk[mnum];\
stk->u.mem.end = mem_end_stk[mnum];\
mem_end_stk[mnum] = GET_STACK_INDEX(stk);\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_END_MARK(mnum) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_END_MARK;\
stk->u.mem.num = (mnum);\
STACK_INC;\
} while(0)
#define STACK_GET_MEM_START(mnum, k) do {\
int level = 0;\
k = stk;\
while (k > stk_base) {\
k--;\
if ((k->type & STK_MASK_MEM_END_OR_MARK) != 0 \
&& k->u.mem.num == (mnum)) {\
level++;\
}\
else if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\
if (level == 0) break;\
level--;\
}\
}\
} while(0)
#define STACK_GET_MEM_RANGE(k, mnum, start, end) do {\
int level = 0;\
while (k < stk) {\
if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\
if (level == 0) (start) = k->u.mem.pstr;\
level++;\
}\
else if (k->type == STK_MEM_END && k->u.mem.num == (mnum)) {\
level--;\
if (level == 0) {\
(end) = k->u.mem.pstr;\
break;\
}\
}\
k++;\
}\
} while(0)
#define STACK_PUSH_NULL_CHECK_START(cnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_NULL_CHECK_START;\
stk->u.null_check.num = (cnum);\
stk->u.null_check.pstr = (s);\
STACK_INC;\
} while(0)
#define STACK_PUSH_NULL_CHECK_END(cnum) do {\
STACK_ENSURE(1);\
stk->type = STK_NULL_CHECK_END;\
stk->u.null_check.num = (cnum);\
STACK_INC;\
} while(0)
#define STACK_PUSH_CALL_FRAME(pat) do {\
STACK_ENSURE(1);\
stk->type = STK_CALL_FRAME;\
stk->u.call_frame.ret_addr = (pat);\
STACK_INC;\
} while(0)
#define STACK_PUSH_RETURN do {\
STACK_ENSURE(1);\
stk->type = STK_RETURN;\
STACK_INC;\
} while(0)
#ifdef ONIG_DEBUG
#define STACK_BASE_CHECK(p, at) \
if ((p) < stk_base) {\
fprintf(stderr, "at %s\n", at);\
goto stack_error;\
}
#else
#define STACK_BASE_CHECK(p, at)
#endif
#define STACK_POP_ONE do {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP_ONE"); \
} while(0)
#define STACK_POP do {\
switch (pop_level) {\
case STACK_POP_LEVEL_FREE:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
break;\
case STACK_POP_LEVEL_MEM_START:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP 2"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
break;\
default:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP 3"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
break;\
}\
} while(0)
#define STACK_POP_TIL_POS_NOT do {\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP_TIL_POS_NOT"); \
if (stk->type == STK_POS_NOT) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
} while(0)
#define STACK_POP_TIL_LOOK_BEHIND_NOT do {\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP_TIL_LOOK_BEHIND_NOT"); \
if (stk->type == STK_LOOK_BEHIND_NOT) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
} while(0)
#define STACK_POS_END(k) do {\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_POS_END"); \
if (IS_TO_VOID_TARGET(k)) {\
k->type = STK_VOID;\
}\
else if (k->type == STK_POS) {\
k->type = STK_VOID;\
break;\
}\
}\
} while(0)
#define STACK_STOP_BT_END do {\
OnigStackType *k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_STOP_BT_END"); \
if (IS_TO_VOID_TARGET(k)) {\
k->type = STK_VOID;\
}\
else if (k->type == STK_STOP_BT) {\
k->type = STK_VOID;\
break;\
}\
}\
} while(0)
#define STACK_NULL_CHECK(isnull,id,s) do {\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_NULL_CHECK"); \
if (k->type == STK_NULL_CHECK_START) {\
if (k->u.null_check.num == (id)) {\
(isnull) = (k->u.null_check.pstr == (s));\
break;\
}\
}\
}\
} while(0)
#define STACK_NULL_CHECK_REC(isnull,id,s) do {\
int level = 0;\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_NULL_CHECK_REC"); \
if (k->type == STK_NULL_CHECK_START) {\
if (k->u.null_check.num == (id)) {\
if (level == 0) {\
(isnull) = (k->u.null_check.pstr == (s));\
break;\
}\
else level--;\
}\
}\
else if (k->type == STK_NULL_CHECK_END) {\
level++;\
}\
}\
} while(0)
#define STACK_NULL_CHECK_MEMST(isnull,id,s,reg) do {\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_NULL_CHECK_MEMST"); \
if (k->type == STK_NULL_CHECK_START) {\
if (k->u.null_check.num == (id)) {\
if (k->u.null_check.pstr != (s)) {\
(isnull) = 0;\
break;\
}\
else {\
UChar* endp;\
(isnull) = 1;\
while (k < stk) {\
if (k->type == STK_MEM_START) {\
if (k->u.mem.end == INVALID_STACK_INDEX) {\
(isnull) = 0; break;\
}\
if (BIT_STATUS_AT(reg->bt_mem_end, k->u.mem.num))\
endp = STACK_AT(k->u.mem.end)->u.mem.pstr;\
else\
endp = (UChar* )k->u.mem.end;\
if (STACK_AT(k->u.mem.start)->u.mem.pstr != endp) {\
(isnull) = 0; break;\
}\
else if (endp != s) {\
(isnull) = -1; /* empty, but position changed */ \
}\
}\
k++;\
}\
break;\
}\
}\
}\
}\
} while(0)
#define STACK_NULL_CHECK_MEMST_REC(isnull,id,s,reg) do {\
int level = 0;\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_NULL_CHECK_MEMST_REC"); \
if (k->type == STK_NULL_CHECK_START) {\
if (k->u.null_check.num == (id)) {\
if (level == 0) {\
if (k->u.null_check.pstr != (s)) {\
(isnull) = 0;\
break;\
}\
else {\
UChar* endp;\
(isnull) = 1;\
while (k < stk) {\
if (k->type == STK_MEM_START) {\
if (k->u.mem.end == INVALID_STACK_INDEX) {\
(isnull) = 0; break;\
}\
if (BIT_STATUS_AT(reg->bt_mem_end, k->u.mem.num))\
endp = STACK_AT(k->u.mem.end)->u.mem.pstr;\
else\
endp = (UChar* )k->u.mem.end;\
if (STACK_AT(k->u.mem.start)->u.mem.pstr != endp) {\
(isnull) = 0; break;\
}\
else if (endp != s) {\
(isnull) = -1; /* empty, but position changed */ \
}\
}\
k++;\
}\
break;\
}\
}\
else {\
level--;\
}\
}\
}\
else if (k->type == STK_NULL_CHECK_END) {\
if (k->u.null_check.num == (id)) level++;\
}\
}\
} while(0)
#define STACK_GET_REPEAT(id, k) do {\
int level = 0;\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_REPEAT"); \
if (k->type == STK_REPEAT) {\
if (level == 0) {\
if (k->u.repeat.num == (id)) {\
break;\
}\
}\
}\
else if (k->type == STK_CALL_FRAME) level--;\
else if (k->type == STK_RETURN) level++;\
}\
} while(0)
#define STACK_RETURN(addr) do {\
int level = 0;\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_RETURN"); \
if (k->type == STK_CALL_FRAME) {\
if (level == 0) {\
(addr) = k->u.call_frame.ret_addr;\
break;\
}\
else level--;\
}\
else if (k->type == STK_RETURN)\
level++;\
}\
} while(0)
#define STRING_CMP(s1,s2,len) do {\
while (len-- > 0) {\
if (*s1++ != *s2++) goto fail;\
}\
} while(0)
#define STRING_CMP_IC(case_fold_flag,s1,ps2,len) do {\
if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \
goto fail; \
} while(0)
static int string_cmp_ic(OnigEncoding enc, int case_fold_flag,
UChar* s1, UChar** ps2, int mblen)
{
UChar buf1[ONIGENC_MBC_CASE_FOLD_MAXLEN];
UChar buf2[ONIGENC_MBC_CASE_FOLD_MAXLEN];
UChar *p1, *p2, *end1, *s2, *end2;
int len1, len2;
s2 = *ps2;
end1 = s1 + mblen;
end2 = s2 + mblen;
while (s1 < end1) {
len1 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s1, end1, buf1);
len2 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s2, end2, buf2);
if (len1 != len2) return 0;
p1 = buf1;
p2 = buf2;
while (len1-- > 0) {
if (*p1 != *p2) return 0;
p1++;
p2++;
}
}
*ps2 = s2;
return 1;
}
#define STRING_CMP_VALUE(s1,s2,len,is_fail) do {\
is_fail = 0;\
while (len-- > 0) {\
if (*s1++ != *s2++) {\
is_fail = 1; break;\
}\
}\
} while(0)
#define STRING_CMP_VALUE_IC(case_fold_flag,s1,ps2,len,is_fail) do {\
if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \
is_fail = 1; \
else \
is_fail = 0; \
} while(0)
#define IS_EMPTY_STR (str == end)
#define ON_STR_BEGIN(s) ((s) == str)
#define ON_STR_END(s) ((s) == end)
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
#define DATA_ENSURE_CHECK1 (s < right_range)
#define DATA_ENSURE_CHECK(n) (s + (n) <= right_range)
#define DATA_ENSURE(n) if (s + (n) > right_range) goto fail
#else
#define DATA_ENSURE_CHECK1 (s < end)
#define DATA_ENSURE_CHECK(n) (s + (n) <= end)
#define DATA_ENSURE(n) if (s + (n) > end) goto fail
#endif /* USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE */
#ifdef USE_CAPTURE_HISTORY
static int
make_capture_history_tree(OnigCaptureTreeNode* node, OnigStackType** kp,
OnigStackType* stk_top, UChar* str, regex_t* reg)
{
int n, r;
OnigCaptureTreeNode* child;
OnigStackType* k = *kp;
while (k < stk_top) {
if (k->type == STK_MEM_START) {
n = k->u.mem.num;
if (n <= ONIG_MAX_CAPTURE_HISTORY_GROUP &&
BIT_STATUS_AT(reg->capture_history, n) != 0) {
child = history_node_new();
CHECK_NULL_RETURN_MEMERR(child);
child->group = n;
child->beg = (int )(k->u.mem.pstr - str);
r = history_tree_add_child(node, child);
if (r != 0) return r;
*kp = (k + 1);
r = make_capture_history_tree(child, kp, stk_top, str, reg);
if (r != 0) return r;
k = *kp;
child->end = (int )(k->u.mem.pstr - str);
}
}
else if (k->type == STK_MEM_END) {
if (k->u.mem.num == node->group) {
node->end = (int )(k->u.mem.pstr - str);
*kp = k;
return 0;
}
}
k++;
}
return 1; /* 1: root node ending. */
}
#endif
#ifdef USE_BACKREF_WITH_LEVEL
static int mem_is_in_memp(int mem, int num, UChar* memp)
{
int i;
MemNumType m;
for (i = 0; i < num; i++) {
GET_MEMNUM_INC(m, memp);
if (mem == (int )m) return 1;
}
return 0;
}
static int backref_match_at_nested_level(regex_t* reg
, OnigStackType* top, OnigStackType* stk_base
, int ignore_case, int case_fold_flag
, int nest, int mem_num, UChar* memp, UChar** s, const UChar* send)
{
UChar *ss, *p, *pstart, *pend = NULL_UCHARP;
int level;
OnigStackType* k;
level = 0;
k = top;
k--;
while (k >= stk_base) {
if (k->type == STK_CALL_FRAME) {
level--;
}
else if (k->type == STK_RETURN) {
level++;
}
else if (level == nest) {
if (k->type == STK_MEM_START) {
if (mem_is_in_memp(k->u.mem.num, mem_num, memp)) {
pstart = k->u.mem.pstr;
if (pend != NULL_UCHARP) {
if (pend - pstart > send - *s) return 0; /* or goto next_mem; */
p = pstart;
ss = *s;
if (ignore_case != 0) {
if (string_cmp_ic(reg->enc, case_fold_flag,
pstart, &ss, (int )(pend - pstart)) == 0)
return 0; /* or goto next_mem; */
}
else {
while (p < pend) {
if (*p++ != *ss++) return 0; /* or goto next_mem; */
}
}
*s = ss;
return 1;
}
}
}
else if (k->type == STK_MEM_END) {
if (mem_is_in_memp(k->u.mem.num, mem_num, memp)) {
pend = k->u.mem.pstr;
}
}
}
k--;
}
return 0;
}
#endif /* USE_BACKREF_WITH_LEVEL */
#ifdef ONIG_DEBUG_STATISTICS
#define USE_TIMEOFDAY
#ifdef USE_TIMEOFDAY
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
static struct timeval ts, te;
#define GETTIME(t) gettimeofday(&(t), (struct timezone* )0)
#define TIMEDIFF(te,ts) (((te).tv_usec - (ts).tv_usec) + \
(((te).tv_sec - (ts).tv_sec)*1000000))
#else
#ifdef HAVE_SYS_TIMES_H
#include <sys/times.h>
#endif
static struct tms ts, te;
#define GETTIME(t) times(&(t))
#define TIMEDIFF(te,ts) ((te).tms_utime - (ts).tms_utime)
#endif
static int OpCounter[256];
static int OpPrevCounter[256];
static unsigned long OpTime[256];
static int OpCurr = OP_FINISH;
static int OpPrevTarget = OP_FAIL;
static int MaxStackDepth = 0;
#define MOP_IN(opcode) do {\
if (opcode == OpPrevTarget) OpPrevCounter[OpCurr]++;\
OpCurr = opcode;\
OpCounter[opcode]++;\
GETTIME(ts);\
} while(0)
#define MOP_OUT do {\
GETTIME(te);\
OpTime[OpCurr] += TIMEDIFF(te, ts);\
} while(0)
extern void
onig_statistics_init(void)
{
int i;
for (i = 0; i < 256; i++) {
OpCounter[i] = OpPrevCounter[i] = 0; OpTime[i] = 0;
}
MaxStackDepth = 0;
}
extern int
onig_print_statistics(FILE* f)
{
int r;
int i;
r = fprintf(f, " count prev time\n");
if (r < 0) return -1;
for (i = 0; OnigOpInfo[i].opcode >= 0; i++) {
r = fprintf(f, "%8d: %8d: %10ld: %s\n",
OpCounter[i], OpPrevCounter[i], OpTime[i], OnigOpInfo[i].name);
if (r < 0) return -1;
}
r = fprintf(f, "\nmax stack depth: %d\n", MaxStackDepth);
if (r < 0) return -1;
return 0;
}
#define STACK_INC do {\
stk++;\
if (stk - stk_base > MaxStackDepth) \
MaxStackDepth = stk - stk_base;\
} while(0)
#else
#define STACK_INC stk++
#define MOP_IN(opcode)
#define MOP_OUT
#endif
/* matching region of POSIX API */
typedef int regoff_t;
typedef struct {
regoff_t rm_so;
regoff_t rm_eo;
} posix_regmatch_t;
/* match data(str - end) from position (sstart). */
/* if sstart == str then set sprev to NULL. */
static int
match_at(regex_t* reg, const UChar* str, const UChar* end,
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
const UChar* right_range,
#endif
const UChar* sstart, UChar* sprev, OnigMatchArg* msa)
{
static UChar FinishCode[] = { OP_FINISH };
int i, n, num_mem, best_len, pop_level;
LengthType tlen, tlen2;
MemNumType mem;
RelAddrType addr;
UChar *s, *q, *sbegin;
int is_alloca;
char *alloc_base;
OnigStackType *stk_base, *stk, *stk_end;
OnigStackType *stkp; /* used as any purpose. */
OnigStackIndex si;
OnigStackIndex *repeat_stk;
OnigStackIndex *mem_start_stk, *mem_end_stk;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
int scv;
unsigned char* state_check_buff = msa->state_check_buff;
int num_comb_exp_check = reg->num_comb_exp_check;
#endif
UChar *p = reg->p;
OnigOptionType option = reg->options;
OnigEncoding encode = reg->enc;
OnigCaseFoldType case_fold_flag = reg->case_fold_flag;
//n = reg->num_repeat + reg->num_mem * 2;
pop_level = reg->stack_pop_level;
num_mem = reg->num_mem;
STACK_INIT(INIT_MATCH_STACK_SIZE);
UPDATE_FOR_STACK_REALLOC;
for (i = 1; i <= num_mem; i++) {
mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX;
}
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "match_at: str: %d, end: %d, start: %d, sprev: %d\n",
(int )str, (int )end, (int )sstart, (int )sprev);
fprintf(stderr, "size: %d, start offset: %d\n",
(int )(end - str), (int )(sstart - str));
#endif
STACK_PUSH_ENSURED(STK_ALT, FinishCode); /* bottom stack */
best_len = ONIG_MISMATCH;
s = (UChar* )sstart;
while (1) {
#ifdef ONIG_DEBUG_MATCH
{
UChar *q, *bp, buf[50];
int len;
fprintf(stderr, "%4d> \"", (int )(s - str));
bp = buf;
for (i = 0, q = s; i < 7 && q < end; i++) {
len = enclen(encode, q);
while (len-- > 0) *bp++ = *q++;
}
if (q < end) { xmemcpy(bp, "...\"", 4); bp += 4; }
else { xmemcpy(bp, "\"", 1); bp += 1; }
*bp = 0;
fputs((char* )buf, stderr);
for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr);
onig_print_compiled_byte_code(stderr, p, NULL, encode);
fprintf(stderr, "\n");
}
#endif
sbegin = s;
switch (*p++) {
case OP_END: MOP_IN(OP_END);
n = s - sstart;
if (n > best_len) {
OnigRegion* region;
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(option)) {
if (n > msa->best_len) {
msa->best_len = n;
msa->best_s = (UChar* )sstart;
}
else
goto end_best_len;
}
#endif
best_len = n;
region = msa->region;
if (region) {
#ifdef USE_POSIX_API_REGION_OPTION
if (IS_POSIX_REGION(msa->options)) {
posix_regmatch_t* rmt = (posix_regmatch_t* )region;
rmt[0].rm_so = sstart - str;
rmt[0].rm_eo = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
rmt[i].rm_so = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
rmt[i].rm_so = (UChar* )((void* )(mem_start_stk[i])) - str;
rmt[i].rm_eo = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS;
}
}
}
else {
#endif /* USE_POSIX_API_REGION_OPTION */
region->beg[0] = sstart - str;
region->end[0] = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
region->beg[i] = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
region->beg[i] = (UChar* )((void* )mem_start_stk[i]) - str;
region->end[i] = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
}
#ifdef USE_CAPTURE_HISTORY
if (reg->capture_history != 0) {
int r;
OnigCaptureTreeNode* node;
if (IS_NULL(region->history_root)) {
region->history_root = node = history_node_new();
CHECK_NULL_RETURN_MEMERR(node);
}
else {
node = region->history_root;
history_tree_clear(node);
}
node->group = 0;
node->beg = sstart - str;
node->end = s - str;
stkp = stk_base;
r = make_capture_history_tree(region->history_root, &stkp,
stk, (UChar* )str, reg);
if (r < 0) {
best_len = r; /* error code */
goto finish;
}
}
#endif /* USE_CAPTURE_HISTORY */
#ifdef USE_POSIX_API_REGION_OPTION
} /* else IS_POSIX_REGION() */
#endif
} /* if (region) */
} /* n > best_len */
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
end_best_len:
#endif
MOP_OUT;
if (IS_FIND_CONDITION(option)) {
if (IS_FIND_NOT_EMPTY(option) && s == sstart) {
best_len = ONIG_MISMATCH;
goto fail; /* for retry */
}
if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) {
goto fail; /* for retry */
}
}
/* default behavior: return first-matching result. */
goto finish;
break;
case OP_EXACT1: MOP_IN(OP_EXACT1);
DATA_ENSURE(1);
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
break;
case OP_EXACT1_IC: MOP_IN(OP_EXACT1_IC);
{
int len;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) {
goto fail;
}
p++; q++;
}
}
MOP_OUT;
break;
case OP_EXACT2: MOP_IN(OP_EXACT2);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT3: MOP_IN(OP_EXACT3);
DATA_ENSURE(3);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT4: MOP_IN(OP_EXACT4);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT5: MOP_IN(OP_EXACT5);
DATA_ENSURE(5);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTN: MOP_IN(OP_EXACTN);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen);
while (tlen-- > 0) {
if (*p++ != *s++) goto fail;
}
sprev = s - 1;
MOP_OUT;
continue;
break;
case OP_EXACTN_IC: MOP_IN(OP_EXACTN_IC);
{
int len;
UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
GET_LENGTH_INC(tlen, p);
endp = p + tlen;
while (p < endp) {
sprev = s;
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) goto fail;
p++; q++;
}
}
}
MOP_OUT;
continue;
break;
case OP_EXACTMB2N1: MOP_IN(OP_EXACTMB2N1);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
break;
case OP_EXACTMB2N2: MOP_IN(OP_EXACTMB2N2);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N3: MOP_IN(OP_EXACTMB2N3);
DATA_ENSURE(6);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N: MOP_IN(OP_EXACTMB2N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 2);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 2;
MOP_OUT;
continue;
break;
case OP_EXACTMB3N: MOP_IN(OP_EXACTMB3N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 3);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 3;
MOP_OUT;
continue;
break;
case OP_EXACTMBN: MOP_IN(OP_EXACTMBN);
GET_LENGTH_INC(tlen, p); /* mb-len */
GET_LENGTH_INC(tlen2, p); /* string len */
tlen2 *= tlen;
DATA_ENSURE(tlen2);
while (tlen2-- > 0) {
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - tlen;
MOP_OUT;
continue;
break;
case OP_CCLASS: MOP_IN(OP_CCLASS);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s); /* OP_CCLASS can match mb-code. \D, \S */
MOP_OUT;
break;
case OP_CCLASS_MB: MOP_IN(OP_CCLASS_MB);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail;
cclass_mb:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len;
DATA_ENSURE(1);
mb_len = enclen(encode, s);
DATA_ENSURE(mb_len);
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (! onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (! onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
MOP_OUT;
break;
case OP_CCLASS_MIX: MOP_IN(OP_CCLASS_MIX);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) == 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NOT: MOP_IN(OP_CCLASS_NOT);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_CCLASS_MB_NOT: MOP_IN(OP_CCLASS_MB_NOT);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) {
s++;
GET_LENGTH_INC(tlen, p);
p += tlen;
goto cc_mb_not_success;
}
cclass_mb_not:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len = enclen(encode, s);
if (! DATA_ENSURE_CHECK(mb_len)) {
DATA_ENSURE(1);
s = (UChar* )end;
p += tlen;
goto cc_mb_not_success;
}
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
cc_mb_not_success:
MOP_OUT;
break;
case OP_CCLASS_MIX_NOT: MOP_IN(OP_CCLASS_MIX_NOT);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb_not;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) != 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NODE: MOP_IN(OP_CCLASS_NODE);
{
OnigCodePoint code;
void *node;
int mb_len;
UChar *ss;
DATA_ENSURE(1);
GET_POINTER_INC(node, p);
mb_len = enclen(encode, s);
ss = s;
s += mb_len;
DATA_ENSURE(0);
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
if (onig_is_code_in_cc_len(mb_len, code, node) == 0) goto fail;
}
MOP_OUT;
break;
case OP_ANYCHAR: MOP_IN(OP_ANYCHAR);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_ML: MOP_IN(OP_ANYCHAR_ML);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_STAR: MOP_IN(OP_ANYCHAR_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR: MOP_IN(OP_ANYCHAR_ML_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
case OP_ANYCHAR_STAR_PEEK_NEXT: MOP_IN(OP_ANYCHAR_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
p++;
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR_PEEK_NEXT:MOP_IN(OP_ANYCHAR_ML_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
p++;
MOP_OUT;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_ANYCHAR_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_STATE_CHECK_ANYCHAR_ML_STAR:
MOP_IN(OP_STATE_CHECK_ANYCHAR_ML_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_WORD: MOP_IN(OP_WORD);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_NOT_WORD: MOP_IN(OP_NOT_WORD);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_WORD_BOUND: MOP_IN(OP_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (! ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
== ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
case OP_NOT_WORD_BOUND: MOP_IN(OP_NOT_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
!= ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
#ifdef USE_WORD_BEGIN_END
case OP_WORD_BEGIN: MOP_IN(OP_WORD_BEGIN);
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) {
if (ON_STR_BEGIN(s) || !ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
case OP_WORD_END: MOP_IN(OP_WORD_END);
if (!ON_STR_BEGIN(s) && ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
if (ON_STR_END(s) || !ONIGENC_IS_MBC_WORD(encode, s, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
#endif
case OP_BEGIN_BUF: MOP_IN(OP_BEGIN_BUF);
if (! ON_STR_BEGIN(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_END_BUF: MOP_IN(OP_END_BUF);
if (! ON_STR_END(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_BEGIN_LINE: MOP_IN(OP_BEGIN_LINE);
if (ON_STR_BEGIN(s)) {
if (IS_NOTBOL(msa->options)) goto fail;
MOP_OUT;
continue;
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) {
MOP_OUT;
continue;
}
goto fail;
break;
case OP_END_LINE: MOP_IN(OP_END_LINE);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
MOP_OUT;
continue;
}
#endif
goto fail;
break;
case OP_SEMI_END_BUF: MOP_IN(OP_SEMI_END_BUF);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) &&
ON_STR_END(s + enclen(encode, s))) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
UChar* ss = s + enclen(encode, s);
ss += enclen(encode, ss);
if (ON_STR_END(ss)) {
MOP_OUT;
continue;
}
}
#endif
goto fail;
break;
case OP_BEGIN_POSITION: MOP_IN(OP_BEGIN_POSITION);
if (s != msa->start)
goto fail;
MOP_OUT;
continue;
break;
case OP_MEMORY_START_PUSH: MOP_IN(OP_MEMORY_START_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_START(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_START: MOP_IN(OP_MEMORY_START);
GET_MEMNUM_INC(mem, p);
mem_start_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_PUSH: MOP_IN(OP_MEMORY_END_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_END(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END: MOP_IN(OP_MEMORY_END);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
#ifdef USE_SUBEXP_CALL
case OP_MEMORY_END_PUSH_REC: MOP_IN(OP_MEMORY_END_PUSH_REC);
GET_MEMNUM_INC(mem, p);
STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */
STACK_PUSH_MEM_END(mem, s);
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_REC: MOP_IN(OP_MEMORY_END_REC);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
STACK_GET_MEM_START(mem, stkp);
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
else
mem_start_stk[mem] = (OnigStackIndex )((void* )stkp->u.mem.pstr);
STACK_PUSH_MEM_END_MARK(mem);
MOP_OUT;
continue;
break;
#endif
case OP_BACKREF1: MOP_IN(OP_BACKREF1);
mem = 1;
goto backref;
break;
case OP_BACKREF2: MOP_IN(OP_BACKREF2);
mem = 2;
goto backref;
break;
case OP_BACKREFN: MOP_IN(OP_BACKREFN);
GET_MEMNUM_INC(mem, p);
backref:
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP(pstart, s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREFN_IC: MOP_IN(OP_BACKREFN_IC);
GET_MEMNUM_INC(mem, p);
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP_IC(case_fold_flag, pstart, &s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI: MOP_IN(OP_BACKREF_MULTI);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE(pstart, swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI_IC: MOP_IN(OP_BACKREF_MULTI_IC);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
#ifdef USE_BACKREF_WITH_LEVEL
case OP_BACKREF_WITH_LEVEL:
{
int len;
OnigOptionType ic;
LengthType level;
GET_OPTION_INC(ic, p);
GET_LENGTH_INC(level, p);
GET_LENGTH_INC(tlen, p);
sprev = s;
if (backref_match_at_nested_level(reg, stk, stk_base, ic
, case_fold_flag, (int )level, (int )tlen, p, &s, end)) {
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * tlen);
}
else
goto fail;
MOP_OUT;
continue;
}
break;
#endif
#if 0 /* no need: IS_DYNAMIC_OPTION() == 0 */
case OP_SET_OPTION_PUSH: MOP_IN(OP_SET_OPTION_PUSH);
GET_OPTION_INC(option, p);
STACK_PUSH_ALT(p, s, sprev);
p += SIZE_OP_SET_OPTION + SIZE_OP_FAIL;
MOP_OUT;
continue;
break;
case OP_SET_OPTION: MOP_IN(OP_SET_OPTION);
GET_OPTION_INC(option, p);
MOP_OUT;
continue;
break;
#endif
case OP_NULL_CHECK_START: MOP_IN(OP_NULL_CHECK_START);
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_PUSH_NULL_CHECK_START(mem, s);
MOP_OUT;
continue;
break;
case OP_NULL_CHECK_END: MOP_IN(OP_NULL_CHECK_END);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK(isnull, mem, s);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
null_check_found:
/* empty loop founded, skip next instruction */
switch (*p++) {
case OP_JUMP:
case OP_PUSH:
p += SIZE_RELADDR;
break;
case OP_REPEAT_INC:
case OP_REPEAT_INC_NG:
case OP_REPEAT_INC_SG:
case OP_REPEAT_INC_NG_SG:
p += SIZE_MEMNUM;
break;
default:
goto unexpected_bytecode_error;
break;
}
}
}
MOP_OUT;
continue;
break;
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
case OP_NULL_CHECK_END_MEMST: MOP_IN(OP_NULL_CHECK_END_MEMST);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK_MEMST(isnull, mem, s, reg);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
}
MOP_OUT;
continue;
break;
#endif
#ifdef USE_SUBEXP_CALL
case OP_NULL_CHECK_END_MEMST_PUSH:
MOP_IN(OP_NULL_CHECK_END_MEMST_PUSH);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
STACK_NULL_CHECK_MEMST_REC(isnull, mem, s, reg);
#else
STACK_NULL_CHECK_REC(isnull, mem, s);
#endif
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST_PUSH: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
else {
STACK_PUSH_NULL_CHECK_END(mem);
}
}
MOP_OUT;
continue;
break;
#endif
case OP_JUMP: MOP_IN(OP_JUMP);
GET_RELADDR_INC(addr, p);
p += addr;
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_PUSH: MOP_IN(OP_PUSH);
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_PUSH: MOP_IN(OP_STATE_CHECK_PUSH);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
MOP_OUT;
continue;
break;
case OP_STATE_CHECK_PUSH_OR_JUMP: MOP_IN(OP_STATE_CHECK_PUSH_OR_JUMP);
GET_STATE_CHECK_NUM_INC(mem, p);
GET_RELADDR_INC(addr, p);
STATE_CHECK_VAL(scv, mem);
if (scv) {
p += addr;
}
else {
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
}
MOP_OUT;
continue;
break;
case OP_STATE_CHECK: MOP_IN(OP_STATE_CHECK);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_STATE_CHECK(s, mem);
MOP_OUT;
continue;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_POP: MOP_IN(OP_POP);
STACK_POP_ONE;
MOP_OUT;
continue;
break;
case OP_PUSH_OR_JUMP_EXACT1: MOP_IN(OP_PUSH_OR_JUMP_EXACT1);
GET_RELADDR_INC(addr, p);
if (*p == *s && DATA_ENSURE_CHECK1) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p += (addr + 1);
MOP_OUT;
continue;
break;
case OP_PUSH_IF_PEEK_NEXT: MOP_IN(OP_PUSH_IF_PEEK_NEXT);
GET_RELADDR_INC(addr, p);
if (*p == *s) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p++;
MOP_OUT;
continue;
break;
case OP_REPEAT: MOP_IN(OP_REPEAT);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p + addr, s, sprev);
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_NG: MOP_IN(OP_REPEAT_NG);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p, s, sprev);
p += addr;
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_INC: MOP_IN(OP_REPEAT_INC);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc:
stkp->u.repeat.count++;
if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) {
/* end of repeat. Nothing to do. */
}
else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
STACK_PUSH_ALT(p, s, sprev);
p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */
}
else {
p = stkp->u.repeat.pcode;
}
STACK_PUSH_REPEAT_INC(si);
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_SG: MOP_IN(OP_REPEAT_INC_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc;
break;
case OP_REPEAT_INC_NG: MOP_IN(OP_REPEAT_INC_NG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc_ng:
stkp->u.repeat.count++;
if (stkp->u.repeat.count < reg->repeat_range[mem].upper) {
if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
UChar* pcode = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
STACK_PUSH_ALT(pcode, s, sprev);
}
else {
p = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
}
}
else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) {
STACK_PUSH_REPEAT_INC(si);
}
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_NG_SG: MOP_IN(OP_REPEAT_INC_NG_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc_ng;
break;
case OP_PUSH_POS: MOP_IN(OP_PUSH_POS);
STACK_PUSH_POS(s, sprev);
MOP_OUT;
continue;
break;
case OP_POP_POS: MOP_IN(OP_POP_POS);
{
STACK_POS_END(stkp);
s = stkp->u.state.pstr;
sprev = stkp->u.state.pstr_prev;
}
MOP_OUT;
continue;
break;
case OP_PUSH_POS_NOT: MOP_IN(OP_PUSH_POS_NOT);
GET_RELADDR_INC(addr, p);
STACK_PUSH_POS_NOT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
case OP_FAIL_POS: MOP_IN(OP_FAIL_POS);
STACK_POP_TIL_POS_NOT;
goto fail;
break;
case OP_PUSH_STOP_BT: MOP_IN(OP_PUSH_STOP_BT);
STACK_PUSH_STOP_BT;
MOP_OUT;
continue;
break;
case OP_POP_STOP_BT: MOP_IN(OP_POP_STOP_BT);
STACK_STOP_BT_END;
MOP_OUT;
continue;
break;
case OP_LOOK_BEHIND: MOP_IN(OP_LOOK_BEHIND);
GET_LENGTH_INC(tlen, p);
s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(s)) goto fail;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
MOP_OUT;
continue;
break;
case OP_PUSH_LOOK_BEHIND_NOT: MOP_IN(OP_PUSH_LOOK_BEHIND_NOT);
GET_RELADDR_INC(addr, p);
GET_LENGTH_INC(tlen, p);
q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(q)) {
/* too short case -> success. ex. /(?<!XXX)a/.match("a")
If you want to change to fail, replace following line. */
p += addr;
/* goto fail; */
}
else {
STACK_PUSH_LOOK_BEHIND_NOT(p + addr, s, sprev);
s = q;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
}
MOP_OUT;
continue;
break;
case OP_FAIL_LOOK_BEHIND_NOT: MOP_IN(OP_FAIL_LOOK_BEHIND_NOT);
STACK_POP_TIL_LOOK_BEHIND_NOT;
goto fail;
break;
#ifdef USE_SUBEXP_CALL
case OP_CALL: MOP_IN(OP_CALL);
GET_ABSADDR_INC(addr, p);
STACK_PUSH_CALL_FRAME(p);
p = reg->p + addr;
MOP_OUT;
continue;
break;
case OP_RETURN: MOP_IN(OP_RETURN);
STACK_RETURN(p);
STACK_PUSH_RETURN;
MOP_OUT;
continue;
break;
#endif
case OP_FINISH:
goto finish;
break;
fail:
MOP_OUT;
/* fall */
case OP_FAIL: MOP_IN(OP_FAIL);
STACK_POP;
p = stk->u.state.pcode;
s = stk->u.state.pstr;
sprev = stk->u.state.pstr_prev;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
if (stk->u.state.state_check != 0) {
stk->type = STK_STATE_CHECK_MARK;
stk++;
}
#endif
MOP_OUT;
continue;
break;
default:
goto bytecode_error;
} /* end of switch */
sprev = sbegin;
} /* end of while(1) */
finish:
STACK_SAVE;
return best_len;
#ifdef ONIG_DEBUG
stack_error:
STACK_SAVE;
return ONIGERR_STACK_BUG;
#endif
bytecode_error:
STACK_SAVE;
return ONIGERR_UNDEFINED_BYTECODE;
unexpected_bytecode_error:
STACK_SAVE;
return ONIGERR_UNEXPECTED_BYTECODE;
}
static UChar*
slow_search(OnigEncoding enc, UChar* target, UChar* target_end,
const UChar* text, const UChar* text_end, UChar* text_range)
{
UChar *t, *p, *s, *end;
end = (UChar* )text_end;
end -= target_end - target - 1;
if (end > text_range)
end = text_range;
s = (UChar* )text;
while (s < end) {
if (*s == *target) {
p = s + 1;
t = target + 1;
while (t < target_end) {
if (*t != *p++)
break;
t++;
}
if (t == target_end)
return s;
}
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static int
str_lower_case_match(OnigEncoding enc, int case_fold_flag,
const UChar* t, const UChar* tend,
const UChar* p, const UChar* end)
{
int lowlen;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
while (t < tend) {
lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);
q = lowbuf;
while (lowlen > 0) {
if (*t++ != *q++) return 0;
lowlen--;
}
}
return 1;
}
static UChar*
slow_search_ic(OnigEncoding enc, int case_fold_flag,
UChar* target, UChar* target_end,
const UChar* text, const UChar* text_end, UChar* text_range)
{
UChar *s, *end;
end = (UChar* )text_end;
end -= target_end - target - 1;
if (end > text_range)
end = text_range;
s = (UChar* )text;
while (s < end) {
if (str_lower_case_match(enc, case_fold_flag, target, target_end,
s, text_end))
return s;
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static UChar*
slow_search_backward(OnigEncoding enc, UChar* target, UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
UChar *t, *p, *s;
s = (UChar* )text_end;
s -= (target_end - target);
if (s > text_start)
s = (UChar* )text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s);
while (s >= text) {
if (*s == *target) {
p = s + 1;
t = target + 1;
while (t < target_end) {
if (*t != *p++)
break;
t++;
}
if (t == target_end)
return s;
}
s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
static UChar*
slow_search_backward_ic(OnigEncoding enc, int case_fold_flag,
UChar* target, UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
UChar *s;
s = (UChar* )text_end;
s -= (target_end - target);
if (s > text_start)
s = (UChar* )text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s);
while (s >= text) {
if (str_lower_case_match(enc, case_fold_flag,
target, target_end, s, text_end))
return s;
s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
static UChar*
bm_search_notrev(regex_t* reg, const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end,
const UChar* text_range)
{
const UChar *s, *se, *t, *p, *end;
const UChar *tail;
int skip, tlen1;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "bm_search_notrev: text: %d, text_end: %d, text_range: %d\n",
(int )text, (int )text_end, (int )text_range);
#endif
tail = target_end - 1;
tlen1 = tail - target;
end = text_range;
if (end + tlen1 > text_end)
end = text_end - tlen1;
s = text;
if (IS_NULL(reg->int_map)) {
while (s < end) {
p = se = s + tlen1;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )s;
p--; t--;
}
skip = reg->map[*se];
t = s;
do {
s += enclen(reg->enc, s);
} while ((s - t) < skip && s < end);
}
}
else {
while (s < end) {
p = se = s + tlen1;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )s;
p--; t--;
}
skip = reg->int_map[*se];
t = s;
do {
s += enclen(reg->enc, s);
} while ((s - t) < skip && s < end);
}
}
return (UChar* )NULL;
}
static UChar*
bm_search(regex_t* reg, const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end, const UChar* text_range)
{
const UChar *s, *t, *p, *end;
const UChar *tail;
end = text_range + (target_end - target) - 1;
if (end > text_end)
end = text_end;
tail = target_end - 1;
s = text + (target_end - target) - 1;
if (IS_NULL(reg->int_map)) {
while (s < end) {
p = s;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )p;
p--; t--;
}
s += reg->map[*s];
}
}
else { /* see int_map[] */
while (s < end) {
p = s;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )p;
p--; t--;
}
s += reg->int_map[*s];
}
}
return (UChar* )NULL;
}
#ifdef USE_INT_MAP_BACKWARD
static int
set_bm_backward_skip(UChar* s, UChar* end, OnigEncoding enc ARG_UNUSED,
int** skip)
{
int i, len;
if (IS_NULL(*skip)) {
*skip = (int* )xmalloc(sizeof(int) * ONIG_CHAR_TABLE_SIZE);
if (IS_NULL(*skip)) return ONIGERR_MEMORY;
}
len = end - s;
for (i = 0; i < ONIG_CHAR_TABLE_SIZE; i++)
(*skip)[i] = len;
for (i = len - 1; i > 0; i--)
(*skip)[s[i]] = i;
return 0;
}
static UChar*
bm_search_backward(regex_t* reg, const UChar* target, const UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
const UChar *s, *t, *p;
s = text_end - (target_end - target);
if (text_start < s)
s = text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, adjust_text, s);
while (s >= text) {
p = s;
t = target;
while (t < target_end && *p == *t) {
p++; t++;
}
if (t == target_end)
return (UChar* )s;
s -= reg->int_map_backward[*s];
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, adjust_text, s);
}
return (UChar* )NULL;
}
#endif
static UChar*
map_search(OnigEncoding enc, UChar map[],
const UChar* text, const UChar* text_range)
{
const UChar *s = text;
while (s < text_range) {
if (map[*s]) return (UChar* )s;
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static UChar*
map_search_backward(OnigEncoding enc, UChar map[],
const UChar* text, const UChar* adjust_text,
const UChar* text_start)
{
const UChar *s = text_start;
while (s >= text) {
if (map[*s]) return (UChar* )s;
s = onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
extern int
onig_match(regex_t* reg, const UChar* str, const UChar* end, const UChar* at, OnigRegion* region,
OnigOptionType option)
{
int r;
UChar *prev;
OnigMatchArg msa;
MATCH_ARG_INIT(msa, reg, option, region, at);
#ifdef USE_COMBINATION_EXPLOSION_CHECK
{
int offset = at - str;
STATE_CHECK_BUFF_INIT(msa, end - str, offset, reg->num_comb_exp_check);
}
#endif
if (region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
r = onig_region_resize_clear(region, reg->num_mem + 1);
}
else
r = 0;
if (r == 0) {
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {
r = ONIGERR_INVALID_WIDE_CHAR_VALUE;
goto end;
}
}
prev = (UChar* )onigenc_get_prev_char_head(reg->enc, str, at);
r = match_at(reg, str, end,
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
end,
#endif
at, prev, &msa);
}
end:
MATCH_ARG_FREE(msa);
return r;
}
static int
forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
if (q >= end) return 0; /* fail */
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
if (p - str < reg->dmax) {
*low = (UChar* )str;
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc, str, *low);
}
else {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
#define BM_BACKWARD_SEARCH_LENGTH_THRESHOLD 100
static int
backward_search_range(regex_t* reg, const UChar* str, const UChar* end,
UChar* s, const UChar* range, UChar* adjrange,
UChar** low, UChar** high)
{
UChar *p;
range += reg->dmin;
p = s;
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
exact_method:
p = slow_search_backward(reg->enc, reg->exact, reg->exact_end,
range, adjrange, end, p);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_backward_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end,
range, adjrange, end, p);
break;
case ONIG_OPTIMIZE_EXACT_BM:
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
#ifdef USE_INT_MAP_BACKWARD
if (IS_NULL(reg->int_map_backward)) {
int r;
if (s - range < BM_BACKWARD_SEARCH_LENGTH_THRESHOLD)
goto exact_method;
r = set_bm_backward_skip(reg->exact, reg->exact_end, reg->enc,
&(reg->int_map_backward));
if (r) return r;
}
p = bm_search_backward(reg, reg->exact, reg->exact_end, range, adjrange,
end, p);
#else
goto exact_method;
#endif
break;
case ONIG_OPTIMIZE_MAP:
p = map_search_backward(reg->enc, reg->map, range, adjrange, p);
break;
}
if (p) {
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc, str, p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {
p = prev;
goto retry;
}
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = onigenc_get_prev_char_head(reg->enc, adjrange, p);
if (IS_NULL(prev)) goto fail;
if (ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {
p = prev;
goto retry;
}
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
) {
p = onigenc_get_prev_char_head(reg->enc, adjrange, p);
if (IS_NULL(p)) goto fail;
goto retry;
}
break;
}
}
/* no needs to adjust *high, *high is used as range check only */
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
*high = p - reg->dmin;
*high = onigenc_get_right_adjust_char_head(reg->enc, adjrange, *high);
}
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "backward_search_range: low: %d, high: %d\n",
(int )(*low - str), (int )(*high - str));
#endif
return 1; /* success */
}
fail:
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "backward_search_range: fail.\n");
#endif
return 0; /* fail */
}
extern int
onig_search(regex_t* reg, const UChar* str, const UChar* end,
const UChar* start, const UChar* range, OnigRegion* region, OnigOptionType option)
{
int r;
UChar *s, *prev;
OnigMatchArg msa;
const UChar *orig_start = start;
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
const UChar *orig_range = range;
#endif
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"onig_search (entry point): str: %d, end: %d, start: %d, range: %d\n",
(int )str, (int )(end - str), (int )(start - str), (int )(range - str));
#endif
if (region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
r = onig_region_resize_clear(region, reg->num_mem + 1);
if (r) goto finish_no_msa;
}
if (start > end || start < str) goto mismatch_no_msa;
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {
r = ONIGERR_INVALID_WIDE_CHAR_VALUE;
goto finish_no_msa;
}
}
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
if (! IS_FIND_LONGEST(reg->options)) {\
goto match;\
}\
}\
else goto finish; /* error */ \
}
#else
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
goto match;\
}\
else goto finish; /* error */ \
}
#endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */
#else
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_AND_RETURN_CHECK(none) \
r = match_at(reg, str, end, s, prev, &msa);\
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
if (! IS_FIND_LONGEST(reg->options)) {\
goto match;\
}\
}\
else goto finish; /* error */ \
}
#else
#define MATCH_AND_RETURN_CHECK(none) \
r = match_at(reg, str, end, s, prev, &msa);\
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
goto match;\
}\
else goto finish; /* error */ \
}
#endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */
#endif /* USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE */
/* anchor optimize: resume search range */
if (reg->anchor != 0 && str < end) {
UChar *min_semi_end, *max_semi_end;
if (reg->anchor & ANCHOR_BEGIN_POSITION) {
/* search start-position only */
begin_position:
if (range > start)
range = start + 1;
else
range = start;
}
else if (reg->anchor & ANCHOR_BEGIN_BUF) {
/* search str-position only */
if (range > start) {
if (start != str) goto mismatch_no_msa;
range = str + 1;
}
else {
if (range <= str) {
start = str;
range = str;
}
else
goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCHOR_END_BUF) {
min_semi_end = max_semi_end = (UChar* )end;
end_buf:
if ((OnigLen )(max_semi_end - str) < reg->anchor_dmin)
goto mismatch_no_msa;
if (range > start) {
if ((OnigLen )(min_semi_end - start) > reg->anchor_dmax) {
start = min_semi_end - reg->anchor_dmax;
if (start < end)
start = onigenc_get_right_adjust_char_head(reg->enc, str, start);
}
if ((OnigLen )(max_semi_end - (range - 1)) < reg->anchor_dmin) {
range = max_semi_end - reg->anchor_dmin + 1;
}
if (start > range) goto mismatch_no_msa;
/* If start == range, match with empty at end.
Backward search is used. */
}
else {
if ((OnigLen )(min_semi_end - range) > reg->anchor_dmax) {
range = min_semi_end - reg->anchor_dmax;
}
if ((OnigLen )(max_semi_end - start) < reg->anchor_dmin) {
start = max_semi_end - reg->anchor_dmin;
start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, start);
}
if (range > start) goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCHOR_SEMI_END_BUF) {
UChar* pre_end = ONIGENC_STEP_BACK(reg->enc, str, end, 1);
max_semi_end = (UChar* )end;
if (ONIGENC_IS_MBC_NEWLINE(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
#ifdef USE_CRNL_AS_LINE_TERMINATOR
pre_end = ONIGENC_STEP_BACK(reg->enc, str, pre_end, 1);
if (IS_NOT_NULL(pre_end) &&
ONIGENC_IS_MBC_CRNL(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
}
#endif
if (min_semi_end > str && start <= min_semi_end) {
goto end_buf;
}
}
else {
min_semi_end = (UChar* )end;
goto end_buf;
}
}
else if ((reg->anchor & ANCHOR_ANYCHAR_STAR_ML)) {
goto begin_position;
}
}
else if (str == end) { /* empty string */
static const UChar* address_for_empty_string = (UChar* )"";
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search: empty string.\n");
#endif
if (reg->threshold_len == 0) {
start = end = str = address_for_empty_string;
s = (UChar* )start;
prev = (UChar* )NULL;
MATCH_ARG_INIT(msa, reg, option, region, start);
#ifdef USE_COMBINATION_EXPLOSION_CHECK
msa.state_check_buff = (void* )0;
msa.state_check_buff_size = 0; /* NO NEED, for valgrind */
#endif
MATCH_AND_RETURN_CHECK(end);
goto mismatch;
}
goto mismatch_no_msa;
}
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search(apply anchor): end: %d, start: %d, range: %d\n",
(int )(end - str), (int )(start - str), (int )(range - str));
#endif
MATCH_ARG_INIT(msa, reg, option, region, orig_start);
#ifdef USE_COMBINATION_EXPLOSION_CHECK
{
int offset = (MIN(start, range) - str);
STATE_CHECK_BUFF_INIT(msa, end - str, offset, reg->num_comb_exp_check);
}
#endif
s = (UChar* )start;
if (range > start) { /* forward search */
if (s > str)
prev = onigenc_get_prev_char_head(reg->enc, str, s);
else
prev = (UChar* )NULL;
if (reg->optimize != ONIG_OPTIMIZE_NONE) {
UChar *sch_range, *low, *high, *low_prev;
sch_range = (UChar* )range;
if (reg->dmax != 0) {
if (reg->dmax == ONIG_INFINITE_DISTANCE)
sch_range = (UChar* )end;
else {
sch_range += reg->dmax;
if (sch_range > end) sch_range = (UChar* )end;
}
}
if ((end - start) < reg->threshold_len)
goto mismatch;
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
do {
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, &low_prev)) goto mismatch;
if (s < low) {
s = low;
prev = low_prev;
}
while (s <= high) {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
}
} while (s < range);
goto mismatch;
}
else { /* check only. */
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, (UChar** )NULL)) goto mismatch;
if ((reg->anchor & ANCHOR_ANYCHAR_STAR) != 0) {
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
if ((reg->anchor & (ANCHOR_LOOK_BEHIND | ANCHOR_PREC_READ_NOT)) == 0) {
while (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end) && s < range) {
prev = s;
s += enclen(reg->enc, s);
}
}
} while (s < range);
goto mismatch;
}
}
}
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
} while (s < range);
if (s == range) { /* because empty match with /$/. */
MATCH_AND_RETURN_CHECK(orig_range);
}
}
else { /* backward search */
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
if (orig_start < end)
orig_start += enclen(reg->enc, orig_start); /* is upper range */
#endif
if (reg->optimize != ONIG_OPTIMIZE_NONE) {
UChar *low, *high, *adjrange, *sch_start;
if (range < end)
adjrange = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, range);
else
adjrange = (UChar* )end;
if (reg->dmax != ONIG_INFINITE_DISTANCE &&
(end - range) >= reg->threshold_len) {
do {
sch_start = s + reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0)
goto mismatch;
if (s > high)
s = high;
while (s >= low) {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
}
} while (s >= range);
goto mismatch;
}
else { /* check only. */
if ((end - range) < reg->threshold_len) goto mismatch;
sch_start = s;
if (reg->dmax != 0) {
if (reg->dmax == ONIG_INFINITE_DISTANCE)
sch_start = (UChar* )end;
else {
sch_start += reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
else
sch_start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc,
start, sch_start);
}
}
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0) goto mismatch;
}
}
do {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
} while (s >= range);
}
mismatch:
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(reg->options)) {
if (msa.best_len >= 0) {
s = msa.best_s;
goto match;
}
}
#endif
r = ONIG_MISMATCH;
finish:
MATCH_ARG_FREE(msa);
/* If result is mismatch and no FIND_NOT_EMPTY option,
then the region is not set in match_at(). */
if (IS_FIND_NOT_EMPTY(reg->options) && region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
onig_region_clear(region);
}
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
mismatch_no_msa:
r = ONIG_MISMATCH;
finish_no_msa:
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
match:
MATCH_ARG_FREE(msa);
return s - str;
}
extern int
onig_scan(regex_t* reg, const UChar* str, const UChar* end,
OnigRegion* region, OnigOptionType option,
int (*scan_callback)(int, int, OnigRegion*, void*),
void* callback_arg)
{
int r;
int n;
int rs;
const UChar* start;
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
ONIG_OPTION_OFF(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING);
}
n = 0;
start = str;
while (1) {
r = onig_search(reg, str, end, start, end, region, option);
if (r >= 0) {
rs = scan_callback(n, r, region, callback_arg);
n++;
if (rs != 0)
return rs;
if (region->end[0] == start - str) {
if (start >= end) break;
start += enclen(reg->enc, start);
}
else
start = str + region->end[0];
if (start > end)
break;
}
else if (r == ONIG_MISMATCH) {
break;
}
else { /* error */
return r;
}
}
return n;
}
extern OnigEncoding
onig_get_encoding(regex_t* reg)
{
return reg->enc;
}
extern OnigOptionType
onig_get_options(regex_t* reg)
{
return reg->options;
}
extern OnigCaseFoldType
onig_get_case_fold_flag(regex_t* reg)
{
return reg->case_fold_flag;
}
extern OnigSyntaxType*
onig_get_syntax(regex_t* reg)
{
return reg->syntax;
}
extern int
onig_number_of_captures(regex_t* reg)
{
return reg->num_mem;
}
extern int
onig_number_of_capture_histories(regex_t* reg)
{
#ifdef USE_CAPTURE_HISTORY
int i, n;
n = 0;
for (i = 0; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) {
if (BIT_STATUS_AT(reg->capture_history, i) != 0)
n++;
}
return n;
#else
return 0;
#endif
}
extern void
onig_copy_encoding(OnigEncoding to, OnigEncoding from)
{
*to = *from;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3378_0 |
crossvul-cpp_data_bad_1620_0 | /*
* PgBouncer - Lightweight connection pooler for PostgreSQL.
*
* Copyright (c) 2007-2009 Marko Kreen, Skype Technologies OÜ
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, 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.
*/
/*
* Client connection handling
*/
#include "bouncer.h"
static const char *hdr2hex(const struct MBuf *data, char *buf, unsigned buflen)
{
const uint8_t *bin = data->data + data->read_pos;
unsigned int dlen;
dlen = mbuf_avail_for_read(data);
return bin2hex(bin, dlen, buf, buflen);
}
static bool check_client_passwd(PgSocket *client, const char *passwd)
{
char md5[MD5_PASSWD_LEN + 1];
const char *correct;
PgUser *user = client->auth_user;
/* disallow empty passwords */
if (!*passwd || !*user->passwd)
return false;
switch (cf_auth_type) {
case AUTH_PLAIN:
return strcmp(user->passwd, passwd) == 0;
case AUTH_CRYPT:
correct = crypt(user->passwd, (char *)client->tmp_login_salt);
return correct && strcmp(correct, passwd) == 0;
case AUTH_MD5:
if (strlen(passwd) != MD5_PASSWD_LEN)
return false;
if (!isMD5(user->passwd))
pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd);
pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5);
return strcmp(md5, passwd) == 0;
}
return false;
}
bool set_pool(PgSocket *client, const char *dbname, const char *username)
{
PgDatabase *db;
PgUser *user;
/* find database */
db = find_database(dbname);
if (!db) {
db = register_auto_database(dbname);
if (!db) {
disconnect_client(client, true, "No such database: %s", dbname);
return false;
}
else {
slog_info(client, "registered new auto-database: db = %s", dbname );
}
}
/* find user */
if (cf_auth_type == AUTH_ANY) {
/* ignore requested user */
user = NULL;
if (db->forced_user == NULL) {
slog_error(client, "auth_type=any requires forced user");
disconnect_client(client, true, "bouncer config error");
return false;
}
client->auth_user = db->forced_user;
} else {
/* the user clients wants to log in as */
user = find_user(username);
if (!user) {
disconnect_client(client, true, "No such user: %s", username);
return false;
}
client->auth_user = user;
}
/* pool user may be forced */
if (db->forced_user)
user = db->forced_user;
client->pool = get_pool(db, user);
if (!client->pool) {
disconnect_client(client, true, "no memory for pool");
return false;
}
return check_fast_fail(client);
}
static bool decide_startup_pool(PgSocket *client, PktHdr *pkt)
{
const char *username = NULL, *dbname = NULL;
const char *key, *val;
bool ok;
while (1) {
ok = mbuf_get_string(&pkt->data, &key);
if (!ok || *key == 0)
break;
ok = mbuf_get_string(&pkt->data, &val);
if (!ok)
break;
if (strcmp(key, "database") == 0) {
slog_debug(client, "got var: %s=%s", key, val);
dbname = val;
} else if (strcmp(key, "user") == 0) {
slog_debug(client, "got var: %s=%s", key, val);
username = val;
} else if (varcache_set(&client->vars, key, val)) {
slog_debug(client, "got var: %s=%s", key, val);
} else if (strlist_contains(cf_ignore_startup_params, key)) {
slog_debug(client, "ignoring startup parameter: %s=%s", key, val);
} else {
slog_warning(client, "unsupported startup parameter: %s=%s", key, val);
disconnect_client(client, true, "Unsupported startup parameter: %s", key);
return false;
}
}
if (!username || !username[0]) {
disconnect_client(client, true, "No username supplied");
return false;
}
/* if missing dbname, default to username */
if (!dbname || !dbname[0])
dbname = username;
/* check if limit allows, dont limit admin db
nb: new incoming conn will be attached to PgSocket, thus
get_active_client_count() counts it */
if (get_active_client_count() > cf_max_client_conn) {
if (strcmp(dbname, "pgbouncer") != 0) {
disconnect_client(client, true, "no more connections allowed (max_client_conn)");
return false;
}
}
/* find pool and log about it */
if (set_pool(client, dbname, username)) {
if (cf_log_connections)
slog_info(client, "login attempt: db=%s user=%s", dbname, username);
return true;
} else {
if (cf_log_connections)
slog_info(client, "login failed: db=%s user=%s", dbname, username);
return false;
}
}
/* mask to get offset into valid_crypt_salt[] */
#define SALT_MASK 0x3F
static const char valid_crypt_salt[] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static bool send_client_authreq(PgSocket *client)
{
uint8_t saltlen = 0;
int res;
int auth = cf_auth_type;
uint8_t randbuf[2];
if (auth == AUTH_CRYPT) {
saltlen = 2;
get_random_bytes(randbuf, saltlen);
client->tmp_login_salt[0] = valid_crypt_salt[randbuf[0] & SALT_MASK];
client->tmp_login_salt[1] = valid_crypt_salt[randbuf[1] & SALT_MASK];
client->tmp_login_salt[2] = 0;
} else if (cf_auth_type == AUTH_MD5) {
saltlen = 4;
get_random_bytes((void*)client->tmp_login_salt, saltlen);
} else if (auth == AUTH_ANY)
auth = AUTH_TRUST;
SEND_generic(res, client, 'R', "ib", auth, client->tmp_login_salt, saltlen);
return res;
}
/* decide on packets of client in login phase */
static bool handle_client_startup(PgSocket *client, PktHdr *pkt)
{
const char *passwd;
const uint8_t *key;
bool ok;
SBuf *sbuf = &client->sbuf;
/* don't tolerate partial packets */
if (incomplete_pkt(pkt)) {
disconnect_client(client, true, "client sent partial pkt in startup phase");
return false;
}
if (client->wait_for_welcome) {
if (finish_client_login(client)) {
/* the packet was already parsed */
sbuf_prepare_skip(sbuf, pkt->len);
return true;
} else
return false;
}
switch (pkt->type) {
case PKT_SSLREQ:
slog_noise(client, "C: req SSL");
slog_noise(client, "P: nak");
/* reject SSL attempt */
if (!sbuf_answer(&client->sbuf, "N", 1)) {
disconnect_client(client, false, "failed to nak SSL");
return false;
}
break;
case PKT_STARTUP_V2:
disconnect_client(client, true, "Old V2 protocol not supported");
return false;
case PKT_STARTUP:
if (client->pool) {
disconnect_client(client, true, "client re-sent startup pkt");
return false;
}
if (!decide_startup_pool(client, pkt))
return false;
if (client->pool->db->admin) {
if (!admin_pre_login(client))
return false;
}
if (cf_auth_type <= AUTH_TRUST || client->own_user) {
if (!finish_client_login(client))
return false;
} else {
if (!send_client_authreq(client)) {
disconnect_client(client, false, "failed to send auth req");
return false;
}
}
break;
case 'p': /* PasswordMessage */
/* haven't requested it */
if (cf_auth_type <= AUTH_TRUST) {
disconnect_client(client, true, "unrequested passwd pkt");
return false;
}
ok = mbuf_get_string(&pkt->data, &passwd);
if (ok && check_client_passwd(client, passwd)) {
if (!finish_client_login(client))
return false;
} else {
disconnect_client(client, true, "Auth failed");
return false;
}
break;
case PKT_CANCEL:
if (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN
&& mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key))
{
memcpy(client->cancel_key, key, BACKENDKEY_LEN);
accept_cancel_request(client);
} else
disconnect_client(client, false, "bad cancel request");
return false;
default:
disconnect_client(client, false, "bad packet");
return false;
}
sbuf_prepare_skip(sbuf, pkt->len);
client->request_time = get_cached_time();
return true;
}
/* decide on packets of logged-in client */
static bool handle_client_work(PgSocket *client, PktHdr *pkt)
{
SBuf *sbuf = &client->sbuf;
switch (pkt->type) {
/* one-packet queries */
case 'Q': /* Query */
if (cf_disable_pqexec) {
slog_error(client, "Client used 'Q' packet type.");
disconnect_client(client, true, "PQexec disallowed");
return false;
}
case 'F': /* FunctionCall */
/* request immediate response from server */
case 'H': /* Flush */
case 'S': /* Sync */
/* copy end markers */
case 'c': /* CopyDone(F/B) */
case 'f': /* CopyFail(F/B) */
/*
* extended protocol allows server (and thus pooler)
* to buffer packets until sync or flush is sent by client
*/
case 'P': /* Parse */
case 'E': /* Execute */
case 'C': /* Close */
case 'B': /* Bind */
case 'D': /* Describe */
case 'd': /* CopyData(F/B) */
/* update stats */
if (!client->query_start) {
client->pool->stats.request_count++;
client->query_start = get_cached_time();
}
if (client->pool->db->admin)
return admin_handle_client(client, pkt);
/* aquire server */
if (!find_server(client))
return false;
client->pool->stats.client_bytes += pkt->len;
/* tag the server as dirty */
client->link->ready = false;
client->link->idle_tx = false;
/* forward the packet */
sbuf_prepare_send(sbuf, &client->link->sbuf, pkt->len);
break;
/* client wants to go away */
default:
slog_error(client, "unknown pkt from client: %d/0x%x", pkt->type, pkt->type);
disconnect_client(client, true, "unknown pkt");
return false;
case 'X': /* Terminate */
disconnect_client(client, false, "client close request");
return false;
}
return true;
}
/* callback from SBuf */
bool client_proto(SBuf *sbuf, SBufEvent evtype, struct MBuf *data)
{
bool res = false;
PgSocket *client = container_of(sbuf, PgSocket, sbuf);
PktHdr pkt;
Assert(!is_server_socket(client));
Assert(client->sbuf.sock);
Assert(client->state != CL_FREE);
/* may happen if close failed */
if (client->state == CL_JUSTFREE)
return false;
switch (evtype) {
case SBUF_EV_CONNECT_OK:
case SBUF_EV_CONNECT_FAILED:
/* ^ those should not happen */
case SBUF_EV_RECV_FAILED:
disconnect_client(client, false, "client unexpected eof");
break;
case SBUF_EV_SEND_FAILED:
disconnect_server(client->link, false, "Server connection closed");
break;
case SBUF_EV_READ:
if (mbuf_avail_for_read(data) < NEW_HEADER_LEN && client->state != CL_LOGIN) {
slog_noise(client, "C: got partial header, trying to wait a bit");
return false;
}
if (!get_header(data, &pkt)) {
char hex[8*2 + 1];
disconnect_client(client, true, "bad packet header: '%s'",
hdr2hex(data, hex, sizeof(hex)));
return false;
}
slog_noise(client, "pkt='%c' len=%d", pkt_desc(&pkt), pkt.len);
client->request_time = get_cached_time();
switch (client->state) {
case CL_LOGIN:
res = handle_client_startup(client, &pkt);
break;
case CL_ACTIVE:
if (client->wait_for_welcome)
res = handle_client_startup(client, &pkt);
else
res = handle_client_work(client, &pkt);
break;
case CL_WAITING:
fatal("why waiting client in client_proto()");
default:
fatal("bad client state: %d", client->state);
}
break;
case SBUF_EV_FLUSH:
/* client is not interested in it */
break;
case SBUF_EV_PKT_CALLBACK:
/* unused ATM */
break;
}
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_1620_0 |
crossvul-cpp_data_good_5345_0 | /******************************************************************************
* emulate.c
*
* Generic x86 (32-bit and 64-bit) instruction decoder and emulator.
*
* Copyright (c) 2005 Keir Fraser
*
* Linux coding style, mod r/m decoder, segment base fixes, real-mode
* privileged instructions:
*
* Copyright (C) 2006 Qumranet
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* 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.
*
* From: xen-unstable 10676:af9809f51f81a3c43f276f00c81a52ef558afda4
*/
#include <linux/kvm_host.h>
#include "kvm_cache_regs.h"
#include <asm/kvm_emulate.h>
#include <linux/stringify.h>
#include <asm/debugreg.h>
#include "x86.h"
#include "tss.h"
/*
* Operand types
*/
#define OpNone 0ull
#define OpImplicit 1ull /* No generic decode */
#define OpReg 2ull /* Register */
#define OpMem 3ull /* Memory */
#define OpAcc 4ull /* Accumulator: AL/AX/EAX/RAX */
#define OpDI 5ull /* ES:DI/EDI/RDI */
#define OpMem64 6ull /* Memory, 64-bit */
#define OpImmUByte 7ull /* Zero-extended 8-bit immediate */
#define OpDX 8ull /* DX register */
#define OpCL 9ull /* CL register (for shifts) */
#define OpImmByte 10ull /* 8-bit sign extended immediate */
#define OpOne 11ull /* Implied 1 */
#define OpImm 12ull /* Sign extended up to 32-bit immediate */
#define OpMem16 13ull /* Memory operand (16-bit). */
#define OpMem32 14ull /* Memory operand (32-bit). */
#define OpImmU 15ull /* Immediate operand, zero extended */
#define OpSI 16ull /* SI/ESI/RSI */
#define OpImmFAddr 17ull /* Immediate far address */
#define OpMemFAddr 18ull /* Far address in memory */
#define OpImmU16 19ull /* Immediate operand, 16 bits, zero extended */
#define OpES 20ull /* ES */
#define OpCS 21ull /* CS */
#define OpSS 22ull /* SS */
#define OpDS 23ull /* DS */
#define OpFS 24ull /* FS */
#define OpGS 25ull /* GS */
#define OpMem8 26ull /* 8-bit zero extended memory operand */
#define OpImm64 27ull /* Sign extended 16/32/64-bit immediate */
#define OpXLat 28ull /* memory at BX/EBX/RBX + zero-extended AL */
#define OpAccLo 29ull /* Low part of extended acc (AX/AX/EAX/RAX) */
#define OpAccHi 30ull /* High part of extended acc (-/DX/EDX/RDX) */
#define OpBits 5 /* Width of operand field */
#define OpMask ((1ull << OpBits) - 1)
/*
* Opcode effective-address decode tables.
* Note that we only emulate instructions that have at least one memory
* operand (excluding implicit stack references). We assume that stack
* references and instruction fetches will never occur in special memory
* areas that require emulation. So, for example, 'mov <imm>,<reg>' need
* not be handled.
*/
/* Operand sizes: 8-bit operands or specified/overridden size. */
#define ByteOp (1<<0) /* 8-bit operands. */
/* Destination operand type. */
#define DstShift 1
#define ImplicitOps (OpImplicit << DstShift)
#define DstReg (OpReg << DstShift)
#define DstMem (OpMem << DstShift)
#define DstAcc (OpAcc << DstShift)
#define DstDI (OpDI << DstShift)
#define DstMem64 (OpMem64 << DstShift)
#define DstMem16 (OpMem16 << DstShift)
#define DstImmUByte (OpImmUByte << DstShift)
#define DstDX (OpDX << DstShift)
#define DstAccLo (OpAccLo << DstShift)
#define DstMask (OpMask << DstShift)
/* Source operand type. */
#define SrcShift 6
#define SrcNone (OpNone << SrcShift)
#define SrcReg (OpReg << SrcShift)
#define SrcMem (OpMem << SrcShift)
#define SrcMem16 (OpMem16 << SrcShift)
#define SrcMem32 (OpMem32 << SrcShift)
#define SrcImm (OpImm << SrcShift)
#define SrcImmByte (OpImmByte << SrcShift)
#define SrcOne (OpOne << SrcShift)
#define SrcImmUByte (OpImmUByte << SrcShift)
#define SrcImmU (OpImmU << SrcShift)
#define SrcSI (OpSI << SrcShift)
#define SrcXLat (OpXLat << SrcShift)
#define SrcImmFAddr (OpImmFAddr << SrcShift)
#define SrcMemFAddr (OpMemFAddr << SrcShift)
#define SrcAcc (OpAcc << SrcShift)
#define SrcImmU16 (OpImmU16 << SrcShift)
#define SrcImm64 (OpImm64 << SrcShift)
#define SrcDX (OpDX << SrcShift)
#define SrcMem8 (OpMem8 << SrcShift)
#define SrcAccHi (OpAccHi << SrcShift)
#define SrcMask (OpMask << SrcShift)
#define BitOp (1<<11)
#define MemAbs (1<<12) /* Memory operand is absolute displacement */
#define String (1<<13) /* String instruction (rep capable) */
#define Stack (1<<14) /* Stack instruction (push/pop) */
#define GroupMask (7<<15) /* Opcode uses one of the group mechanisms */
#define Group (1<<15) /* Bits 3:5 of modrm byte extend opcode */
#define GroupDual (2<<15) /* Alternate decoding of mod == 3 */
#define Prefix (3<<15) /* Instruction varies with 66/f2/f3 prefix */
#define RMExt (4<<15) /* Opcode extension in ModRM r/m if mod == 3 */
#define Escape (5<<15) /* Escape to coprocessor instruction */
#define InstrDual (6<<15) /* Alternate instruction decoding of mod == 3 */
#define ModeDual (7<<15) /* Different instruction for 32/64 bit */
#define Sse (1<<18) /* SSE Vector instruction */
/* Generic ModRM decode. */
#define ModRM (1<<19)
/* Destination is only written; never read. */
#define Mov (1<<20)
/* Misc flags */
#define Prot (1<<21) /* instruction generates #UD if not in prot-mode */
#define EmulateOnUD (1<<22) /* Emulate if unsupported by the host */
#define NoAccess (1<<23) /* Don't access memory (lea/invlpg/verr etc) */
#define Op3264 (1<<24) /* Operand is 64b in long mode, 32b otherwise */
#define Undefined (1<<25) /* No Such Instruction */
#define Lock (1<<26) /* lock prefix is allowed for the instruction */
#define Priv (1<<27) /* instruction generates #GP if current CPL != 0 */
#define No64 (1<<28)
#define PageTable (1 << 29) /* instruction used to write page table */
#define NotImpl (1 << 30) /* instruction is not implemented */
/* Source 2 operand type */
#define Src2Shift (31)
#define Src2None (OpNone << Src2Shift)
#define Src2Mem (OpMem << Src2Shift)
#define Src2CL (OpCL << Src2Shift)
#define Src2ImmByte (OpImmByte << Src2Shift)
#define Src2One (OpOne << Src2Shift)
#define Src2Imm (OpImm << Src2Shift)
#define Src2ES (OpES << Src2Shift)
#define Src2CS (OpCS << Src2Shift)
#define Src2SS (OpSS << Src2Shift)
#define Src2DS (OpDS << Src2Shift)
#define Src2FS (OpFS << Src2Shift)
#define Src2GS (OpGS << Src2Shift)
#define Src2Mask (OpMask << Src2Shift)
#define Mmx ((u64)1 << 40) /* MMX Vector instruction */
#define Aligned ((u64)1 << 41) /* Explicitly aligned (e.g. MOVDQA) */
#define Unaligned ((u64)1 << 42) /* Explicitly unaligned (e.g. MOVDQU) */
#define Avx ((u64)1 << 43) /* Advanced Vector Extensions */
#define Fastop ((u64)1 << 44) /* Use opcode::u.fastop */
#define NoWrite ((u64)1 << 45) /* No writeback */
#define SrcWrite ((u64)1 << 46) /* Write back src operand */
#define NoMod ((u64)1 << 47) /* Mod field is ignored */
#define Intercept ((u64)1 << 48) /* Has valid intercept field */
#define CheckPerm ((u64)1 << 49) /* Has valid check_perm field */
#define PrivUD ((u64)1 << 51) /* #UD instead of #GP on CPL > 0 */
#define NearBranch ((u64)1 << 52) /* Near branches */
#define No16 ((u64)1 << 53) /* No 16 bit operand */
#define IncSP ((u64)1 << 54) /* SP is incremented before ModRM calc */
#define DstXacc (DstAccLo | SrcAccHi | SrcWrite)
#define X2(x...) x, x
#define X3(x...) X2(x), x
#define X4(x...) X2(x), X2(x)
#define X5(x...) X4(x), x
#define X6(x...) X4(x), X2(x)
#define X7(x...) X4(x), X3(x)
#define X8(x...) X4(x), X4(x)
#define X16(x...) X8(x), X8(x)
#define NR_FASTOP (ilog2(sizeof(ulong)) + 1)
#define FASTOP_SIZE 8
/*
* fastop functions have a special calling convention:
*
* dst: rax (in/out)
* src: rdx (in/out)
* src2: rcx (in)
* flags: rflags (in/out)
* ex: rsi (in:fastop pointer, out:zero if exception)
*
* Moreover, they are all exactly FASTOP_SIZE bytes long, so functions for
* different operand sizes can be reached by calculation, rather than a jump
* table (which would be bigger than the code).
*
* fastop functions are declared as taking a never-defined fastop parameter,
* so they can't be called from C directly.
*/
struct fastop;
struct opcode {
u64 flags : 56;
u64 intercept : 8;
union {
int (*execute)(struct x86_emulate_ctxt *ctxt);
const struct opcode *group;
const struct group_dual *gdual;
const struct gprefix *gprefix;
const struct escape *esc;
const struct instr_dual *idual;
const struct mode_dual *mdual;
void (*fastop)(struct fastop *fake);
} u;
int (*check_perm)(struct x86_emulate_ctxt *ctxt);
};
struct group_dual {
struct opcode mod012[8];
struct opcode mod3[8];
};
struct gprefix {
struct opcode pfx_no;
struct opcode pfx_66;
struct opcode pfx_f2;
struct opcode pfx_f3;
};
struct escape {
struct opcode op[8];
struct opcode high[64];
};
struct instr_dual {
struct opcode mod012;
struct opcode mod3;
};
struct mode_dual {
struct opcode mode32;
struct opcode mode64;
};
#define EFLG_RESERVED_ZEROS_MASK 0xffc0802a
enum x86_transfer_type {
X86_TRANSFER_NONE,
X86_TRANSFER_CALL_JMP,
X86_TRANSFER_RET,
X86_TRANSFER_TASK_SWITCH,
};
static ulong reg_read(struct x86_emulate_ctxt *ctxt, unsigned nr)
{
if (!(ctxt->regs_valid & (1 << nr))) {
ctxt->regs_valid |= 1 << nr;
ctxt->_regs[nr] = ctxt->ops->read_gpr(ctxt, nr);
}
return ctxt->_regs[nr];
}
static ulong *reg_write(struct x86_emulate_ctxt *ctxt, unsigned nr)
{
ctxt->regs_valid |= 1 << nr;
ctxt->regs_dirty |= 1 << nr;
return &ctxt->_regs[nr];
}
static ulong *reg_rmw(struct x86_emulate_ctxt *ctxt, unsigned nr)
{
reg_read(ctxt, nr);
return reg_write(ctxt, nr);
}
static void writeback_registers(struct x86_emulate_ctxt *ctxt)
{
unsigned reg;
for_each_set_bit(reg, (ulong *)&ctxt->regs_dirty, 16)
ctxt->ops->write_gpr(ctxt, reg, ctxt->_regs[reg]);
}
static void invalidate_registers(struct x86_emulate_ctxt *ctxt)
{
ctxt->regs_dirty = 0;
ctxt->regs_valid = 0;
}
/*
* These EFLAGS bits are restored from saved value during emulation, and
* any changes are written back to the saved value after emulation.
*/
#define EFLAGS_MASK (X86_EFLAGS_OF|X86_EFLAGS_SF|X86_EFLAGS_ZF|X86_EFLAGS_AF|\
X86_EFLAGS_PF|X86_EFLAGS_CF)
#ifdef CONFIG_X86_64
#define ON64(x) x
#else
#define ON64(x)
#endif
static int fastop(struct x86_emulate_ctxt *ctxt, void (*fop)(struct fastop *));
#define FOP_FUNC(name) \
".align " __stringify(FASTOP_SIZE) " \n\t" \
".type " name ", @function \n\t" \
name ":\n\t"
#define FOP_RET "ret \n\t"
#define FOP_START(op) \
extern void em_##op(struct fastop *fake); \
asm(".pushsection .text, \"ax\" \n\t" \
".global em_" #op " \n\t" \
FOP_FUNC("em_" #op)
#define FOP_END \
".popsection")
#define FOPNOP() \
FOP_FUNC(__stringify(__UNIQUE_ID(nop))) \
FOP_RET
#define FOP1E(op, dst) \
FOP_FUNC(#op "_" #dst) \
"10: " #op " %" #dst " \n\t" FOP_RET
#define FOP1EEX(op, dst) \
FOP1E(op, dst) _ASM_EXTABLE(10b, kvm_fastop_exception)
#define FASTOP1(op) \
FOP_START(op) \
FOP1E(op##b, al) \
FOP1E(op##w, ax) \
FOP1E(op##l, eax) \
ON64(FOP1E(op##q, rax)) \
FOP_END
/* 1-operand, using src2 (for MUL/DIV r/m) */
#define FASTOP1SRC2(op, name) \
FOP_START(name) \
FOP1E(op, cl) \
FOP1E(op, cx) \
FOP1E(op, ecx) \
ON64(FOP1E(op, rcx)) \
FOP_END
/* 1-operand, using src2 (for MUL/DIV r/m), with exceptions */
#define FASTOP1SRC2EX(op, name) \
FOP_START(name) \
FOP1EEX(op, cl) \
FOP1EEX(op, cx) \
FOP1EEX(op, ecx) \
ON64(FOP1EEX(op, rcx)) \
FOP_END
#define FOP2E(op, dst, src) \
FOP_FUNC(#op "_" #dst "_" #src) \
#op " %" #src ", %" #dst " \n\t" FOP_RET
#define FASTOP2(op) \
FOP_START(op) \
FOP2E(op##b, al, dl) \
FOP2E(op##w, ax, dx) \
FOP2E(op##l, eax, edx) \
ON64(FOP2E(op##q, rax, rdx)) \
FOP_END
/* 2 operand, word only */
#define FASTOP2W(op) \
FOP_START(op) \
FOPNOP() \
FOP2E(op##w, ax, dx) \
FOP2E(op##l, eax, edx) \
ON64(FOP2E(op##q, rax, rdx)) \
FOP_END
/* 2 operand, src is CL */
#define FASTOP2CL(op) \
FOP_START(op) \
FOP2E(op##b, al, cl) \
FOP2E(op##w, ax, cl) \
FOP2E(op##l, eax, cl) \
ON64(FOP2E(op##q, rax, cl)) \
FOP_END
/* 2 operand, src and dest are reversed */
#define FASTOP2R(op, name) \
FOP_START(name) \
FOP2E(op##b, dl, al) \
FOP2E(op##w, dx, ax) \
FOP2E(op##l, edx, eax) \
ON64(FOP2E(op##q, rdx, rax)) \
FOP_END
#define FOP3E(op, dst, src, src2) \
FOP_FUNC(#op "_" #dst "_" #src "_" #src2) \
#op " %" #src2 ", %" #src ", %" #dst " \n\t" FOP_RET
/* 3-operand, word-only, src2=cl */
#define FASTOP3WCL(op) \
FOP_START(op) \
FOPNOP() \
FOP3E(op##w, ax, dx, cl) \
FOP3E(op##l, eax, edx, cl) \
ON64(FOP3E(op##q, rax, rdx, cl)) \
FOP_END
/* Special case for SETcc - 1 instruction per cc */
#define FOP_SETCC(op) \
".align 4 \n\t" \
".type " #op ", @function \n\t" \
#op ": \n\t" \
#op " %al \n\t" \
FOP_RET
asm(".global kvm_fastop_exception \n"
"kvm_fastop_exception: xor %esi, %esi; ret");
FOP_START(setcc)
FOP_SETCC(seto)
FOP_SETCC(setno)
FOP_SETCC(setc)
FOP_SETCC(setnc)
FOP_SETCC(setz)
FOP_SETCC(setnz)
FOP_SETCC(setbe)
FOP_SETCC(setnbe)
FOP_SETCC(sets)
FOP_SETCC(setns)
FOP_SETCC(setp)
FOP_SETCC(setnp)
FOP_SETCC(setl)
FOP_SETCC(setnl)
FOP_SETCC(setle)
FOP_SETCC(setnle)
FOP_END;
FOP_START(salc) "pushf; sbb %al, %al; popf \n\t" FOP_RET
FOP_END;
static int emulator_check_intercept(struct x86_emulate_ctxt *ctxt,
enum x86_intercept intercept,
enum x86_intercept_stage stage)
{
struct x86_instruction_info info = {
.intercept = intercept,
.rep_prefix = ctxt->rep_prefix,
.modrm_mod = ctxt->modrm_mod,
.modrm_reg = ctxt->modrm_reg,
.modrm_rm = ctxt->modrm_rm,
.src_val = ctxt->src.val64,
.dst_val = ctxt->dst.val64,
.src_bytes = ctxt->src.bytes,
.dst_bytes = ctxt->dst.bytes,
.ad_bytes = ctxt->ad_bytes,
.next_rip = ctxt->eip,
};
return ctxt->ops->intercept(ctxt, &info, stage);
}
static void assign_masked(ulong *dest, ulong src, ulong mask)
{
*dest = (*dest & ~mask) | (src & mask);
}
static void assign_register(unsigned long *reg, u64 val, int bytes)
{
/* The 4-byte case *is* correct: in 64-bit mode we zero-extend. */
switch (bytes) {
case 1:
*(u8 *)reg = (u8)val;
break;
case 2:
*(u16 *)reg = (u16)val;
break;
case 4:
*reg = (u32)val;
break; /* 64b: zero-extend */
case 8:
*reg = val;
break;
}
}
static inline unsigned long ad_mask(struct x86_emulate_ctxt *ctxt)
{
return (1UL << (ctxt->ad_bytes << 3)) - 1;
}
static ulong stack_mask(struct x86_emulate_ctxt *ctxt)
{
u16 sel;
struct desc_struct ss;
if (ctxt->mode == X86EMUL_MODE_PROT64)
return ~0UL;
ctxt->ops->get_segment(ctxt, &sel, &ss, NULL, VCPU_SREG_SS);
return ~0U >> ((ss.d ^ 1) * 16); /* d=0: 0xffff; d=1: 0xffffffff */
}
static int stack_size(struct x86_emulate_ctxt *ctxt)
{
return (__fls(stack_mask(ctxt)) + 1) >> 3;
}
/* Access/update address held in a register, based on addressing mode. */
static inline unsigned long
address_mask(struct x86_emulate_ctxt *ctxt, unsigned long reg)
{
if (ctxt->ad_bytes == sizeof(unsigned long))
return reg;
else
return reg & ad_mask(ctxt);
}
static inline unsigned long
register_address(struct x86_emulate_ctxt *ctxt, int reg)
{
return address_mask(ctxt, reg_read(ctxt, reg));
}
static void masked_increment(ulong *reg, ulong mask, int inc)
{
assign_masked(reg, *reg + inc, mask);
}
static inline void
register_address_increment(struct x86_emulate_ctxt *ctxt, int reg, int inc)
{
ulong *preg = reg_rmw(ctxt, reg);
assign_register(preg, *preg + inc, ctxt->ad_bytes);
}
static void rsp_increment(struct x86_emulate_ctxt *ctxt, int inc)
{
masked_increment(reg_rmw(ctxt, VCPU_REGS_RSP), stack_mask(ctxt), inc);
}
static u32 desc_limit_scaled(struct desc_struct *desc)
{
u32 limit = get_desc_limit(desc);
return desc->g ? (limit << 12) | 0xfff : limit;
}
static unsigned long seg_base(struct x86_emulate_ctxt *ctxt, int seg)
{
if (ctxt->mode == X86EMUL_MODE_PROT64 && seg < VCPU_SREG_FS)
return 0;
return ctxt->ops->get_cached_segment_base(ctxt, seg);
}
static int emulate_exception(struct x86_emulate_ctxt *ctxt, int vec,
u32 error, bool valid)
{
WARN_ON(vec > 0x1f);
ctxt->exception.vector = vec;
ctxt->exception.error_code = error;
ctxt->exception.error_code_valid = valid;
return X86EMUL_PROPAGATE_FAULT;
}
static int emulate_db(struct x86_emulate_ctxt *ctxt)
{
return emulate_exception(ctxt, DB_VECTOR, 0, false);
}
static int emulate_gp(struct x86_emulate_ctxt *ctxt, int err)
{
return emulate_exception(ctxt, GP_VECTOR, err, true);
}
static int emulate_ss(struct x86_emulate_ctxt *ctxt, int err)
{
return emulate_exception(ctxt, SS_VECTOR, err, true);
}
static int emulate_ud(struct x86_emulate_ctxt *ctxt)
{
return emulate_exception(ctxt, UD_VECTOR, 0, false);
}
static int emulate_ts(struct x86_emulate_ctxt *ctxt, int err)
{
return emulate_exception(ctxt, TS_VECTOR, err, true);
}
static int emulate_de(struct x86_emulate_ctxt *ctxt)
{
return emulate_exception(ctxt, DE_VECTOR, 0, false);
}
static int emulate_nm(struct x86_emulate_ctxt *ctxt)
{
return emulate_exception(ctxt, NM_VECTOR, 0, false);
}
static u16 get_segment_selector(struct x86_emulate_ctxt *ctxt, unsigned seg)
{
u16 selector;
struct desc_struct desc;
ctxt->ops->get_segment(ctxt, &selector, &desc, NULL, seg);
return selector;
}
static void set_segment_selector(struct x86_emulate_ctxt *ctxt, u16 selector,
unsigned seg)
{
u16 dummy;
u32 base3;
struct desc_struct desc;
ctxt->ops->get_segment(ctxt, &dummy, &desc, &base3, seg);
ctxt->ops->set_segment(ctxt, selector, &desc, base3, seg);
}
/*
* x86 defines three classes of vector instructions: explicitly
* aligned, explicitly unaligned, and the rest, which change behaviour
* depending on whether they're AVX encoded or not.
*
* Also included is CMPXCHG16B which is not a vector instruction, yet it is
* subject to the same check.
*/
static bool insn_aligned(struct x86_emulate_ctxt *ctxt, unsigned size)
{
if (likely(size < 16))
return false;
if (ctxt->d & Aligned)
return true;
else if (ctxt->d & Unaligned)
return false;
else if (ctxt->d & Avx)
return false;
else
return true;
}
static __always_inline int __linearize(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
unsigned *max_size, unsigned size,
bool write, bool fetch,
enum x86emul_mode mode, ulong *linear)
{
struct desc_struct desc;
bool usable;
ulong la;
u32 lim;
u16 sel;
la = seg_base(ctxt, addr.seg) + addr.ea;
*max_size = 0;
switch (mode) {
case X86EMUL_MODE_PROT64:
*linear = la;
if (is_noncanonical_address(la))
goto bad;
*max_size = min_t(u64, ~0u, (1ull << 48) - la);
if (size > *max_size)
goto bad;
break;
default:
*linear = la = (u32)la;
usable = ctxt->ops->get_segment(ctxt, &sel, &desc, NULL,
addr.seg);
if (!usable)
goto bad;
/* code segment in protected mode or read-only data segment */
if ((((ctxt->mode != X86EMUL_MODE_REAL) && (desc.type & 8))
|| !(desc.type & 2)) && write)
goto bad;
/* unreadable code segment */
if (!fetch && (desc.type & 8) && !(desc.type & 2))
goto bad;
lim = desc_limit_scaled(&desc);
if (!(desc.type & 8) && (desc.type & 4)) {
/* expand-down segment */
if (addr.ea <= lim)
goto bad;
lim = desc.d ? 0xffffffff : 0xffff;
}
if (addr.ea > lim)
goto bad;
if (lim == 0xffffffff)
*max_size = ~0u;
else {
*max_size = (u64)lim + 1 - addr.ea;
if (size > *max_size)
goto bad;
}
break;
}
if (insn_aligned(ctxt, size) && ((la & (size - 1)) != 0))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
bad:
if (addr.seg == VCPU_SREG_SS)
return emulate_ss(ctxt, 0);
else
return emulate_gp(ctxt, 0);
}
static int linearize(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
unsigned size, bool write,
ulong *linear)
{
unsigned max_size;
return __linearize(ctxt, addr, &max_size, size, write, false,
ctxt->mode, linear);
}
static inline int assign_eip(struct x86_emulate_ctxt *ctxt, ulong dst,
enum x86emul_mode mode)
{
ulong linear;
int rc;
unsigned max_size;
struct segmented_address addr = { .seg = VCPU_SREG_CS,
.ea = dst };
if (ctxt->op_bytes != sizeof(unsigned long))
addr.ea = dst & ((1UL << (ctxt->op_bytes << 3)) - 1);
rc = __linearize(ctxt, addr, &max_size, 1, false, true, mode, &linear);
if (rc == X86EMUL_CONTINUE)
ctxt->_eip = addr.ea;
return rc;
}
static inline int assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst)
{
return assign_eip(ctxt, dst, ctxt->mode);
}
static int assign_eip_far(struct x86_emulate_ctxt *ctxt, ulong dst,
const struct desc_struct *cs_desc)
{
enum x86emul_mode mode = ctxt->mode;
int rc;
#ifdef CONFIG_X86_64
if (ctxt->mode >= X86EMUL_MODE_PROT16) {
if (cs_desc->l) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
mode = X86EMUL_MODE_PROT64;
} else
mode = X86EMUL_MODE_PROT32; /* temporary value */
}
#endif
if (mode == X86EMUL_MODE_PROT16 || mode == X86EMUL_MODE_PROT32)
mode = cs_desc->d ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
rc = assign_eip(ctxt, dst, mode);
if (rc == X86EMUL_CONTINUE)
ctxt->mode = mode;
return rc;
}
static inline int jmp_rel(struct x86_emulate_ctxt *ctxt, int rel)
{
return assign_eip_near(ctxt, ctxt->_eip + rel);
}
static int segmented_read_std(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
void *data,
unsigned size)
{
int rc;
ulong linear;
rc = linearize(ctxt, addr, size, false, &linear);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->read_std(ctxt, linear, data, size, &ctxt->exception);
}
/*
* Prefetch the remaining bytes of the instruction without crossing page
* boundary if they are not in fetch_cache yet.
*/
static int __do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt, int op_size)
{
int rc;
unsigned size, max_size;
unsigned long linear;
int cur_size = ctxt->fetch.end - ctxt->fetch.data;
struct segmented_address addr = { .seg = VCPU_SREG_CS,
.ea = ctxt->eip + cur_size };
/*
* We do not know exactly how many bytes will be needed, and
* __linearize is expensive, so fetch as much as possible. We
* just have to avoid going beyond the 15 byte limit, the end
* of the segment, or the end of the page.
*
* __linearize is called with size 0 so that it does not do any
* boundary check itself. Instead, we use max_size to check
* against op_size.
*/
rc = __linearize(ctxt, addr, &max_size, 0, false, true, ctxt->mode,
&linear);
if (unlikely(rc != X86EMUL_CONTINUE))
return rc;
size = min_t(unsigned, 15UL ^ cur_size, max_size);
size = min_t(unsigned, size, PAGE_SIZE - offset_in_page(linear));
/*
* One instruction can only straddle two pages,
* and one has been loaded at the beginning of
* x86_decode_insn. So, if not enough bytes
* still, we must have hit the 15-byte boundary.
*/
if (unlikely(size < op_size))
return emulate_gp(ctxt, 0);
rc = ctxt->ops->fetch(ctxt, linear, ctxt->fetch.end,
size, &ctxt->exception);
if (unlikely(rc != X86EMUL_CONTINUE))
return rc;
ctxt->fetch.end += size;
return X86EMUL_CONTINUE;
}
static __always_inline int do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt,
unsigned size)
{
unsigned done_size = ctxt->fetch.end - ctxt->fetch.ptr;
if (unlikely(done_size < size))
return __do_insn_fetch_bytes(ctxt, size - done_size);
else
return X86EMUL_CONTINUE;
}
/* Fetch next part of the instruction being emulated. */
#define insn_fetch(_type, _ctxt) \
({ _type _x; \
\
rc = do_insn_fetch_bytes(_ctxt, sizeof(_type)); \
if (rc != X86EMUL_CONTINUE) \
goto done; \
ctxt->_eip += sizeof(_type); \
_x = *(_type __aligned(1) *) ctxt->fetch.ptr; \
ctxt->fetch.ptr += sizeof(_type); \
_x; \
})
#define insn_fetch_arr(_arr, _size, _ctxt) \
({ \
rc = do_insn_fetch_bytes(_ctxt, _size); \
if (rc != X86EMUL_CONTINUE) \
goto done; \
ctxt->_eip += (_size); \
memcpy(_arr, ctxt->fetch.ptr, _size); \
ctxt->fetch.ptr += (_size); \
})
/*
* Given the 'reg' portion of a ModRM byte, and a register block, return a
* pointer into the block that addresses the relevant register.
* @highbyte_regs specifies whether to decode AH,CH,DH,BH.
*/
static void *decode_register(struct x86_emulate_ctxt *ctxt, u8 modrm_reg,
int byteop)
{
void *p;
int highbyte_regs = (ctxt->rex_prefix == 0) && byteop;
if (highbyte_regs && modrm_reg >= 4 && modrm_reg < 8)
p = (unsigned char *)reg_rmw(ctxt, modrm_reg & 3) + 1;
else
p = reg_rmw(ctxt, modrm_reg);
return p;
}
static int read_descriptor(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
u16 *size, unsigned long *address, int op_bytes)
{
int rc;
if (op_bytes == 2)
op_bytes = 3;
*address = 0;
rc = segmented_read_std(ctxt, addr, size, 2);
if (rc != X86EMUL_CONTINUE)
return rc;
addr.ea += 2;
rc = segmented_read_std(ctxt, addr, address, op_bytes);
return rc;
}
FASTOP2(add);
FASTOP2(or);
FASTOP2(adc);
FASTOP2(sbb);
FASTOP2(and);
FASTOP2(sub);
FASTOP2(xor);
FASTOP2(cmp);
FASTOP2(test);
FASTOP1SRC2(mul, mul_ex);
FASTOP1SRC2(imul, imul_ex);
FASTOP1SRC2EX(div, div_ex);
FASTOP1SRC2EX(idiv, idiv_ex);
FASTOP3WCL(shld);
FASTOP3WCL(shrd);
FASTOP2W(imul);
FASTOP1(not);
FASTOP1(neg);
FASTOP1(inc);
FASTOP1(dec);
FASTOP2CL(rol);
FASTOP2CL(ror);
FASTOP2CL(rcl);
FASTOP2CL(rcr);
FASTOP2CL(shl);
FASTOP2CL(shr);
FASTOP2CL(sar);
FASTOP2W(bsf);
FASTOP2W(bsr);
FASTOP2W(bt);
FASTOP2W(bts);
FASTOP2W(btr);
FASTOP2W(btc);
FASTOP2(xadd);
FASTOP2R(cmp, cmp_r);
static int em_bsf_c(struct x86_emulate_ctxt *ctxt)
{
/* If src is zero, do not writeback, but update flags */
if (ctxt->src.val == 0)
ctxt->dst.type = OP_NONE;
return fastop(ctxt, em_bsf);
}
static int em_bsr_c(struct x86_emulate_ctxt *ctxt)
{
/* If src is zero, do not writeback, but update flags */
if (ctxt->src.val == 0)
ctxt->dst.type = OP_NONE;
return fastop(ctxt, em_bsr);
}
static __always_inline u8 test_cc(unsigned int condition, unsigned long flags)
{
u8 rc;
void (*fop)(void) = (void *)em_setcc + 4 * (condition & 0xf);
flags = (flags & EFLAGS_MASK) | X86_EFLAGS_IF;
asm("push %[flags]; popf; call *%[fastop]"
: "=a"(rc) : [fastop]"r"(fop), [flags]"r"(flags));
return rc;
}
static void fetch_register_operand(struct operand *op)
{
switch (op->bytes) {
case 1:
op->val = *(u8 *)op->addr.reg;
break;
case 2:
op->val = *(u16 *)op->addr.reg;
break;
case 4:
op->val = *(u32 *)op->addr.reg;
break;
case 8:
op->val = *(u64 *)op->addr.reg;
break;
}
}
static void read_sse_reg(struct x86_emulate_ctxt *ctxt, sse128_t *data, int reg)
{
ctxt->ops->get_fpu(ctxt);
switch (reg) {
case 0: asm("movdqa %%xmm0, %0" : "=m"(*data)); break;
case 1: asm("movdqa %%xmm1, %0" : "=m"(*data)); break;
case 2: asm("movdqa %%xmm2, %0" : "=m"(*data)); break;
case 3: asm("movdqa %%xmm3, %0" : "=m"(*data)); break;
case 4: asm("movdqa %%xmm4, %0" : "=m"(*data)); break;
case 5: asm("movdqa %%xmm5, %0" : "=m"(*data)); break;
case 6: asm("movdqa %%xmm6, %0" : "=m"(*data)); break;
case 7: asm("movdqa %%xmm7, %0" : "=m"(*data)); break;
#ifdef CONFIG_X86_64
case 8: asm("movdqa %%xmm8, %0" : "=m"(*data)); break;
case 9: asm("movdqa %%xmm9, %0" : "=m"(*data)); break;
case 10: asm("movdqa %%xmm10, %0" : "=m"(*data)); break;
case 11: asm("movdqa %%xmm11, %0" : "=m"(*data)); break;
case 12: asm("movdqa %%xmm12, %0" : "=m"(*data)); break;
case 13: asm("movdqa %%xmm13, %0" : "=m"(*data)); break;
case 14: asm("movdqa %%xmm14, %0" : "=m"(*data)); break;
case 15: asm("movdqa %%xmm15, %0" : "=m"(*data)); break;
#endif
default: BUG();
}
ctxt->ops->put_fpu(ctxt);
}
static void write_sse_reg(struct x86_emulate_ctxt *ctxt, sse128_t *data,
int reg)
{
ctxt->ops->get_fpu(ctxt);
switch (reg) {
case 0: asm("movdqa %0, %%xmm0" : : "m"(*data)); break;
case 1: asm("movdqa %0, %%xmm1" : : "m"(*data)); break;
case 2: asm("movdqa %0, %%xmm2" : : "m"(*data)); break;
case 3: asm("movdqa %0, %%xmm3" : : "m"(*data)); break;
case 4: asm("movdqa %0, %%xmm4" : : "m"(*data)); break;
case 5: asm("movdqa %0, %%xmm5" : : "m"(*data)); break;
case 6: asm("movdqa %0, %%xmm6" : : "m"(*data)); break;
case 7: asm("movdqa %0, %%xmm7" : : "m"(*data)); break;
#ifdef CONFIG_X86_64
case 8: asm("movdqa %0, %%xmm8" : : "m"(*data)); break;
case 9: asm("movdqa %0, %%xmm9" : : "m"(*data)); break;
case 10: asm("movdqa %0, %%xmm10" : : "m"(*data)); break;
case 11: asm("movdqa %0, %%xmm11" : : "m"(*data)); break;
case 12: asm("movdqa %0, %%xmm12" : : "m"(*data)); break;
case 13: asm("movdqa %0, %%xmm13" : : "m"(*data)); break;
case 14: asm("movdqa %0, %%xmm14" : : "m"(*data)); break;
case 15: asm("movdqa %0, %%xmm15" : : "m"(*data)); break;
#endif
default: BUG();
}
ctxt->ops->put_fpu(ctxt);
}
static void read_mmx_reg(struct x86_emulate_ctxt *ctxt, u64 *data, int reg)
{
ctxt->ops->get_fpu(ctxt);
switch (reg) {
case 0: asm("movq %%mm0, %0" : "=m"(*data)); break;
case 1: asm("movq %%mm1, %0" : "=m"(*data)); break;
case 2: asm("movq %%mm2, %0" : "=m"(*data)); break;
case 3: asm("movq %%mm3, %0" : "=m"(*data)); break;
case 4: asm("movq %%mm4, %0" : "=m"(*data)); break;
case 5: asm("movq %%mm5, %0" : "=m"(*data)); break;
case 6: asm("movq %%mm6, %0" : "=m"(*data)); break;
case 7: asm("movq %%mm7, %0" : "=m"(*data)); break;
default: BUG();
}
ctxt->ops->put_fpu(ctxt);
}
static void write_mmx_reg(struct x86_emulate_ctxt *ctxt, u64 *data, int reg)
{
ctxt->ops->get_fpu(ctxt);
switch (reg) {
case 0: asm("movq %0, %%mm0" : : "m"(*data)); break;
case 1: asm("movq %0, %%mm1" : : "m"(*data)); break;
case 2: asm("movq %0, %%mm2" : : "m"(*data)); break;
case 3: asm("movq %0, %%mm3" : : "m"(*data)); break;
case 4: asm("movq %0, %%mm4" : : "m"(*data)); break;
case 5: asm("movq %0, %%mm5" : : "m"(*data)); break;
case 6: asm("movq %0, %%mm6" : : "m"(*data)); break;
case 7: asm("movq %0, %%mm7" : : "m"(*data)); break;
default: BUG();
}
ctxt->ops->put_fpu(ctxt);
}
static int em_fninit(struct x86_emulate_ctxt *ctxt)
{
if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
return emulate_nm(ctxt);
ctxt->ops->get_fpu(ctxt);
asm volatile("fninit");
ctxt->ops->put_fpu(ctxt);
return X86EMUL_CONTINUE;
}
static int em_fnstcw(struct x86_emulate_ctxt *ctxt)
{
u16 fcw;
if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
return emulate_nm(ctxt);
ctxt->ops->get_fpu(ctxt);
asm volatile("fnstcw %0": "+m"(fcw));
ctxt->ops->put_fpu(ctxt);
ctxt->dst.val = fcw;
return X86EMUL_CONTINUE;
}
static int em_fnstsw(struct x86_emulate_ctxt *ctxt)
{
u16 fsw;
if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
return emulate_nm(ctxt);
ctxt->ops->get_fpu(ctxt);
asm volatile("fnstsw %0": "+m"(fsw));
ctxt->ops->put_fpu(ctxt);
ctxt->dst.val = fsw;
return X86EMUL_CONTINUE;
}
static void decode_register_operand(struct x86_emulate_ctxt *ctxt,
struct operand *op)
{
unsigned reg = ctxt->modrm_reg;
if (!(ctxt->d & ModRM))
reg = (ctxt->b & 7) | ((ctxt->rex_prefix & 1) << 3);
if (ctxt->d & Sse) {
op->type = OP_XMM;
op->bytes = 16;
op->addr.xmm = reg;
read_sse_reg(ctxt, &op->vec_val, reg);
return;
}
if (ctxt->d & Mmx) {
reg &= 7;
op->type = OP_MM;
op->bytes = 8;
op->addr.mm = reg;
return;
}
op->type = OP_REG;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.reg = decode_register(ctxt, reg, ctxt->d & ByteOp);
fetch_register_operand(op);
op->orig_val = op->val;
}
static void adjust_modrm_seg(struct x86_emulate_ctxt *ctxt, int base_reg)
{
if (base_reg == VCPU_REGS_RSP || base_reg == VCPU_REGS_RBP)
ctxt->modrm_seg = VCPU_SREG_SS;
}
static int decode_modrm(struct x86_emulate_ctxt *ctxt,
struct operand *op)
{
u8 sib;
int index_reg, base_reg, scale;
int rc = X86EMUL_CONTINUE;
ulong modrm_ea = 0;
ctxt->modrm_reg = ((ctxt->rex_prefix << 1) & 8); /* REX.R */
index_reg = (ctxt->rex_prefix << 2) & 8; /* REX.X */
base_reg = (ctxt->rex_prefix << 3) & 8; /* REX.B */
ctxt->modrm_mod = (ctxt->modrm & 0xc0) >> 6;
ctxt->modrm_reg |= (ctxt->modrm & 0x38) >> 3;
ctxt->modrm_rm = base_reg | (ctxt->modrm & 0x07);
ctxt->modrm_seg = VCPU_SREG_DS;
if (ctxt->modrm_mod == 3 || (ctxt->d & NoMod)) {
op->type = OP_REG;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.reg = decode_register(ctxt, ctxt->modrm_rm,
ctxt->d & ByteOp);
if (ctxt->d & Sse) {
op->type = OP_XMM;
op->bytes = 16;
op->addr.xmm = ctxt->modrm_rm;
read_sse_reg(ctxt, &op->vec_val, ctxt->modrm_rm);
return rc;
}
if (ctxt->d & Mmx) {
op->type = OP_MM;
op->bytes = 8;
op->addr.mm = ctxt->modrm_rm & 7;
return rc;
}
fetch_register_operand(op);
return rc;
}
op->type = OP_MEM;
if (ctxt->ad_bytes == 2) {
unsigned bx = reg_read(ctxt, VCPU_REGS_RBX);
unsigned bp = reg_read(ctxt, VCPU_REGS_RBP);
unsigned si = reg_read(ctxt, VCPU_REGS_RSI);
unsigned di = reg_read(ctxt, VCPU_REGS_RDI);
/* 16-bit ModR/M decode. */
switch (ctxt->modrm_mod) {
case 0:
if (ctxt->modrm_rm == 6)
modrm_ea += insn_fetch(u16, ctxt);
break;
case 1:
modrm_ea += insn_fetch(s8, ctxt);
break;
case 2:
modrm_ea += insn_fetch(u16, ctxt);
break;
}
switch (ctxt->modrm_rm) {
case 0:
modrm_ea += bx + si;
break;
case 1:
modrm_ea += bx + di;
break;
case 2:
modrm_ea += bp + si;
break;
case 3:
modrm_ea += bp + di;
break;
case 4:
modrm_ea += si;
break;
case 5:
modrm_ea += di;
break;
case 6:
if (ctxt->modrm_mod != 0)
modrm_ea += bp;
break;
case 7:
modrm_ea += bx;
break;
}
if (ctxt->modrm_rm == 2 || ctxt->modrm_rm == 3 ||
(ctxt->modrm_rm == 6 && ctxt->modrm_mod != 0))
ctxt->modrm_seg = VCPU_SREG_SS;
modrm_ea = (u16)modrm_ea;
} else {
/* 32/64-bit ModR/M decode. */
if ((ctxt->modrm_rm & 7) == 4) {
sib = insn_fetch(u8, ctxt);
index_reg |= (sib >> 3) & 7;
base_reg |= sib & 7;
scale = sib >> 6;
if ((base_reg & 7) == 5 && ctxt->modrm_mod == 0)
modrm_ea += insn_fetch(s32, ctxt);
else {
modrm_ea += reg_read(ctxt, base_reg);
adjust_modrm_seg(ctxt, base_reg);
/* Increment ESP on POP [ESP] */
if ((ctxt->d & IncSP) &&
base_reg == VCPU_REGS_RSP)
modrm_ea += ctxt->op_bytes;
}
if (index_reg != 4)
modrm_ea += reg_read(ctxt, index_reg) << scale;
} else if ((ctxt->modrm_rm & 7) == 5 && ctxt->modrm_mod == 0) {
modrm_ea += insn_fetch(s32, ctxt);
if (ctxt->mode == X86EMUL_MODE_PROT64)
ctxt->rip_relative = 1;
} else {
base_reg = ctxt->modrm_rm;
modrm_ea += reg_read(ctxt, base_reg);
adjust_modrm_seg(ctxt, base_reg);
}
switch (ctxt->modrm_mod) {
case 1:
modrm_ea += insn_fetch(s8, ctxt);
break;
case 2:
modrm_ea += insn_fetch(s32, ctxt);
break;
}
}
op->addr.mem.ea = modrm_ea;
if (ctxt->ad_bytes != 8)
ctxt->memop.addr.mem.ea = (u32)ctxt->memop.addr.mem.ea;
done:
return rc;
}
static int decode_abs(struct x86_emulate_ctxt *ctxt,
struct operand *op)
{
int rc = X86EMUL_CONTINUE;
op->type = OP_MEM;
switch (ctxt->ad_bytes) {
case 2:
op->addr.mem.ea = insn_fetch(u16, ctxt);
break;
case 4:
op->addr.mem.ea = insn_fetch(u32, ctxt);
break;
case 8:
op->addr.mem.ea = insn_fetch(u64, ctxt);
break;
}
done:
return rc;
}
static void fetch_bit_operand(struct x86_emulate_ctxt *ctxt)
{
long sv = 0, mask;
if (ctxt->dst.type == OP_MEM && ctxt->src.type == OP_REG) {
mask = ~((long)ctxt->dst.bytes * 8 - 1);
if (ctxt->src.bytes == 2)
sv = (s16)ctxt->src.val & (s16)mask;
else if (ctxt->src.bytes == 4)
sv = (s32)ctxt->src.val & (s32)mask;
else
sv = (s64)ctxt->src.val & (s64)mask;
ctxt->dst.addr.mem.ea = address_mask(ctxt,
ctxt->dst.addr.mem.ea + (sv >> 3));
}
/* only subword offset */
ctxt->src.val &= (ctxt->dst.bytes << 3) - 1;
}
static int read_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr, void *dest, unsigned size)
{
int rc;
struct read_cache *mc = &ctxt->mem_read;
if (mc->pos < mc->end)
goto read_cached;
WARN_ON((mc->end + size) >= sizeof(mc->data));
rc = ctxt->ops->read_emulated(ctxt, addr, mc->data + mc->end, size,
&ctxt->exception);
if (rc != X86EMUL_CONTINUE)
return rc;
mc->end += size;
read_cached:
memcpy(dest, mc->data + mc->pos, size);
mc->pos += size;
return X86EMUL_CONTINUE;
}
static int segmented_read(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
void *data,
unsigned size)
{
int rc;
ulong linear;
rc = linearize(ctxt, addr, size, false, &linear);
if (rc != X86EMUL_CONTINUE)
return rc;
return read_emulated(ctxt, linear, data, size);
}
static int segmented_write(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
const void *data,
unsigned size)
{
int rc;
ulong linear;
rc = linearize(ctxt, addr, size, true, &linear);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->write_emulated(ctxt, linear, data, size,
&ctxt->exception);
}
static int segmented_cmpxchg(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
const void *orig_data, const void *data,
unsigned size)
{
int rc;
ulong linear;
rc = linearize(ctxt, addr, size, true, &linear);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->cmpxchg_emulated(ctxt, linear, orig_data, data,
size, &ctxt->exception);
}
static int pio_in_emulated(struct x86_emulate_ctxt *ctxt,
unsigned int size, unsigned short port,
void *dest)
{
struct read_cache *rc = &ctxt->io_read;
if (rc->pos == rc->end) { /* refill pio read ahead */
unsigned int in_page, n;
unsigned int count = ctxt->rep_prefix ?
address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) : 1;
in_page = (ctxt->eflags & X86_EFLAGS_DF) ?
offset_in_page(reg_read(ctxt, VCPU_REGS_RDI)) :
PAGE_SIZE - offset_in_page(reg_read(ctxt, VCPU_REGS_RDI));
n = min3(in_page, (unsigned int)sizeof(rc->data) / size, count);
if (n == 0)
n = 1;
rc->pos = rc->end = 0;
if (!ctxt->ops->pio_in_emulated(ctxt, size, port, rc->data, n))
return 0;
rc->end = n * size;
}
if (ctxt->rep_prefix && (ctxt->d & String) &&
!(ctxt->eflags & X86_EFLAGS_DF)) {
ctxt->dst.data = rc->data + rc->pos;
ctxt->dst.type = OP_MEM_STR;
ctxt->dst.count = (rc->end - rc->pos) / size;
rc->pos = rc->end;
} else {
memcpy(dest, rc->data + rc->pos, size);
rc->pos += size;
}
return 1;
}
static int read_interrupt_descriptor(struct x86_emulate_ctxt *ctxt,
u16 index, struct desc_struct *desc)
{
struct desc_ptr dt;
ulong addr;
ctxt->ops->get_idt(ctxt, &dt);
if (dt.size < index * 8 + 7)
return emulate_gp(ctxt, index << 3 | 0x2);
addr = dt.address + index * 8;
return ctxt->ops->read_std(ctxt, addr, desc, sizeof *desc,
&ctxt->exception);
}
static void get_descriptor_table_ptr(struct x86_emulate_ctxt *ctxt,
u16 selector, struct desc_ptr *dt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
u32 base3 = 0;
if (selector & 1 << 2) {
struct desc_struct desc;
u16 sel;
memset (dt, 0, sizeof *dt);
if (!ops->get_segment(ctxt, &sel, &desc, &base3,
VCPU_SREG_LDTR))
return;
dt->size = desc_limit_scaled(&desc); /* what if limit > 65535? */
dt->address = get_desc_base(&desc) | ((u64)base3 << 32);
} else
ops->get_gdt(ctxt, dt);
}
static int get_descriptor_ptr(struct x86_emulate_ctxt *ctxt,
u16 selector, ulong *desc_addr_p)
{
struct desc_ptr dt;
u16 index = selector >> 3;
ulong addr;
get_descriptor_table_ptr(ctxt, selector, &dt);
if (dt.size < index * 8 + 7)
return emulate_gp(ctxt, selector & 0xfffc);
addr = dt.address + index * 8;
#ifdef CONFIG_X86_64
if (addr >> 32 != 0) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (!(efer & EFER_LMA))
addr &= (u32)-1;
}
#endif
*desc_addr_p = addr;
return X86EMUL_CONTINUE;
}
/* allowed just for 8 bytes segments */
static int read_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, struct desc_struct *desc,
ulong *desc_addr_p)
{
int rc;
rc = get_descriptor_ptr(ctxt, selector, desc_addr_p);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->read_std(ctxt, *desc_addr_p, desc, sizeof(*desc),
&ctxt->exception);
}
/* allowed just for 8 bytes segments */
static int write_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, struct desc_struct *desc)
{
int rc;
ulong addr;
rc = get_descriptor_ptr(ctxt, selector, &addr);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->write_std(ctxt, addr, desc, sizeof *desc,
&ctxt->exception);
}
/* Does not support long mode */
static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg, u8 cpl,
enum x86_transfer_type transfer,
struct desc_struct *desc)
{
struct desc_struct seg_desc, old_desc;
u8 dpl, rpl;
unsigned err_vec = GP_VECTOR;
u32 err_code = 0;
bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
ulong desc_addr;
int ret;
u16 dummy;
u32 base3 = 0;
memset(&seg_desc, 0, sizeof seg_desc);
if (ctxt->mode == X86EMUL_MODE_REAL) {
/* set real mode segment descriptor (keep limit etc. for
* unreal mode) */
ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);
set_desc_base(&seg_desc, selector << 4);
goto load;
} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {
/* VM86 needs a clean new segment descriptor */
set_desc_base(&seg_desc, selector << 4);
set_desc_limit(&seg_desc, 0xffff);
seg_desc.type = 3;
seg_desc.p = 1;
seg_desc.s = 1;
seg_desc.dpl = 3;
goto load;
}
rpl = selector & 3;
/* NULL selector is not valid for TR, CS and SS (except for long mode) */
if ((seg == VCPU_SREG_CS
|| (seg == VCPU_SREG_SS
&& (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl))
|| seg == VCPU_SREG_TR)
&& null_selector)
goto exception;
/* TR should be in GDT only */
if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
goto exception;
if (null_selector) /* for NULL selector skip all following checks */
goto load;
ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
err_code = selector & 0xfffc;
err_vec = (transfer == X86_TRANSFER_TASK_SWITCH) ? TS_VECTOR :
GP_VECTOR;
/* can't load system descriptor into segment selector */
if (seg <= VCPU_SREG_GS && !seg_desc.s) {
if (transfer == X86_TRANSFER_CALL_JMP)
return X86EMUL_UNHANDLEABLE;
goto exception;
}
if (!seg_desc.p) {
err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
goto exception;
}
dpl = seg_desc.dpl;
switch (seg) {
case VCPU_SREG_SS:
/*
* segment is not a writable data segment or segment
* selector's RPL != CPL or segment selector's RPL != CPL
*/
if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
goto exception;
break;
case VCPU_SREG_CS:
if (!(seg_desc.type & 8))
goto exception;
if (seg_desc.type & 4) {
/* conforming */
if (dpl > cpl)
goto exception;
} else {
/* nonconforming */
if (rpl > cpl || dpl != cpl)
goto exception;
}
/* in long-mode d/b must be clear if l is set */
if (seg_desc.d && seg_desc.l) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
goto exception;
}
/* CS(RPL) <- CPL */
selector = (selector & 0xfffc) | cpl;
break;
case VCPU_SREG_TR:
if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
goto exception;
old_desc = seg_desc;
seg_desc.type |= 2; /* busy */
ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,
sizeof(seg_desc), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
break;
case VCPU_SREG_LDTR:
if (seg_desc.s || seg_desc.type != 2)
goto exception;
break;
default: /* DS, ES, FS, or GS */
/*
* segment is not a data or readable code segment or
* ((segment is a data or nonconforming code segment)
* and (both RPL and CPL > DPL))
*/
if ((seg_desc.type & 0xa) == 0x8 ||
(((seg_desc.type & 0xc) != 0xc) &&
(rpl > dpl && cpl > dpl)))
goto exception;
break;
}
if (seg_desc.s) {
/* mark segment as accessed */
if (!(seg_desc.type & 1)) {
seg_desc.type |= 1;
ret = write_segment_descriptor(ctxt, selector,
&seg_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
}
} else if (ctxt->mode == X86EMUL_MODE_PROT64) {
ret = ctxt->ops->read_std(ctxt, desc_addr+8, &base3,
sizeof(base3), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
if (is_noncanonical_address(get_desc_base(&seg_desc) |
((u64)base3 << 32)))
return emulate_gp(ctxt, 0);
}
load:
ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);
if (desc)
*desc = seg_desc;
return X86EMUL_CONTINUE;
exception:
return emulate_exception(ctxt, err_vec, err_code, true);
}
static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg)
{
u8 cpl = ctxt->ops->cpl(ctxt);
return __load_segment_descriptor(ctxt, selector, seg, cpl,
X86_TRANSFER_NONE, NULL);
}
static void write_register_operand(struct operand *op)
{
return assign_register(op->addr.reg, op->val, op->bytes);
}
static int writeback(struct x86_emulate_ctxt *ctxt, struct operand *op)
{
switch (op->type) {
case OP_REG:
write_register_operand(op);
break;
case OP_MEM:
if (ctxt->lock_prefix)
return segmented_cmpxchg(ctxt,
op->addr.mem,
&op->orig_val,
&op->val,
op->bytes);
else
return segmented_write(ctxt,
op->addr.mem,
&op->val,
op->bytes);
break;
case OP_MEM_STR:
return segmented_write(ctxt,
op->addr.mem,
op->data,
op->bytes * op->count);
break;
case OP_XMM:
write_sse_reg(ctxt, &op->vec_val, op->addr.xmm);
break;
case OP_MM:
write_mmx_reg(ctxt, &op->mm_val, op->addr.mm);
break;
case OP_NONE:
/* no writeback */
break;
default:
break;
}
return X86EMUL_CONTINUE;
}
static int push(struct x86_emulate_ctxt *ctxt, void *data, int bytes)
{
struct segmented_address addr;
rsp_increment(ctxt, -bytes);
addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt);
addr.seg = VCPU_SREG_SS;
return segmented_write(ctxt, addr, data, bytes);
}
static int em_push(struct x86_emulate_ctxt *ctxt)
{
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return push(ctxt, &ctxt->src.val, ctxt->op_bytes);
}
static int emulate_pop(struct x86_emulate_ctxt *ctxt,
void *dest, int len)
{
int rc;
struct segmented_address addr;
addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt);
addr.seg = VCPU_SREG_SS;
rc = segmented_read(ctxt, addr, dest, len);
if (rc != X86EMUL_CONTINUE)
return rc;
rsp_increment(ctxt, len);
return rc;
}
static int em_pop(struct x86_emulate_ctxt *ctxt)
{
return emulate_pop(ctxt, &ctxt->dst.val, ctxt->op_bytes);
}
static int emulate_popf(struct x86_emulate_ctxt *ctxt,
void *dest, int len)
{
int rc;
unsigned long val, change_mask;
int iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> X86_EFLAGS_IOPL_BIT;
int cpl = ctxt->ops->cpl(ctxt);
rc = emulate_pop(ctxt, &val, len);
if (rc != X86EMUL_CONTINUE)
return rc;
change_mask = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF |
X86_EFLAGS_TF | X86_EFLAGS_DF | X86_EFLAGS_NT |
X86_EFLAGS_AC | X86_EFLAGS_ID;
switch(ctxt->mode) {
case X86EMUL_MODE_PROT64:
case X86EMUL_MODE_PROT32:
case X86EMUL_MODE_PROT16:
if (cpl == 0)
change_mask |= X86_EFLAGS_IOPL;
if (cpl <= iopl)
change_mask |= X86_EFLAGS_IF;
break;
case X86EMUL_MODE_VM86:
if (iopl < 3)
return emulate_gp(ctxt, 0);
change_mask |= X86_EFLAGS_IF;
break;
default: /* real mode */
change_mask |= (X86_EFLAGS_IOPL | X86_EFLAGS_IF);
break;
}
*(unsigned long *)dest =
(ctxt->eflags & ~change_mask) | (val & change_mask);
return rc;
}
static int em_popf(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.type = OP_REG;
ctxt->dst.addr.reg = &ctxt->eflags;
ctxt->dst.bytes = ctxt->op_bytes;
return emulate_popf(ctxt, &ctxt->dst.val, ctxt->op_bytes);
}
static int em_enter(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned frame_size = ctxt->src.val;
unsigned nesting_level = ctxt->src2.val & 31;
ulong rbp;
if (nesting_level)
return X86EMUL_UNHANDLEABLE;
rbp = reg_read(ctxt, VCPU_REGS_RBP);
rc = push(ctxt, &rbp, stack_size(ctxt));
if (rc != X86EMUL_CONTINUE)
return rc;
assign_masked(reg_rmw(ctxt, VCPU_REGS_RBP), reg_read(ctxt, VCPU_REGS_RSP),
stack_mask(ctxt));
assign_masked(reg_rmw(ctxt, VCPU_REGS_RSP),
reg_read(ctxt, VCPU_REGS_RSP) - frame_size,
stack_mask(ctxt));
return X86EMUL_CONTINUE;
}
static int em_leave(struct x86_emulate_ctxt *ctxt)
{
assign_masked(reg_rmw(ctxt, VCPU_REGS_RSP), reg_read(ctxt, VCPU_REGS_RBP),
stack_mask(ctxt));
return emulate_pop(ctxt, reg_rmw(ctxt, VCPU_REGS_RBP), ctxt->op_bytes);
}
static int em_push_sreg(struct x86_emulate_ctxt *ctxt)
{
int seg = ctxt->src2.val;
ctxt->src.val = get_segment_selector(ctxt, seg);
if (ctxt->op_bytes == 4) {
rsp_increment(ctxt, -2);
ctxt->op_bytes = 2;
}
return em_push(ctxt);
}
static int em_pop_sreg(struct x86_emulate_ctxt *ctxt)
{
int seg = ctxt->src2.val;
unsigned long selector;
int rc;
rc = emulate_pop(ctxt, &selector, 2);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->modrm_reg == VCPU_SREG_SS)
ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS;
if (ctxt->op_bytes > 2)
rsp_increment(ctxt, ctxt->op_bytes - 2);
rc = load_segment_descriptor(ctxt, (u16)selector, seg);
return rc;
}
static int em_pusha(struct x86_emulate_ctxt *ctxt)
{
unsigned long old_esp = reg_read(ctxt, VCPU_REGS_RSP);
int rc = X86EMUL_CONTINUE;
int reg = VCPU_REGS_RAX;
while (reg <= VCPU_REGS_RDI) {
(reg == VCPU_REGS_RSP) ?
(ctxt->src.val = old_esp) : (ctxt->src.val = reg_read(ctxt, reg));
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
++reg;
}
return rc;
}
static int em_pushf(struct x86_emulate_ctxt *ctxt)
{
ctxt->src.val = (unsigned long)ctxt->eflags & ~X86_EFLAGS_VM;
return em_push(ctxt);
}
static int em_popa(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
int reg = VCPU_REGS_RDI;
u32 val;
while (reg >= VCPU_REGS_RAX) {
if (reg == VCPU_REGS_RSP) {
rsp_increment(ctxt, ctxt->op_bytes);
--reg;
}
rc = emulate_pop(ctxt, &val, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
break;
assign_register(reg_rmw(ctxt, reg), val, ctxt->op_bytes);
--reg;
}
return rc;
}
static int __emulate_int_real(struct x86_emulate_ctxt *ctxt, int irq)
{
const struct x86_emulate_ops *ops = ctxt->ops;
int rc;
struct desc_ptr dt;
gva_t cs_addr;
gva_t eip_addr;
u16 cs, eip;
/* TODO: Add limit checks */
ctxt->src.val = ctxt->eflags;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->eflags &= ~(X86_EFLAGS_IF | X86_EFLAGS_TF | X86_EFLAGS_AC);
ctxt->src.val = get_segment_selector(ctxt, VCPU_SREG_CS);
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->src.val = ctxt->_eip;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ops->get_idt(ctxt, &dt);
eip_addr = dt.address + (irq << 2);
cs_addr = dt.address + (irq << 2) + 2;
rc = ops->read_std(ctxt, cs_addr, &cs, 2, &ctxt->exception);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = ops->read_std(ctxt, eip_addr, &eip, 2, &ctxt->exception);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = load_segment_descriptor(ctxt, cs, VCPU_SREG_CS);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->_eip = eip;
return rc;
}
int emulate_int_real(struct x86_emulate_ctxt *ctxt, int irq)
{
int rc;
invalidate_registers(ctxt);
rc = __emulate_int_real(ctxt, irq);
if (rc == X86EMUL_CONTINUE)
writeback_registers(ctxt);
return rc;
}
static int emulate_int(struct x86_emulate_ctxt *ctxt, int irq)
{
switch(ctxt->mode) {
case X86EMUL_MODE_REAL:
return __emulate_int_real(ctxt, irq);
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
case X86EMUL_MODE_PROT32:
case X86EMUL_MODE_PROT64:
default:
/* Protected mode interrupts unimplemented yet */
return X86EMUL_UNHANDLEABLE;
}
}
static int emulate_iret_real(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
unsigned long temp_eip = 0;
unsigned long temp_eflags = 0;
unsigned long cs = 0;
unsigned long mask = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_TF |
X86_EFLAGS_IF | X86_EFLAGS_DF | X86_EFLAGS_OF |
X86_EFLAGS_IOPL | X86_EFLAGS_NT | X86_EFLAGS_RF |
X86_EFLAGS_AC | X86_EFLAGS_ID |
X86_EFLAGS_FIXED;
unsigned long vm86_mask = X86_EFLAGS_VM | X86_EFLAGS_VIF |
X86_EFLAGS_VIP;
/* TODO: Add stack limit check */
rc = emulate_pop(ctxt, &temp_eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
if (temp_eip & ~0xffff)
return emulate_gp(ctxt, 0);
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &temp_eflags, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->_eip = temp_eip;
if (ctxt->op_bytes == 4)
ctxt->eflags = ((temp_eflags & mask) | (ctxt->eflags & vm86_mask));
else if (ctxt->op_bytes == 2) {
ctxt->eflags &= ~0xffff;
ctxt->eflags |= temp_eflags;
}
ctxt->eflags &= ~EFLG_RESERVED_ZEROS_MASK; /* Clear reserved zeros */
ctxt->eflags |= X86_EFLAGS_FIXED;
ctxt->ops->set_nmi_mask(ctxt, false);
return rc;
}
static int em_iret(struct x86_emulate_ctxt *ctxt)
{
switch(ctxt->mode) {
case X86EMUL_MODE_REAL:
return emulate_iret_real(ctxt);
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
case X86EMUL_MODE_PROT32:
case X86EMUL_MODE_PROT64:
default:
/* iret from protected mode unimplemented yet */
return X86EMUL_UNHANDLEABLE;
}
}
static int em_jmp_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned short sel, old_sel;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
u8 cpl = ctxt->ops->cpl(ctxt);
/* Assignment of RIP may only fail in 64-bit mode */
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_sel, &old_desc, NULL,
VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,
X86_TRANSFER_CALL_JMP,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, ctxt->src.val, &new_desc);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);
/* assigning eip failed; restore the old cs */
ops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS);
return rc;
}
return rc;
}
static int em_jmp_abs(struct x86_emulate_ctxt *ctxt)
{
return assign_eip_near(ctxt, ctxt->src.val);
}
static int em_call_near_abs(struct x86_emulate_ctxt *ctxt)
{
int rc;
long int old_eip;
old_eip = ctxt->_eip;
rc = assign_eip_near(ctxt, ctxt->src.val);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->src.val = old_eip;
rc = em_push(ctxt);
return rc;
}
static int em_cmpxchg8b(struct x86_emulate_ctxt *ctxt)
{
u64 old = ctxt->dst.orig_val64;
if (ctxt->dst.bytes == 16)
return X86EMUL_UNHANDLEABLE;
if (((u32) (old >> 0) != (u32) reg_read(ctxt, VCPU_REGS_RAX)) ||
((u32) (old >> 32) != (u32) reg_read(ctxt, VCPU_REGS_RDX))) {
*reg_write(ctxt, VCPU_REGS_RAX) = (u32) (old >> 0);
*reg_write(ctxt, VCPU_REGS_RDX) = (u32) (old >> 32);
ctxt->eflags &= ~X86_EFLAGS_ZF;
} else {
ctxt->dst.val64 = ((u64)reg_read(ctxt, VCPU_REGS_RCX) << 32) |
(u32) reg_read(ctxt, VCPU_REGS_RBX);
ctxt->eflags |= X86_EFLAGS_ZF;
}
return X86EMUL_CONTINUE;
}
static int em_ret(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip;
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
return assign_eip_near(ctxt, eip);
}
static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip, cs;
u16 old_cs;
int cpl = ctxt->ops->cpl(ctxt);
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_cs, &old_desc, NULL,
VCPU_SREG_CS);
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, cpl,
X86_TRANSFER_RET,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, eip, &new_desc);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
}
return rc;
}
static int em_ret_far_imm(struct x86_emulate_ctxt *ctxt)
{
int rc;
rc = em_ret_far(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
rsp_increment(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
static int em_cmpxchg(struct x86_emulate_ctxt *ctxt)
{
/* Save real source value, then compare EAX against destination. */
ctxt->dst.orig_val = ctxt->dst.val;
ctxt->dst.val = reg_read(ctxt, VCPU_REGS_RAX);
ctxt->src.orig_val = ctxt->src.val;
ctxt->src.val = ctxt->dst.orig_val;
fastop(ctxt, em_cmp);
if (ctxt->eflags & X86_EFLAGS_ZF) {
/* Success: write back to memory; no update of EAX */
ctxt->src.type = OP_NONE;
ctxt->dst.val = ctxt->src.orig_val;
} else {
/* Failure: write the value we saw to EAX. */
ctxt->src.type = OP_REG;
ctxt->src.addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
ctxt->src.val = ctxt->dst.orig_val;
/* Create write-cycle to dest by writing the same value */
ctxt->dst.val = ctxt->dst.orig_val;
}
return X86EMUL_CONTINUE;
}
static int em_lseg(struct x86_emulate_ctxt *ctxt)
{
int seg = ctxt->src2.val;
unsigned short sel;
int rc;
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = load_segment_descriptor(ctxt, sel, seg);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->dst.val = ctxt->src.val;
return rc;
}
static int emulator_has_longmode(struct x86_emulate_ctxt *ctxt)
{
u32 eax, ebx, ecx, edx;
eax = 0x80000001;
ecx = 0;
ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
return edx & bit(X86_FEATURE_LM);
}
#define GET_SMSTATE(type, smbase, offset) \
({ \
type __val; \
int r = ctxt->ops->read_phys(ctxt, smbase + offset, &__val, \
sizeof(__val)); \
if (r != X86EMUL_CONTINUE) \
return X86EMUL_UNHANDLEABLE; \
__val; \
})
static void rsm_set_desc_flags(struct desc_struct *desc, u32 flags)
{
desc->g = (flags >> 23) & 1;
desc->d = (flags >> 22) & 1;
desc->l = (flags >> 21) & 1;
desc->avl = (flags >> 20) & 1;
desc->p = (flags >> 15) & 1;
desc->dpl = (flags >> 13) & 3;
desc->s = (flags >> 12) & 1;
desc->type = (flags >> 8) & 15;
}
static int rsm_load_seg_32(struct x86_emulate_ctxt *ctxt, u64 smbase, int n)
{
struct desc_struct desc;
int offset;
u16 selector;
selector = GET_SMSTATE(u32, smbase, 0x7fa8 + n * 4);
if (n < 3)
offset = 0x7f84 + n * 12;
else
offset = 0x7f2c + (n - 3) * 12;
set_desc_base(&desc, GET_SMSTATE(u32, smbase, offset + 8));
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, offset + 4));
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, offset));
ctxt->ops->set_segment(ctxt, selector, &desc, 0, n);
return X86EMUL_CONTINUE;
}
static int rsm_load_seg_64(struct x86_emulate_ctxt *ctxt, u64 smbase, int n)
{
struct desc_struct desc;
int offset;
u16 selector;
u32 base3;
offset = 0x7e00 + n * 16;
selector = GET_SMSTATE(u16, smbase, offset);
rsm_set_desc_flags(&desc, GET_SMSTATE(u16, smbase, offset + 2) << 8);
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, offset + 4));
set_desc_base(&desc, GET_SMSTATE(u32, smbase, offset + 8));
base3 = GET_SMSTATE(u32, smbase, offset + 12);
ctxt->ops->set_segment(ctxt, selector, &desc, base3, n);
return X86EMUL_CONTINUE;
}
static int rsm_enter_protected_mode(struct x86_emulate_ctxt *ctxt,
u64 cr0, u64 cr4)
{
int bad;
/*
* First enable PAE, long mode needs it before CR0.PG = 1 is set.
* Then enable protected mode. However, PCID cannot be enabled
* if EFER.LMA=0, so set it separately.
*/
bad = ctxt->ops->set_cr(ctxt, 4, cr4 & ~X86_CR4_PCIDE);
if (bad)
return X86EMUL_UNHANDLEABLE;
bad = ctxt->ops->set_cr(ctxt, 0, cr0);
if (bad)
return X86EMUL_UNHANDLEABLE;
if (cr4 & X86_CR4_PCIDE) {
bad = ctxt->ops->set_cr(ctxt, 4, cr4);
if (bad)
return X86EMUL_UNHANDLEABLE;
}
return X86EMUL_CONTINUE;
}
static int rsm_load_state_32(struct x86_emulate_ctxt *ctxt, u64 smbase)
{
struct desc_struct desc;
struct desc_ptr dt;
u16 selector;
u32 val, cr0, cr4;
int i;
cr0 = GET_SMSTATE(u32, smbase, 0x7ffc);
ctxt->ops->set_cr(ctxt, 3, GET_SMSTATE(u32, smbase, 0x7ff8));
ctxt->eflags = GET_SMSTATE(u32, smbase, 0x7ff4) | X86_EFLAGS_FIXED;
ctxt->_eip = GET_SMSTATE(u32, smbase, 0x7ff0);
for (i = 0; i < 8; i++)
*reg_write(ctxt, i) = GET_SMSTATE(u32, smbase, 0x7fd0 + i * 4);
val = GET_SMSTATE(u32, smbase, 0x7fcc);
ctxt->ops->set_dr(ctxt, 6, (val & DR6_VOLATILE) | DR6_FIXED_1);
val = GET_SMSTATE(u32, smbase, 0x7fc8);
ctxt->ops->set_dr(ctxt, 7, (val & DR7_VOLATILE) | DR7_FIXED_1);
selector = GET_SMSTATE(u32, smbase, 0x7fc4);
set_desc_base(&desc, GET_SMSTATE(u32, smbase, 0x7f64));
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, 0x7f60));
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, 0x7f5c));
ctxt->ops->set_segment(ctxt, selector, &desc, 0, VCPU_SREG_TR);
selector = GET_SMSTATE(u32, smbase, 0x7fc0);
set_desc_base(&desc, GET_SMSTATE(u32, smbase, 0x7f80));
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, 0x7f7c));
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, 0x7f78));
ctxt->ops->set_segment(ctxt, selector, &desc, 0, VCPU_SREG_LDTR);
dt.address = GET_SMSTATE(u32, smbase, 0x7f74);
dt.size = GET_SMSTATE(u32, smbase, 0x7f70);
ctxt->ops->set_gdt(ctxt, &dt);
dt.address = GET_SMSTATE(u32, smbase, 0x7f58);
dt.size = GET_SMSTATE(u32, smbase, 0x7f54);
ctxt->ops->set_idt(ctxt, &dt);
for (i = 0; i < 6; i++) {
int r = rsm_load_seg_32(ctxt, smbase, i);
if (r != X86EMUL_CONTINUE)
return r;
}
cr4 = GET_SMSTATE(u32, smbase, 0x7f14);
ctxt->ops->set_smbase(ctxt, GET_SMSTATE(u32, smbase, 0x7ef8));
return rsm_enter_protected_mode(ctxt, cr0, cr4);
}
static int rsm_load_state_64(struct x86_emulate_ctxt *ctxt, u64 smbase)
{
struct desc_struct desc;
struct desc_ptr dt;
u64 val, cr0, cr4;
u32 base3;
u16 selector;
int i, r;
for (i = 0; i < 16; i++)
*reg_write(ctxt, i) = GET_SMSTATE(u64, smbase, 0x7ff8 - i * 8);
ctxt->_eip = GET_SMSTATE(u64, smbase, 0x7f78);
ctxt->eflags = GET_SMSTATE(u32, smbase, 0x7f70) | X86_EFLAGS_FIXED;
val = GET_SMSTATE(u32, smbase, 0x7f68);
ctxt->ops->set_dr(ctxt, 6, (val & DR6_VOLATILE) | DR6_FIXED_1);
val = GET_SMSTATE(u32, smbase, 0x7f60);
ctxt->ops->set_dr(ctxt, 7, (val & DR7_VOLATILE) | DR7_FIXED_1);
cr0 = GET_SMSTATE(u64, smbase, 0x7f58);
ctxt->ops->set_cr(ctxt, 3, GET_SMSTATE(u64, smbase, 0x7f50));
cr4 = GET_SMSTATE(u64, smbase, 0x7f48);
ctxt->ops->set_smbase(ctxt, GET_SMSTATE(u32, smbase, 0x7f00));
val = GET_SMSTATE(u64, smbase, 0x7ed0);
ctxt->ops->set_msr(ctxt, MSR_EFER, val & ~EFER_LMA);
selector = GET_SMSTATE(u32, smbase, 0x7e90);
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, 0x7e92) << 8);
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, 0x7e94));
set_desc_base(&desc, GET_SMSTATE(u32, smbase, 0x7e98));
base3 = GET_SMSTATE(u32, smbase, 0x7e9c);
ctxt->ops->set_segment(ctxt, selector, &desc, base3, VCPU_SREG_TR);
dt.size = GET_SMSTATE(u32, smbase, 0x7e84);
dt.address = GET_SMSTATE(u64, smbase, 0x7e88);
ctxt->ops->set_idt(ctxt, &dt);
selector = GET_SMSTATE(u32, smbase, 0x7e70);
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, 0x7e72) << 8);
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, 0x7e74));
set_desc_base(&desc, GET_SMSTATE(u32, smbase, 0x7e78));
base3 = GET_SMSTATE(u32, smbase, 0x7e7c);
ctxt->ops->set_segment(ctxt, selector, &desc, base3, VCPU_SREG_LDTR);
dt.size = GET_SMSTATE(u32, smbase, 0x7e64);
dt.address = GET_SMSTATE(u64, smbase, 0x7e68);
ctxt->ops->set_gdt(ctxt, &dt);
r = rsm_enter_protected_mode(ctxt, cr0, cr4);
if (r != X86EMUL_CONTINUE)
return r;
for (i = 0; i < 6; i++) {
r = rsm_load_seg_64(ctxt, smbase, i);
if (r != X86EMUL_CONTINUE)
return r;
}
return X86EMUL_CONTINUE;
}
static int em_rsm(struct x86_emulate_ctxt *ctxt)
{
unsigned long cr0, cr4, efer;
u64 smbase;
int ret;
if ((ctxt->emul_flags & X86EMUL_SMM_MASK) == 0)
return emulate_ud(ctxt);
/*
* Get back to real mode, to prepare a safe state in which to load
* CR0/CR3/CR4/EFER. It's all a bit more complicated if the vCPU
* supports long mode.
*/
cr4 = ctxt->ops->get_cr(ctxt, 4);
if (emulator_has_longmode(ctxt)) {
struct desc_struct cs_desc;
/* Zero CR4.PCIDE before CR0.PG. */
if (cr4 & X86_CR4_PCIDE) {
ctxt->ops->set_cr(ctxt, 4, cr4 & ~X86_CR4_PCIDE);
cr4 &= ~X86_CR4_PCIDE;
}
/* A 32-bit code segment is required to clear EFER.LMA. */
memset(&cs_desc, 0, sizeof(cs_desc));
cs_desc.type = 0xb;
cs_desc.s = cs_desc.g = cs_desc.p = 1;
ctxt->ops->set_segment(ctxt, 0, &cs_desc, 0, VCPU_SREG_CS);
}
/* For the 64-bit case, this will clear EFER.LMA. */
cr0 = ctxt->ops->get_cr(ctxt, 0);
if (cr0 & X86_CR0_PE)
ctxt->ops->set_cr(ctxt, 0, cr0 & ~(X86_CR0_PG | X86_CR0_PE));
/* Now clear CR4.PAE (which must be done before clearing EFER.LME). */
if (cr4 & X86_CR4_PAE)
ctxt->ops->set_cr(ctxt, 4, cr4 & ~X86_CR4_PAE);
/* And finally go back to 32-bit mode. */
efer = 0;
ctxt->ops->set_msr(ctxt, MSR_EFER, efer);
smbase = ctxt->ops->get_smbase(ctxt);
if (emulator_has_longmode(ctxt))
ret = rsm_load_state_64(ctxt, smbase + 0x8000);
else
ret = rsm_load_state_32(ctxt, smbase + 0x8000);
if (ret != X86EMUL_CONTINUE) {
/* FIXME: should triple fault */
return X86EMUL_UNHANDLEABLE;
}
if ((ctxt->emul_flags & X86EMUL_SMM_INSIDE_NMI_MASK) == 0)
ctxt->ops->set_nmi_mask(ctxt, false);
ctxt->emul_flags &= ~X86EMUL_SMM_INSIDE_NMI_MASK;
ctxt->emul_flags &= ~X86EMUL_SMM_MASK;
return X86EMUL_CONTINUE;
}
static void
setup_syscalls_segments(struct x86_emulate_ctxt *ctxt,
struct desc_struct *cs, struct desc_struct *ss)
{
cs->l = 0; /* will be adjusted later */
set_desc_base(cs, 0); /* flat segment */
cs->g = 1; /* 4kb granularity */
set_desc_limit(cs, 0xfffff); /* 4GB limit */
cs->type = 0x0b; /* Read, Execute, Accessed */
cs->s = 1;
cs->dpl = 0; /* will be adjusted later */
cs->p = 1;
cs->d = 1;
cs->avl = 0;
set_desc_base(ss, 0); /* flat segment */
set_desc_limit(ss, 0xfffff); /* 4GB limit */
ss->g = 1; /* 4kb granularity */
ss->s = 1;
ss->type = 0x03; /* Read/Write, Accessed */
ss->d = 1; /* 32bit stack segment */
ss->dpl = 0;
ss->p = 1;
ss->l = 0;
ss->avl = 0;
}
static bool vendor_intel(struct x86_emulate_ctxt *ctxt)
{
u32 eax, ebx, ecx, edx;
eax = ecx = 0;
ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
return ebx == X86EMUL_CPUID_VENDOR_GenuineIntel_ebx
&& ecx == X86EMUL_CPUID_VENDOR_GenuineIntel_ecx
&& edx == X86EMUL_CPUID_VENDOR_GenuineIntel_edx;
}
static bool em_syscall_is_enabled(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
u32 eax, ebx, ecx, edx;
/*
* syscall should always be enabled in longmode - so only become
* vendor specific (cpuid) if other modes are active...
*/
if (ctxt->mode == X86EMUL_MODE_PROT64)
return true;
eax = 0x00000000;
ecx = 0x00000000;
ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
/*
* Intel ("GenuineIntel")
* remark: Intel CPUs only support "syscall" in 64bit
* longmode. Also an 64bit guest with a
* 32bit compat-app running will #UD !! While this
* behaviour can be fixed (by emulating) into AMD
* response - CPUs of AMD can't behave like Intel.
*/
if (ebx == X86EMUL_CPUID_VENDOR_GenuineIntel_ebx &&
ecx == X86EMUL_CPUID_VENDOR_GenuineIntel_ecx &&
edx == X86EMUL_CPUID_VENDOR_GenuineIntel_edx)
return false;
/* AMD ("AuthenticAMD") */
if (ebx == X86EMUL_CPUID_VENDOR_AuthenticAMD_ebx &&
ecx == X86EMUL_CPUID_VENDOR_AuthenticAMD_ecx &&
edx == X86EMUL_CPUID_VENDOR_AuthenticAMD_edx)
return true;
/* AMD ("AMDisbetter!") */
if (ebx == X86EMUL_CPUID_VENDOR_AMDisbetterI_ebx &&
ecx == X86EMUL_CPUID_VENDOR_AMDisbetterI_ecx &&
edx == X86EMUL_CPUID_VENDOR_AMDisbetterI_edx)
return true;
/* default: (not Intel, not AMD), apply Intel's stricter rules... */
return false;
}
static int em_syscall(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data;
u16 cs_sel, ss_sel;
u64 efer = 0;
/* syscall is not available in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86)
return emulate_ud(ctxt);
if (!(em_syscall_is_enabled(ctxt)))
return emulate_ud(ctxt);
ops->get_msr(ctxt, MSR_EFER, &efer);
setup_syscalls_segments(ctxt, &cs, &ss);
if (!(efer & EFER_SCE))
return emulate_ud(ctxt);
ops->get_msr(ctxt, MSR_STAR, &msr_data);
msr_data >>= 32;
cs_sel = (u16)(msr_data & 0xfffc);
ss_sel = (u16)(msr_data + 8);
if (efer & EFER_LMA) {
cs.d = 0;
cs.l = 1;
}
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
*reg_write(ctxt, VCPU_REGS_RCX) = ctxt->_eip;
if (efer & EFER_LMA) {
#ifdef CONFIG_X86_64
*reg_write(ctxt, VCPU_REGS_R11) = ctxt->eflags;
ops->get_msr(ctxt,
ctxt->mode == X86EMUL_MODE_PROT64 ?
MSR_LSTAR : MSR_CSTAR, &msr_data);
ctxt->_eip = msr_data;
ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data);
ctxt->eflags &= ~msr_data;
ctxt->eflags |= X86_EFLAGS_FIXED;
#endif
} else {
/* legacy mode */
ops->get_msr(ctxt, MSR_STAR, &msr_data);
ctxt->_eip = (u32)msr_data;
ctxt->eflags &= ~(X86_EFLAGS_VM | X86_EFLAGS_IF);
}
return X86EMUL_CONTINUE;
}
static int em_sysenter(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data;
u16 cs_sel, ss_sel;
u64 efer = 0;
ops->get_msr(ctxt, MSR_EFER, &efer);
/* inject #GP if in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL)
return emulate_gp(ctxt, 0);
/*
* Not recognized on AMD in compat mode (but is recognized in legacy
* mode).
*/
if ((ctxt->mode != X86EMUL_MODE_PROT64) && (efer & EFER_LMA)
&& !vendor_intel(ctxt))
return emulate_ud(ctxt);
/* sysenter/sysexit have not been tested in 64bit mode. */
if (ctxt->mode == X86EMUL_MODE_PROT64)
return X86EMUL_UNHANDLEABLE;
setup_syscalls_segments(ctxt, &cs, &ss);
ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
if ((msr_data & 0xfffc) == 0x0)
return emulate_gp(ctxt, 0);
ctxt->eflags &= ~(X86_EFLAGS_VM | X86_EFLAGS_IF);
cs_sel = (u16)msr_data & ~SEGMENT_RPL_MASK;
ss_sel = cs_sel + 8;
if (efer & EFER_LMA) {
cs.d = 0;
cs.l = 1;
}
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data);
ctxt->_eip = (efer & EFER_LMA) ? msr_data : (u32)msr_data;
ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data);
*reg_write(ctxt, VCPU_REGS_RSP) = (efer & EFER_LMA) ? msr_data :
(u32)msr_data;
return X86EMUL_CONTINUE;
}
static int em_sysexit(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data, rcx, rdx;
int usermode;
u16 cs_sel = 0, ss_sel = 0;
/* inject #GP if in real mode or Virtual 8086 mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86)
return emulate_gp(ctxt, 0);
setup_syscalls_segments(ctxt, &cs, &ss);
if ((ctxt->rex_prefix & 0x8) != 0x0)
usermode = X86EMUL_MODE_PROT64;
else
usermode = X86EMUL_MODE_PROT32;
rcx = reg_read(ctxt, VCPU_REGS_RCX);
rdx = reg_read(ctxt, VCPU_REGS_RDX);
cs.dpl = 3;
ss.dpl = 3;
ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
switch (usermode) {
case X86EMUL_MODE_PROT32:
cs_sel = (u16)(msr_data + 16);
if ((msr_data & 0xfffc) == 0x0)
return emulate_gp(ctxt, 0);
ss_sel = (u16)(msr_data + 24);
rcx = (u32)rcx;
rdx = (u32)rdx;
break;
case X86EMUL_MODE_PROT64:
cs_sel = (u16)(msr_data + 32);
if (msr_data == 0x0)
return emulate_gp(ctxt, 0);
ss_sel = cs_sel + 8;
cs.d = 0;
cs.l = 1;
if (is_noncanonical_address(rcx) ||
is_noncanonical_address(rdx))
return emulate_gp(ctxt, 0);
break;
}
cs_sel |= SEGMENT_RPL_MASK;
ss_sel |= SEGMENT_RPL_MASK;
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ctxt->_eip = rdx;
*reg_write(ctxt, VCPU_REGS_RSP) = rcx;
return X86EMUL_CONTINUE;
}
static bool emulator_bad_iopl(struct x86_emulate_ctxt *ctxt)
{
int iopl;
if (ctxt->mode == X86EMUL_MODE_REAL)
return false;
if (ctxt->mode == X86EMUL_MODE_VM86)
return true;
iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> X86_EFLAGS_IOPL_BIT;
return ctxt->ops->cpl(ctxt) > iopl;
}
static bool emulator_io_port_access_allowed(struct x86_emulate_ctxt *ctxt,
u16 port, u16 len)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct tr_seg;
u32 base3;
int r;
u16 tr, io_bitmap_ptr, perm, bit_idx = port & 0x7;
unsigned mask = (1 << len) - 1;
unsigned long base;
ops->get_segment(ctxt, &tr, &tr_seg, &base3, VCPU_SREG_TR);
if (!tr_seg.p)
return false;
if (desc_limit_scaled(&tr_seg) < 103)
return false;
base = get_desc_base(&tr_seg);
#ifdef CONFIG_X86_64
base |= ((u64)base3) << 32;
#endif
r = ops->read_std(ctxt, base + 102, &io_bitmap_ptr, 2, NULL);
if (r != X86EMUL_CONTINUE)
return false;
if (io_bitmap_ptr + port/8 > desc_limit_scaled(&tr_seg))
return false;
r = ops->read_std(ctxt, base + io_bitmap_ptr + port/8, &perm, 2, NULL);
if (r != X86EMUL_CONTINUE)
return false;
if ((perm >> bit_idx) & mask)
return false;
return true;
}
static bool emulator_io_permited(struct x86_emulate_ctxt *ctxt,
u16 port, u16 len)
{
if (ctxt->perm_ok)
return true;
if (emulator_bad_iopl(ctxt))
if (!emulator_io_port_access_allowed(ctxt, port, len))
return false;
ctxt->perm_ok = true;
return true;
}
static void string_registers_quirk(struct x86_emulate_ctxt *ctxt)
{
/*
* Intel CPUs mask the counter and pointers in quite strange
* manner when ECX is zero due to REP-string optimizations.
*/
#ifdef CONFIG_X86_64
if (ctxt->ad_bytes != 4 || !vendor_intel(ctxt))
return;
*reg_write(ctxt, VCPU_REGS_RCX) = 0;
switch (ctxt->b) {
case 0xa4: /* movsb */
case 0xa5: /* movsd/w */
*reg_rmw(ctxt, VCPU_REGS_RSI) &= (u32)-1;
/* fall through */
case 0xaa: /* stosb */
case 0xab: /* stosd/w */
*reg_rmw(ctxt, VCPU_REGS_RDI) &= (u32)-1;
}
#endif
}
static void save_state_to_tss16(struct x86_emulate_ctxt *ctxt,
struct tss_segment_16 *tss)
{
tss->ip = ctxt->_eip;
tss->flag = ctxt->eflags;
tss->ax = reg_read(ctxt, VCPU_REGS_RAX);
tss->cx = reg_read(ctxt, VCPU_REGS_RCX);
tss->dx = reg_read(ctxt, VCPU_REGS_RDX);
tss->bx = reg_read(ctxt, VCPU_REGS_RBX);
tss->sp = reg_read(ctxt, VCPU_REGS_RSP);
tss->bp = reg_read(ctxt, VCPU_REGS_RBP);
tss->si = reg_read(ctxt, VCPU_REGS_RSI);
tss->di = reg_read(ctxt, VCPU_REGS_RDI);
tss->es = get_segment_selector(ctxt, VCPU_SREG_ES);
tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS);
tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS);
tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS);
tss->ldt = get_segment_selector(ctxt, VCPU_SREG_LDTR);
}
static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt,
struct tss_segment_16 *tss)
{
int ret;
u8 cpl;
ctxt->_eip = tss->ip;
ctxt->eflags = tss->flag | 2;
*reg_write(ctxt, VCPU_REGS_RAX) = tss->ax;
*reg_write(ctxt, VCPU_REGS_RCX) = tss->cx;
*reg_write(ctxt, VCPU_REGS_RDX) = tss->dx;
*reg_write(ctxt, VCPU_REGS_RBX) = tss->bx;
*reg_write(ctxt, VCPU_REGS_RSP) = tss->sp;
*reg_write(ctxt, VCPU_REGS_RBP) = tss->bp;
*reg_write(ctxt, VCPU_REGS_RSI) = tss->si;
*reg_write(ctxt, VCPU_REGS_RDI) = tss->di;
/*
* SDM says that segment selectors are loaded before segment
* descriptors
*/
set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR);
set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
cpl = tss->cs & 3;
/*
* Now load segment descriptors. If fault happens at this stage
* it is handled in a context of new task
*/
ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
return X86EMUL_CONTINUE;
}
static int task_switch_16(struct x86_emulate_ctxt *ctxt,
u16 tss_selector, u16 old_tss_sel,
ulong old_tss_base, struct desc_struct *new_desc)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct tss_segment_16 tss_seg;
int ret;
u32 new_tss_base = get_desc_base(new_desc);
ret = ops->read_std(ctxt, old_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
save_state_to_tss16(ctxt, &tss_seg);
ret = ops->write_std(ctxt, old_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = ops->read_std(ctxt, new_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
if (old_tss_sel != 0xffff) {
tss_seg.prev_task_link = old_tss_sel;
ret = ops->write_std(ctxt, new_tss_base,
&tss_seg.prev_task_link,
sizeof tss_seg.prev_task_link,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
}
return load_state_from_tss16(ctxt, &tss_seg);
}
static void save_state_to_tss32(struct x86_emulate_ctxt *ctxt,
struct tss_segment_32 *tss)
{
/* CR3 and ldt selector are not saved intentionally */
tss->eip = ctxt->_eip;
tss->eflags = ctxt->eflags;
tss->eax = reg_read(ctxt, VCPU_REGS_RAX);
tss->ecx = reg_read(ctxt, VCPU_REGS_RCX);
tss->edx = reg_read(ctxt, VCPU_REGS_RDX);
tss->ebx = reg_read(ctxt, VCPU_REGS_RBX);
tss->esp = reg_read(ctxt, VCPU_REGS_RSP);
tss->ebp = reg_read(ctxt, VCPU_REGS_RBP);
tss->esi = reg_read(ctxt, VCPU_REGS_RSI);
tss->edi = reg_read(ctxt, VCPU_REGS_RDI);
tss->es = get_segment_selector(ctxt, VCPU_SREG_ES);
tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS);
tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS);
tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS);
tss->fs = get_segment_selector(ctxt, VCPU_SREG_FS);
tss->gs = get_segment_selector(ctxt, VCPU_SREG_GS);
}
static int load_state_from_tss32(struct x86_emulate_ctxt *ctxt,
struct tss_segment_32 *tss)
{
int ret;
u8 cpl;
if (ctxt->ops->set_cr(ctxt, 3, tss->cr3))
return emulate_gp(ctxt, 0);
ctxt->_eip = tss->eip;
ctxt->eflags = tss->eflags | 2;
/* General purpose registers */
*reg_write(ctxt, VCPU_REGS_RAX) = tss->eax;
*reg_write(ctxt, VCPU_REGS_RCX) = tss->ecx;
*reg_write(ctxt, VCPU_REGS_RDX) = tss->edx;
*reg_write(ctxt, VCPU_REGS_RBX) = tss->ebx;
*reg_write(ctxt, VCPU_REGS_RSP) = tss->esp;
*reg_write(ctxt, VCPU_REGS_RBP) = tss->ebp;
*reg_write(ctxt, VCPU_REGS_RSI) = tss->esi;
*reg_write(ctxt, VCPU_REGS_RDI) = tss->edi;
/*
* SDM says that segment selectors are loaded before segment
* descriptors. This is important because CPL checks will
* use CS.RPL.
*/
set_segment_selector(ctxt, tss->ldt_selector, VCPU_SREG_LDTR);
set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
set_segment_selector(ctxt, tss->fs, VCPU_SREG_FS);
set_segment_selector(ctxt, tss->gs, VCPU_SREG_GS);
/*
* If we're switching between Protected Mode and VM86, we need to make
* sure to update the mode before loading the segment descriptors so
* that the selectors are interpreted correctly.
*/
if (ctxt->eflags & X86_EFLAGS_VM) {
ctxt->mode = X86EMUL_MODE_VM86;
cpl = 3;
} else {
ctxt->mode = X86EMUL_MODE_PROT32;
cpl = tss->cs & 3;
}
/*
* Now load segment descriptors. If fault happenes at this stage
* it is handled in a context of new task
*/
ret = __load_segment_descriptor(ctxt, tss->ldt_selector, VCPU_SREG_LDTR,
cpl, X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->fs, VCPU_SREG_FS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->gs, VCPU_SREG_GS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
return ret;
}
static int task_switch_32(struct x86_emulate_ctxt *ctxt,
u16 tss_selector, u16 old_tss_sel,
ulong old_tss_base, struct desc_struct *new_desc)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct tss_segment_32 tss_seg;
int ret;
u32 new_tss_base = get_desc_base(new_desc);
u32 eip_offset = offsetof(struct tss_segment_32, eip);
u32 ldt_sel_offset = offsetof(struct tss_segment_32, ldt_selector);
ret = ops->read_std(ctxt, old_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
save_state_to_tss32(ctxt, &tss_seg);
/* Only GP registers and segment selectors are saved */
ret = ops->write_std(ctxt, old_tss_base + eip_offset, &tss_seg.eip,
ldt_sel_offset - eip_offset, &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = ops->read_std(ctxt, new_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
if (old_tss_sel != 0xffff) {
tss_seg.prev_task_link = old_tss_sel;
ret = ops->write_std(ctxt, new_tss_base,
&tss_seg.prev_task_link,
sizeof tss_seg.prev_task_link,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
}
return load_state_from_tss32(ctxt, &tss_seg);
}
static int emulator_do_task_switch(struct x86_emulate_ctxt *ctxt,
u16 tss_selector, int idt_index, int reason,
bool has_error_code, u32 error_code)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct curr_tss_desc, next_tss_desc;
int ret;
u16 old_tss_sel = get_segment_selector(ctxt, VCPU_SREG_TR);
ulong old_tss_base =
ops->get_cached_segment_base(ctxt, VCPU_SREG_TR);
u32 desc_limit;
ulong desc_addr, dr7;
/* FIXME: old_tss_base == ~0 ? */
ret = read_segment_descriptor(ctxt, tss_selector, &next_tss_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = read_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
/* FIXME: check that next_tss_desc is tss */
/*
* Check privileges. The three cases are task switch caused by...
*
* 1. jmp/call/int to task gate: Check against DPL of the task gate
* 2. Exception/IRQ/iret: No check is performed
* 3. jmp/call to TSS/task-gate: No check is performed since the
* hardware checks it before exiting.
*/
if (reason == TASK_SWITCH_GATE) {
if (idt_index != -1) {
/* Software interrupts */
struct desc_struct task_gate_desc;
int dpl;
ret = read_interrupt_descriptor(ctxt, idt_index,
&task_gate_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
dpl = task_gate_desc.dpl;
if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl)
return emulate_gp(ctxt, (idt_index << 3) | 0x2);
}
}
desc_limit = desc_limit_scaled(&next_tss_desc);
if (!next_tss_desc.p ||
((desc_limit < 0x67 && (next_tss_desc.type & 8)) ||
desc_limit < 0x2b)) {
return emulate_ts(ctxt, tss_selector & 0xfffc);
}
if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
curr_tss_desc.type &= ~(1 << 1); /* clear busy flag */
write_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc);
}
if (reason == TASK_SWITCH_IRET)
ctxt->eflags = ctxt->eflags & ~X86_EFLAGS_NT;
/* set back link to prev task only if NT bit is set in eflags
note that old_tss_sel is not used after this point */
if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE)
old_tss_sel = 0xffff;
if (next_tss_desc.type & 8)
ret = task_switch_32(ctxt, tss_selector, old_tss_sel,
old_tss_base, &next_tss_desc);
else
ret = task_switch_16(ctxt, tss_selector, old_tss_sel,
old_tss_base, &next_tss_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE)
ctxt->eflags = ctxt->eflags | X86_EFLAGS_NT;
if (reason != TASK_SWITCH_IRET) {
next_tss_desc.type |= (1 << 1); /* set busy flag */
write_segment_descriptor(ctxt, tss_selector, &next_tss_desc);
}
ops->set_cr(ctxt, 0, ops->get_cr(ctxt, 0) | X86_CR0_TS);
ops->set_segment(ctxt, tss_selector, &next_tss_desc, 0, VCPU_SREG_TR);
if (has_error_code) {
ctxt->op_bytes = ctxt->ad_bytes = (next_tss_desc.type & 8) ? 4 : 2;
ctxt->lock_prefix = 0;
ctxt->src.val = (unsigned long) error_code;
ret = em_push(ctxt);
}
ops->get_dr(ctxt, 7, &dr7);
ops->set_dr(ctxt, 7, dr7 & ~(DR_LOCAL_ENABLE_MASK | DR_LOCAL_SLOWDOWN));
return ret;
}
int emulator_task_switch(struct x86_emulate_ctxt *ctxt,
u16 tss_selector, int idt_index, int reason,
bool has_error_code, u32 error_code)
{
int rc;
invalidate_registers(ctxt);
ctxt->_eip = ctxt->eip;
ctxt->dst.type = OP_NONE;
rc = emulator_do_task_switch(ctxt, tss_selector, idt_index, reason,
has_error_code, error_code);
if (rc == X86EMUL_CONTINUE) {
ctxt->eip = ctxt->_eip;
writeback_registers(ctxt);
}
return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK;
}
static void string_addr_inc(struct x86_emulate_ctxt *ctxt, int reg,
struct operand *op)
{
int df = (ctxt->eflags & X86_EFLAGS_DF) ? -op->count : op->count;
register_address_increment(ctxt, reg, df * op->bytes);
op->addr.mem.ea = register_address(ctxt, reg);
}
static int em_das(struct x86_emulate_ctxt *ctxt)
{
u8 al, old_al;
bool af, cf, old_cf;
cf = ctxt->eflags & X86_EFLAGS_CF;
al = ctxt->dst.val;
old_al = al;
old_cf = cf;
cf = false;
af = ctxt->eflags & X86_EFLAGS_AF;
if ((al & 0x0f) > 9 || af) {
al -= 6;
cf = old_cf | (al >= 250);
af = true;
} else {
af = false;
}
if (old_al > 0x99 || old_cf) {
al -= 0x60;
cf = true;
}
ctxt->dst.val = al;
/* Set PF, ZF, SF */
ctxt->src.type = OP_IMM;
ctxt->src.val = 0;
ctxt->src.bytes = 1;
fastop(ctxt, em_or);
ctxt->eflags &= ~(X86_EFLAGS_AF | X86_EFLAGS_CF);
if (cf)
ctxt->eflags |= X86_EFLAGS_CF;
if (af)
ctxt->eflags |= X86_EFLAGS_AF;
return X86EMUL_CONTINUE;
}
static int em_aam(struct x86_emulate_ctxt *ctxt)
{
u8 al, ah;
if (ctxt->src.val == 0)
return emulate_de(ctxt);
al = ctxt->dst.val & 0xff;
ah = al / ctxt->src.val;
al %= ctxt->src.val;
ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al | (ah << 8);
/* Set PF, ZF, SF */
ctxt->src.type = OP_IMM;
ctxt->src.val = 0;
ctxt->src.bytes = 1;
fastop(ctxt, em_or);
return X86EMUL_CONTINUE;
}
static int em_aad(struct x86_emulate_ctxt *ctxt)
{
u8 al = ctxt->dst.val & 0xff;
u8 ah = (ctxt->dst.val >> 8) & 0xff;
al = (al + (ah * ctxt->src.val)) & 0xff;
ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al;
/* Set PF, ZF, SF */
ctxt->src.type = OP_IMM;
ctxt->src.val = 0;
ctxt->src.bytes = 1;
fastop(ctxt, em_or);
return X86EMUL_CONTINUE;
}
static int em_call(struct x86_emulate_ctxt *ctxt)
{
int rc;
long rel = ctxt->src.val;
ctxt->src.val = (unsigned long)ctxt->_eip;
rc = jmp_rel(ctxt, rel);
if (rc != X86EMUL_CONTINUE)
return rc;
return em_push(ctxt);
}
static int em_call_far(struct x86_emulate_ctxt *ctxt)
{
u16 sel, old_cs;
ulong old_eip;
int rc;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
int cpl = ctxt->ops->cpl(ctxt);
enum x86emul_mode prev_mode = ctxt->mode;
old_eip = ctxt->_eip;
ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,
X86_TRANSFER_CALL_JMP, &new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, ctxt->src.val, &new_desc);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_cs;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_eip;
rc = em_push(ctxt);
/* If we failed, we tainted the memory, but the very least we should
restore cs */
if (rc != X86EMUL_CONTINUE) {
pr_warn_once("faulting far call emulation tainted memory\n");
goto fail;
}
return rc;
fail:
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
ctxt->mode = prev_mode;
return rc;
}
static int em_ret_near_imm(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip;
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_near(ctxt, eip);
if (rc != X86EMUL_CONTINUE)
return rc;
rsp_increment(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
static int em_xchg(struct x86_emulate_ctxt *ctxt)
{
/* Write back the register source. */
ctxt->src.val = ctxt->dst.val;
write_register_operand(&ctxt->src);
/* Write back the memory destination with implicit LOCK prefix. */
ctxt->dst.val = ctxt->src.orig_val;
ctxt->lock_prefix = 1;
return X86EMUL_CONTINUE;
}
static int em_imul_3op(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.val = ctxt->src2.val;
return fastop(ctxt, em_imul);
}
static int em_cwd(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.type = OP_REG;
ctxt->dst.bytes = ctxt->src.bytes;
ctxt->dst.addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
ctxt->dst.val = ~((ctxt->src.val >> (ctxt->src.bytes * 8 - 1)) - 1);
return X86EMUL_CONTINUE;
}
static int em_rdtsc(struct x86_emulate_ctxt *ctxt)
{
u64 tsc = 0;
ctxt->ops->get_msr(ctxt, MSR_IA32_TSC, &tsc);
*reg_write(ctxt, VCPU_REGS_RAX) = (u32)tsc;
*reg_write(ctxt, VCPU_REGS_RDX) = tsc >> 32;
return X86EMUL_CONTINUE;
}
static int em_rdpmc(struct x86_emulate_ctxt *ctxt)
{
u64 pmc;
if (ctxt->ops->read_pmc(ctxt, reg_read(ctxt, VCPU_REGS_RCX), &pmc))
return emulate_gp(ctxt, 0);
*reg_write(ctxt, VCPU_REGS_RAX) = (u32)pmc;
*reg_write(ctxt, VCPU_REGS_RDX) = pmc >> 32;
return X86EMUL_CONTINUE;
}
static int em_mov(struct x86_emulate_ctxt *ctxt)
{
memcpy(ctxt->dst.valptr, ctxt->src.valptr, sizeof(ctxt->src.valptr));
return X86EMUL_CONTINUE;
}
#define FFL(x) bit(X86_FEATURE_##x)
static int em_movbe(struct x86_emulate_ctxt *ctxt)
{
u32 ebx, ecx, edx, eax = 1;
u16 tmp;
/*
* Check MOVBE is set in the guest-visible CPUID leaf.
*/
ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
if (!(ecx & FFL(MOVBE)))
return emulate_ud(ctxt);
switch (ctxt->op_bytes) {
case 2:
/*
* From MOVBE definition: "...When the operand size is 16 bits,
* the upper word of the destination register remains unchanged
* ..."
*
* Both casting ->valptr and ->val to u16 breaks strict aliasing
* rules so we have to do the operation almost per hand.
*/
tmp = (u16)ctxt->src.val;
ctxt->dst.val &= ~0xffffUL;
ctxt->dst.val |= (unsigned long)swab16(tmp);
break;
case 4:
ctxt->dst.val = swab32((u32)ctxt->src.val);
break;
case 8:
ctxt->dst.val = swab64(ctxt->src.val);
break;
default:
BUG();
}
return X86EMUL_CONTINUE;
}
static int em_cr_write(struct x86_emulate_ctxt *ctxt)
{
if (ctxt->ops->set_cr(ctxt, ctxt->modrm_reg, ctxt->src.val))
return emulate_gp(ctxt, 0);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_dr_write(struct x86_emulate_ctxt *ctxt)
{
unsigned long val;
if (ctxt->mode == X86EMUL_MODE_PROT64)
val = ctxt->src.val & ~0ULL;
else
val = ctxt->src.val & ~0U;
/* #UD condition is already handled. */
if (ctxt->ops->set_dr(ctxt, ctxt->modrm_reg, val) < 0)
return emulate_gp(ctxt, 0);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_wrmsr(struct x86_emulate_ctxt *ctxt)
{
u64 msr_data;
msr_data = (u32)reg_read(ctxt, VCPU_REGS_RAX)
| ((u64)reg_read(ctxt, VCPU_REGS_RDX) << 32);
if (ctxt->ops->set_msr(ctxt, reg_read(ctxt, VCPU_REGS_RCX), msr_data))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
}
static int em_rdmsr(struct x86_emulate_ctxt *ctxt)
{
u64 msr_data;
if (ctxt->ops->get_msr(ctxt, reg_read(ctxt, VCPU_REGS_RCX), &msr_data))
return emulate_gp(ctxt, 0);
*reg_write(ctxt, VCPU_REGS_RAX) = (u32)msr_data;
*reg_write(ctxt, VCPU_REGS_RDX) = msr_data >> 32;
return X86EMUL_CONTINUE;
}
static int em_mov_rm_sreg(struct x86_emulate_ctxt *ctxt)
{
if (ctxt->modrm_reg > VCPU_SREG_GS)
return emulate_ud(ctxt);
ctxt->dst.val = get_segment_selector(ctxt, ctxt->modrm_reg);
if (ctxt->dst.bytes == 4 && ctxt->dst.type == OP_MEM)
ctxt->dst.bytes = 2;
return X86EMUL_CONTINUE;
}
static int em_mov_sreg_rm(struct x86_emulate_ctxt *ctxt)
{
u16 sel = ctxt->src.val;
if (ctxt->modrm_reg == VCPU_SREG_CS || ctxt->modrm_reg > VCPU_SREG_GS)
return emulate_ud(ctxt);
if (ctxt->modrm_reg == VCPU_SREG_SS)
ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return load_segment_descriptor(ctxt, sel, ctxt->modrm_reg);
}
static int em_lldt(struct x86_emulate_ctxt *ctxt)
{
u16 sel = ctxt->src.val;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return load_segment_descriptor(ctxt, sel, VCPU_SREG_LDTR);
}
static int em_ltr(struct x86_emulate_ctxt *ctxt)
{
u16 sel = ctxt->src.val;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return load_segment_descriptor(ctxt, sel, VCPU_SREG_TR);
}
static int em_invlpg(struct x86_emulate_ctxt *ctxt)
{
int rc;
ulong linear;
rc = linearize(ctxt, ctxt->src.addr.mem, 1, false, &linear);
if (rc == X86EMUL_CONTINUE)
ctxt->ops->invlpg(ctxt, linear);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_clts(struct x86_emulate_ctxt *ctxt)
{
ulong cr0;
cr0 = ctxt->ops->get_cr(ctxt, 0);
cr0 &= ~X86_CR0_TS;
ctxt->ops->set_cr(ctxt, 0, cr0);
return X86EMUL_CONTINUE;
}
static int em_hypercall(struct x86_emulate_ctxt *ctxt)
{
int rc = ctxt->ops->fix_hypercall(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Let the processor re-execute the fixed hypercall */
ctxt->_eip = ctxt->eip;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int emulate_store_desc_ptr(struct x86_emulate_ctxt *ctxt,
void (*get)(struct x86_emulate_ctxt *ctxt,
struct desc_ptr *ptr))
{
struct desc_ptr desc_ptr;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ctxt->op_bytes = 8;
get(ctxt, &desc_ptr);
if (ctxt->op_bytes == 2) {
ctxt->op_bytes = 4;
desc_ptr.address &= 0x00ffffff;
}
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return segmented_write(ctxt, ctxt->dst.addr.mem,
&desc_ptr, 2 + ctxt->op_bytes);
}
static int em_sgdt(struct x86_emulate_ctxt *ctxt)
{
return emulate_store_desc_ptr(ctxt, ctxt->ops->get_gdt);
}
static int em_sidt(struct x86_emulate_ctxt *ctxt)
{
return emulate_store_desc_ptr(ctxt, ctxt->ops->get_idt);
}
static int em_lgdt_lidt(struct x86_emulate_ctxt *ctxt, bool lgdt)
{
struct desc_ptr desc_ptr;
int rc;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ctxt->op_bytes = 8;
rc = read_descriptor(ctxt, ctxt->src.addr.mem,
&desc_ptr.size, &desc_ptr.address,
ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->mode == X86EMUL_MODE_PROT64 &&
is_noncanonical_address(desc_ptr.address))
return emulate_gp(ctxt, 0);
if (lgdt)
ctxt->ops->set_gdt(ctxt, &desc_ptr);
else
ctxt->ops->set_idt(ctxt, &desc_ptr);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_lgdt(struct x86_emulate_ctxt *ctxt)
{
return em_lgdt_lidt(ctxt, true);
}
static int em_lidt(struct x86_emulate_ctxt *ctxt)
{
return em_lgdt_lidt(ctxt, false);
}
static int em_smsw(struct x86_emulate_ctxt *ctxt)
{
if (ctxt->dst.type == OP_MEM)
ctxt->dst.bytes = 2;
ctxt->dst.val = ctxt->ops->get_cr(ctxt, 0);
return X86EMUL_CONTINUE;
}
static int em_lmsw(struct x86_emulate_ctxt *ctxt)
{
ctxt->ops->set_cr(ctxt, 0, (ctxt->ops->get_cr(ctxt, 0) & ~0x0eul)
| (ctxt->src.val & 0x0f));
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_loop(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
register_address_increment(ctxt, VCPU_REGS_RCX, -1);
if ((address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) != 0) &&
(ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags)))
rc = jmp_rel(ctxt, ctxt->src.val);
return rc;
}
static int em_jcxz(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)
rc = jmp_rel(ctxt, ctxt->src.val);
return rc;
}
static int em_in(struct x86_emulate_ctxt *ctxt)
{
if (!pio_in_emulated(ctxt, ctxt->dst.bytes, ctxt->src.val,
&ctxt->dst.val))
return X86EMUL_IO_NEEDED;
return X86EMUL_CONTINUE;
}
static int em_out(struct x86_emulate_ctxt *ctxt)
{
ctxt->ops->pio_out_emulated(ctxt, ctxt->src.bytes, ctxt->dst.val,
&ctxt->src.val, 1);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_cli(struct x86_emulate_ctxt *ctxt)
{
if (emulator_bad_iopl(ctxt))
return emulate_gp(ctxt, 0);
ctxt->eflags &= ~X86_EFLAGS_IF;
return X86EMUL_CONTINUE;
}
static int em_sti(struct x86_emulate_ctxt *ctxt)
{
if (emulator_bad_iopl(ctxt))
return emulate_gp(ctxt, 0);
ctxt->interruptibility = KVM_X86_SHADOW_INT_STI;
ctxt->eflags |= X86_EFLAGS_IF;
return X86EMUL_CONTINUE;
}
static int em_cpuid(struct x86_emulate_ctxt *ctxt)
{
u32 eax, ebx, ecx, edx;
eax = reg_read(ctxt, VCPU_REGS_RAX);
ecx = reg_read(ctxt, VCPU_REGS_RCX);
ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
*reg_write(ctxt, VCPU_REGS_RAX) = eax;
*reg_write(ctxt, VCPU_REGS_RBX) = ebx;
*reg_write(ctxt, VCPU_REGS_RCX) = ecx;
*reg_write(ctxt, VCPU_REGS_RDX) = edx;
return X86EMUL_CONTINUE;
}
static int em_sahf(struct x86_emulate_ctxt *ctxt)
{
u32 flags;
flags = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
X86_EFLAGS_SF;
flags &= *reg_rmw(ctxt, VCPU_REGS_RAX) >> 8;
ctxt->eflags &= ~0xffUL;
ctxt->eflags |= flags | X86_EFLAGS_FIXED;
return X86EMUL_CONTINUE;
}
static int em_lahf(struct x86_emulate_ctxt *ctxt)
{
*reg_rmw(ctxt, VCPU_REGS_RAX) &= ~0xff00UL;
*reg_rmw(ctxt, VCPU_REGS_RAX) |= (ctxt->eflags & 0xff) << 8;
return X86EMUL_CONTINUE;
}
static int em_bswap(struct x86_emulate_ctxt *ctxt)
{
switch (ctxt->op_bytes) {
#ifdef CONFIG_X86_64
case 8:
asm("bswap %0" : "+r"(ctxt->dst.val));
break;
#endif
default:
asm("bswap %0" : "+r"(*(u32 *)&ctxt->dst.val));
break;
}
return X86EMUL_CONTINUE;
}
static int em_clflush(struct x86_emulate_ctxt *ctxt)
{
/* emulating clflush regardless of cpuid */
return X86EMUL_CONTINUE;
}
static int em_movsxd(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.val = (s32) ctxt->src.val;
return X86EMUL_CONTINUE;
}
static bool valid_cr(int nr)
{
switch (nr) {
case 0:
case 2 ... 4:
case 8:
return true;
default:
return false;
}
}
static int check_cr_read(struct x86_emulate_ctxt *ctxt)
{
if (!valid_cr(ctxt->modrm_reg))
return emulate_ud(ctxt);
return X86EMUL_CONTINUE;
}
static int check_cr_write(struct x86_emulate_ctxt *ctxt)
{
u64 new_val = ctxt->src.val64;
int cr = ctxt->modrm_reg;
u64 efer = 0;
static u64 cr_reserved_bits[] = {
0xffffffff00000000ULL,
0, 0, 0, /* CR3 checked later */
CR4_RESERVED_BITS,
0, 0, 0,
CR8_RESERVED_BITS,
};
if (!valid_cr(cr))
return emulate_ud(ctxt);
if (new_val & cr_reserved_bits[cr])
return emulate_gp(ctxt, 0);
switch (cr) {
case 0: {
u64 cr4;
if (((new_val & X86_CR0_PG) && !(new_val & X86_CR0_PE)) ||
((new_val & X86_CR0_NW) && !(new_val & X86_CR0_CD)))
return emulate_gp(ctxt, 0);
cr4 = ctxt->ops->get_cr(ctxt, 4);
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if ((new_val & X86_CR0_PG) && (efer & EFER_LME) &&
!(cr4 & X86_CR4_PAE))
return emulate_gp(ctxt, 0);
break;
}
case 3: {
u64 rsvd = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
rsvd = CR3_L_MODE_RESERVED_BITS & ~CR3_PCID_INVD;
if (new_val & rsvd)
return emulate_gp(ctxt, 0);
break;
}
case 4: {
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if ((efer & EFER_LMA) && !(new_val & X86_CR4_PAE))
return emulate_gp(ctxt, 0);
break;
}
}
return X86EMUL_CONTINUE;
}
static int check_dr7_gd(struct x86_emulate_ctxt *ctxt)
{
unsigned long dr7;
ctxt->ops->get_dr(ctxt, 7, &dr7);
/* Check if DR7.Global_Enable is set */
return dr7 & (1 << 13);
}
static int check_dr_read(struct x86_emulate_ctxt *ctxt)
{
int dr = ctxt->modrm_reg;
u64 cr4;
if (dr > 7)
return emulate_ud(ctxt);
cr4 = ctxt->ops->get_cr(ctxt, 4);
if ((cr4 & X86_CR4_DE) && (dr == 4 || dr == 5))
return emulate_ud(ctxt);
if (check_dr7_gd(ctxt)) {
ulong dr6;
ctxt->ops->get_dr(ctxt, 6, &dr6);
dr6 &= ~15;
dr6 |= DR6_BD | DR6_RTM;
ctxt->ops->set_dr(ctxt, 6, dr6);
return emulate_db(ctxt);
}
return X86EMUL_CONTINUE;
}
static int check_dr_write(struct x86_emulate_ctxt *ctxt)
{
u64 new_val = ctxt->src.val64;
int dr = ctxt->modrm_reg;
if ((dr == 6 || dr == 7) && (new_val & 0xffffffff00000000ULL))
return emulate_gp(ctxt, 0);
return check_dr_read(ctxt);
}
static int check_svme(struct x86_emulate_ctxt *ctxt)
{
u64 efer;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (!(efer & EFER_SVME))
return emulate_ud(ctxt);
return X86EMUL_CONTINUE;
}
static int check_svme_pa(struct x86_emulate_ctxt *ctxt)
{
u64 rax = reg_read(ctxt, VCPU_REGS_RAX);
/* Valid physical address? */
if (rax & 0xffff000000000000ULL)
return emulate_gp(ctxt, 0);
return check_svme(ctxt);
}
static int check_rdtsc(struct x86_emulate_ctxt *ctxt)
{
u64 cr4 = ctxt->ops->get_cr(ctxt, 4);
if (cr4 & X86_CR4_TSD && ctxt->ops->cpl(ctxt))
return emulate_ud(ctxt);
return X86EMUL_CONTINUE;
}
static int check_rdpmc(struct x86_emulate_ctxt *ctxt)
{
u64 cr4 = ctxt->ops->get_cr(ctxt, 4);
u64 rcx = reg_read(ctxt, VCPU_REGS_RCX);
if ((!(cr4 & X86_CR4_PCE) && ctxt->ops->cpl(ctxt)) ||
ctxt->ops->check_pmc(ctxt, rcx))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
}
static int check_perm_in(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.bytes = min(ctxt->dst.bytes, 4u);
if (!emulator_io_permited(ctxt, ctxt->src.val, ctxt->dst.bytes))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
}
static int check_perm_out(struct x86_emulate_ctxt *ctxt)
{
ctxt->src.bytes = min(ctxt->src.bytes, 4u);
if (!emulator_io_permited(ctxt, ctxt->dst.val, ctxt->src.bytes))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
}
#define D(_y) { .flags = (_y) }
#define DI(_y, _i) { .flags = (_y)|Intercept, .intercept = x86_intercept_##_i }
#define DIP(_y, _i, _p) { .flags = (_y)|Intercept|CheckPerm, \
.intercept = x86_intercept_##_i, .check_perm = (_p) }
#define N D(NotImpl)
#define EXT(_f, _e) { .flags = ((_f) | RMExt), .u.group = (_e) }
#define G(_f, _g) { .flags = ((_f) | Group | ModRM), .u.group = (_g) }
#define GD(_f, _g) { .flags = ((_f) | GroupDual | ModRM), .u.gdual = (_g) }
#define ID(_f, _i) { .flags = ((_f) | InstrDual | ModRM), .u.idual = (_i) }
#define MD(_f, _m) { .flags = ((_f) | ModeDual), .u.mdual = (_m) }
#define E(_f, _e) { .flags = ((_f) | Escape | ModRM), .u.esc = (_e) }
#define I(_f, _e) { .flags = (_f), .u.execute = (_e) }
#define F(_f, _e) { .flags = (_f) | Fastop, .u.fastop = (_e) }
#define II(_f, _e, _i) \
{ .flags = (_f)|Intercept, .u.execute = (_e), .intercept = x86_intercept_##_i }
#define IIP(_f, _e, _i, _p) \
{ .flags = (_f)|Intercept|CheckPerm, .u.execute = (_e), \
.intercept = x86_intercept_##_i, .check_perm = (_p) }
#define GP(_f, _g) { .flags = ((_f) | Prefix), .u.gprefix = (_g) }
#define D2bv(_f) D((_f) | ByteOp), D(_f)
#define D2bvIP(_f, _i, _p) DIP((_f) | ByteOp, _i, _p), DIP(_f, _i, _p)
#define I2bv(_f, _e) I((_f) | ByteOp, _e), I(_f, _e)
#define F2bv(_f, _e) F((_f) | ByteOp, _e), F(_f, _e)
#define I2bvIP(_f, _e, _i, _p) \
IIP((_f) | ByteOp, _e, _i, _p), IIP(_f, _e, _i, _p)
#define F6ALU(_f, _e) F2bv((_f) | DstMem | SrcReg | ModRM, _e), \
F2bv(((_f) | DstReg | SrcMem | ModRM) & ~Lock, _e), \
F2bv(((_f) & ~Lock) | DstAcc | SrcImm, _e)
static const struct opcode group7_rm0[] = {
N,
I(SrcNone | Priv | EmulateOnUD, em_hypercall),
N, N, N, N, N, N,
};
static const struct opcode group7_rm1[] = {
DI(SrcNone | Priv, monitor),
DI(SrcNone | Priv, mwait),
N, N, N, N, N, N,
};
static const struct opcode group7_rm3[] = {
DIP(SrcNone | Prot | Priv, vmrun, check_svme_pa),
II(SrcNone | Prot | EmulateOnUD, em_hypercall, vmmcall),
DIP(SrcNone | Prot | Priv, vmload, check_svme_pa),
DIP(SrcNone | Prot | Priv, vmsave, check_svme_pa),
DIP(SrcNone | Prot | Priv, stgi, check_svme),
DIP(SrcNone | Prot | Priv, clgi, check_svme),
DIP(SrcNone | Prot | Priv, skinit, check_svme),
DIP(SrcNone | Prot | Priv, invlpga, check_svme),
};
static const struct opcode group7_rm7[] = {
N,
DIP(SrcNone, rdtscp, check_rdtsc),
N, N, N, N, N, N,
};
static const struct opcode group1[] = {
F(Lock, em_add),
F(Lock | PageTable, em_or),
F(Lock, em_adc),
F(Lock, em_sbb),
F(Lock | PageTable, em_and),
F(Lock, em_sub),
F(Lock, em_xor),
F(NoWrite, em_cmp),
};
static const struct opcode group1A[] = {
I(DstMem | SrcNone | Mov | Stack | IncSP, em_pop), N, N, N, N, N, N, N,
};
static const struct opcode group2[] = {
F(DstMem | ModRM, em_rol),
F(DstMem | ModRM, em_ror),
F(DstMem | ModRM, em_rcl),
F(DstMem | ModRM, em_rcr),
F(DstMem | ModRM, em_shl),
F(DstMem | ModRM, em_shr),
F(DstMem | ModRM, em_shl),
F(DstMem | ModRM, em_sar),
};
static const struct opcode group3[] = {
F(DstMem | SrcImm | NoWrite, em_test),
F(DstMem | SrcImm | NoWrite, em_test),
F(DstMem | SrcNone | Lock, em_not),
F(DstMem | SrcNone | Lock, em_neg),
F(DstXacc | Src2Mem, em_mul_ex),
F(DstXacc | Src2Mem, em_imul_ex),
F(DstXacc | Src2Mem, em_div_ex),
F(DstXacc | Src2Mem, em_idiv_ex),
};
static const struct opcode group4[] = {
F(ByteOp | DstMem | SrcNone | Lock, em_inc),
F(ByteOp | DstMem | SrcNone | Lock, em_dec),
N, N, N, N, N, N,
};
static const struct opcode group5[] = {
F(DstMem | SrcNone | Lock, em_inc),
F(DstMem | SrcNone | Lock, em_dec),
I(SrcMem | NearBranch, em_call_near_abs),
I(SrcMemFAddr | ImplicitOps, em_call_far),
I(SrcMem | NearBranch, em_jmp_abs),
I(SrcMemFAddr | ImplicitOps, em_jmp_far),
I(SrcMem | Stack, em_push), D(Undefined),
};
static const struct opcode group6[] = {
DI(Prot | DstMem, sldt),
DI(Prot | DstMem, str),
II(Prot | Priv | SrcMem16, em_lldt, lldt),
II(Prot | Priv | SrcMem16, em_ltr, ltr),
N, N, N, N,
};
static const struct group_dual group7 = { {
II(Mov | DstMem, em_sgdt, sgdt),
II(Mov | DstMem, em_sidt, sidt),
II(SrcMem | Priv, em_lgdt, lgdt),
II(SrcMem | Priv, em_lidt, lidt),
II(SrcNone | DstMem | Mov, em_smsw, smsw), N,
II(SrcMem16 | Mov | Priv, em_lmsw, lmsw),
II(SrcMem | ByteOp | Priv | NoAccess, em_invlpg, invlpg),
}, {
EXT(0, group7_rm0),
EXT(0, group7_rm1),
N, EXT(0, group7_rm3),
II(SrcNone | DstMem | Mov, em_smsw, smsw), N,
II(SrcMem16 | Mov | Priv, em_lmsw, lmsw),
EXT(0, group7_rm7),
} };
static const struct opcode group8[] = {
N, N, N, N,
F(DstMem | SrcImmByte | NoWrite, em_bt),
F(DstMem | SrcImmByte | Lock | PageTable, em_bts),
F(DstMem | SrcImmByte | Lock, em_btr),
F(DstMem | SrcImmByte | Lock | PageTable, em_btc),
};
static const struct group_dual group9 = { {
N, I(DstMem64 | Lock | PageTable, em_cmpxchg8b), N, N, N, N, N, N,
}, {
N, N, N, N, N, N, N, N,
} };
static const struct opcode group11[] = {
I(DstMem | SrcImm | Mov | PageTable, em_mov),
X7(D(Undefined)),
};
static const struct gprefix pfx_0f_ae_7 = {
I(SrcMem | ByteOp, em_clflush), N, N, N,
};
static const struct group_dual group15 = { {
N, N, N, N, N, N, N, GP(0, &pfx_0f_ae_7),
}, {
N, N, N, N, N, N, N, N,
} };
static const struct gprefix pfx_0f_6f_0f_7f = {
I(Mmx, em_mov), I(Sse | Aligned, em_mov), N, I(Sse | Unaligned, em_mov),
};
static const struct instr_dual instr_dual_0f_2b = {
I(0, em_mov), N
};
static const struct gprefix pfx_0f_2b = {
ID(0, &instr_dual_0f_2b), ID(0, &instr_dual_0f_2b), N, N,
};
static const struct gprefix pfx_0f_28_0f_29 = {
I(Aligned, em_mov), I(Aligned, em_mov), N, N,
};
static const struct gprefix pfx_0f_e7 = {
N, I(Sse, em_mov), N, N,
};
static const struct escape escape_d9 = { {
N, N, N, N, N, N, N, I(DstMem16 | Mov, em_fnstcw),
}, {
/* 0xC0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xC8 - 0xCF */
N, N, N, N, N, N, N, N,
/* 0xD0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xD8 - 0xDF */
N, N, N, N, N, N, N, N,
/* 0xE0 - 0xE7 */
N, N, N, N, N, N, N, N,
/* 0xE8 - 0xEF */
N, N, N, N, N, N, N, N,
/* 0xF0 - 0xF7 */
N, N, N, N, N, N, N, N,
/* 0xF8 - 0xFF */
N, N, N, N, N, N, N, N,
} };
static const struct escape escape_db = { {
N, N, N, N, N, N, N, N,
}, {
/* 0xC0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xC8 - 0xCF */
N, N, N, N, N, N, N, N,
/* 0xD0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xD8 - 0xDF */
N, N, N, N, N, N, N, N,
/* 0xE0 - 0xE7 */
N, N, N, I(ImplicitOps, em_fninit), N, N, N, N,
/* 0xE8 - 0xEF */
N, N, N, N, N, N, N, N,
/* 0xF0 - 0xF7 */
N, N, N, N, N, N, N, N,
/* 0xF8 - 0xFF */
N, N, N, N, N, N, N, N,
} };
static const struct escape escape_dd = { {
N, N, N, N, N, N, N, I(DstMem16 | Mov, em_fnstsw),
}, {
/* 0xC0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xC8 - 0xCF */
N, N, N, N, N, N, N, N,
/* 0xD0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xD8 - 0xDF */
N, N, N, N, N, N, N, N,
/* 0xE0 - 0xE7 */
N, N, N, N, N, N, N, N,
/* 0xE8 - 0xEF */
N, N, N, N, N, N, N, N,
/* 0xF0 - 0xF7 */
N, N, N, N, N, N, N, N,
/* 0xF8 - 0xFF */
N, N, N, N, N, N, N, N,
} };
static const struct instr_dual instr_dual_0f_c3 = {
I(DstMem | SrcReg | ModRM | No16 | Mov, em_mov), N
};
static const struct mode_dual mode_dual_63 = {
N, I(DstReg | SrcMem32 | ModRM | Mov, em_movsxd)
};
static const struct opcode opcode_table[256] = {
/* 0x00 - 0x07 */
F6ALU(Lock, em_add),
I(ImplicitOps | Stack | No64 | Src2ES, em_push_sreg),
I(ImplicitOps | Stack | No64 | Src2ES, em_pop_sreg),
/* 0x08 - 0x0F */
F6ALU(Lock | PageTable, em_or),
I(ImplicitOps | Stack | No64 | Src2CS, em_push_sreg),
N,
/* 0x10 - 0x17 */
F6ALU(Lock, em_adc),
I(ImplicitOps | Stack | No64 | Src2SS, em_push_sreg),
I(ImplicitOps | Stack | No64 | Src2SS, em_pop_sreg),
/* 0x18 - 0x1F */
F6ALU(Lock, em_sbb),
I(ImplicitOps | Stack | No64 | Src2DS, em_push_sreg),
I(ImplicitOps | Stack | No64 | Src2DS, em_pop_sreg),
/* 0x20 - 0x27 */
F6ALU(Lock | PageTable, em_and), N, N,
/* 0x28 - 0x2F */
F6ALU(Lock, em_sub), N, I(ByteOp | DstAcc | No64, em_das),
/* 0x30 - 0x37 */
F6ALU(Lock, em_xor), N, N,
/* 0x38 - 0x3F */
F6ALU(NoWrite, em_cmp), N, N,
/* 0x40 - 0x4F */
X8(F(DstReg, em_inc)), X8(F(DstReg, em_dec)),
/* 0x50 - 0x57 */
X8(I(SrcReg | Stack, em_push)),
/* 0x58 - 0x5F */
X8(I(DstReg | Stack, em_pop)),
/* 0x60 - 0x67 */
I(ImplicitOps | Stack | No64, em_pusha),
I(ImplicitOps | Stack | No64, em_popa),
N, MD(ModRM, &mode_dual_63),
N, N, N, N,
/* 0x68 - 0x6F */
I(SrcImm | Mov | Stack, em_push),
I(DstReg | SrcMem | ModRM | Src2Imm, em_imul_3op),
I(SrcImmByte | Mov | Stack, em_push),
I(DstReg | SrcMem | ModRM | Src2ImmByte, em_imul_3op),
I2bvIP(DstDI | SrcDX | Mov | String | Unaligned, em_in, ins, check_perm_in), /* insb, insw/insd */
I2bvIP(SrcSI | DstDX | String, em_out, outs, check_perm_out), /* outsb, outsw/outsd */
/* 0x70 - 0x7F */
X16(D(SrcImmByte | NearBranch)),
/* 0x80 - 0x87 */
G(ByteOp | DstMem | SrcImm, group1),
G(DstMem | SrcImm, group1),
G(ByteOp | DstMem | SrcImm | No64, group1),
G(DstMem | SrcImmByte, group1),
F2bv(DstMem | SrcReg | ModRM | NoWrite, em_test),
I2bv(DstMem | SrcReg | ModRM | Lock | PageTable, em_xchg),
/* 0x88 - 0x8F */
I2bv(DstMem | SrcReg | ModRM | Mov | PageTable, em_mov),
I2bv(DstReg | SrcMem | ModRM | Mov, em_mov),
I(DstMem | SrcNone | ModRM | Mov | PageTable, em_mov_rm_sreg),
D(ModRM | SrcMem | NoAccess | DstReg),
I(ImplicitOps | SrcMem16 | ModRM, em_mov_sreg_rm),
G(0, group1A),
/* 0x90 - 0x97 */
DI(SrcAcc | DstReg, pause), X7(D(SrcAcc | DstReg)),
/* 0x98 - 0x9F */
D(DstAcc | SrcNone), I(ImplicitOps | SrcAcc, em_cwd),
I(SrcImmFAddr | No64, em_call_far), N,
II(ImplicitOps | Stack, em_pushf, pushf),
II(ImplicitOps | Stack, em_popf, popf),
I(ImplicitOps, em_sahf), I(ImplicitOps, em_lahf),
/* 0xA0 - 0xA7 */
I2bv(DstAcc | SrcMem | Mov | MemAbs, em_mov),
I2bv(DstMem | SrcAcc | Mov | MemAbs | PageTable, em_mov),
I2bv(SrcSI | DstDI | Mov | String, em_mov),
F2bv(SrcSI | DstDI | String | NoWrite, em_cmp_r),
/* 0xA8 - 0xAF */
F2bv(DstAcc | SrcImm | NoWrite, em_test),
I2bv(SrcAcc | DstDI | Mov | String, em_mov),
I2bv(SrcSI | DstAcc | Mov | String, em_mov),
F2bv(SrcAcc | DstDI | String | NoWrite, em_cmp_r),
/* 0xB0 - 0xB7 */
X8(I(ByteOp | DstReg | SrcImm | Mov, em_mov)),
/* 0xB8 - 0xBF */
X8(I(DstReg | SrcImm64 | Mov, em_mov)),
/* 0xC0 - 0xC7 */
G(ByteOp | Src2ImmByte, group2), G(Src2ImmByte, group2),
I(ImplicitOps | NearBranch | SrcImmU16, em_ret_near_imm),
I(ImplicitOps | NearBranch, em_ret),
I(DstReg | SrcMemFAddr | ModRM | No64 | Src2ES, em_lseg),
I(DstReg | SrcMemFAddr | ModRM | No64 | Src2DS, em_lseg),
G(ByteOp, group11), G(0, group11),
/* 0xC8 - 0xCF */
I(Stack | SrcImmU16 | Src2ImmByte, em_enter), I(Stack, em_leave),
I(ImplicitOps | SrcImmU16, em_ret_far_imm),
I(ImplicitOps, em_ret_far),
D(ImplicitOps), DI(SrcImmByte, intn),
D(ImplicitOps | No64), II(ImplicitOps, em_iret, iret),
/* 0xD0 - 0xD7 */
G(Src2One | ByteOp, group2), G(Src2One, group2),
G(Src2CL | ByteOp, group2), G(Src2CL, group2),
I(DstAcc | SrcImmUByte | No64, em_aam),
I(DstAcc | SrcImmUByte | No64, em_aad),
F(DstAcc | ByteOp | No64, em_salc),
I(DstAcc | SrcXLat | ByteOp, em_mov),
/* 0xD8 - 0xDF */
N, E(0, &escape_d9), N, E(0, &escape_db), N, E(0, &escape_dd), N, N,
/* 0xE0 - 0xE7 */
X3(I(SrcImmByte | NearBranch, em_loop)),
I(SrcImmByte | NearBranch, em_jcxz),
I2bvIP(SrcImmUByte | DstAcc, em_in, in, check_perm_in),
I2bvIP(SrcAcc | DstImmUByte, em_out, out, check_perm_out),
/* 0xE8 - 0xEF */
I(SrcImm | NearBranch, em_call), D(SrcImm | ImplicitOps | NearBranch),
I(SrcImmFAddr | No64, em_jmp_far),
D(SrcImmByte | ImplicitOps | NearBranch),
I2bvIP(SrcDX | DstAcc, em_in, in, check_perm_in),
I2bvIP(SrcAcc | DstDX, em_out, out, check_perm_out),
/* 0xF0 - 0xF7 */
N, DI(ImplicitOps, icebp), N, N,
DI(ImplicitOps | Priv, hlt), D(ImplicitOps),
G(ByteOp, group3), G(0, group3),
/* 0xF8 - 0xFF */
D(ImplicitOps), D(ImplicitOps),
I(ImplicitOps, em_cli), I(ImplicitOps, em_sti),
D(ImplicitOps), D(ImplicitOps), G(0, group4), G(0, group5),
};
static const struct opcode twobyte_table[256] = {
/* 0x00 - 0x0F */
G(0, group6), GD(0, &group7), N, N,
N, I(ImplicitOps | EmulateOnUD, em_syscall),
II(ImplicitOps | Priv, em_clts, clts), N,
DI(ImplicitOps | Priv, invd), DI(ImplicitOps | Priv, wbinvd), N, N,
N, D(ImplicitOps | ModRM | SrcMem | NoAccess), N, N,
/* 0x10 - 0x1F */
N, N, N, N, N, N, N, N,
D(ImplicitOps | ModRM | SrcMem | NoAccess),
N, N, N, N, N, N, D(ImplicitOps | ModRM | SrcMem | NoAccess),
/* 0x20 - 0x2F */
DIP(ModRM | DstMem | Priv | Op3264 | NoMod, cr_read, check_cr_read),
DIP(ModRM | DstMem | Priv | Op3264 | NoMod, dr_read, check_dr_read),
IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_cr_write, cr_write,
check_cr_write),
IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_dr_write, dr_write,
check_dr_write),
N, N, N, N,
GP(ModRM | DstReg | SrcMem | Mov | Sse, &pfx_0f_28_0f_29),
GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_28_0f_29),
N, GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_2b),
N, N, N, N,
/* 0x30 - 0x3F */
II(ImplicitOps | Priv, em_wrmsr, wrmsr),
IIP(ImplicitOps, em_rdtsc, rdtsc, check_rdtsc),
II(ImplicitOps | Priv, em_rdmsr, rdmsr),
IIP(ImplicitOps, em_rdpmc, rdpmc, check_rdpmc),
I(ImplicitOps | EmulateOnUD, em_sysenter),
I(ImplicitOps | Priv | EmulateOnUD, em_sysexit),
N, N,
N, N, N, N, N, N, N, N,
/* 0x40 - 0x4F */
X16(D(DstReg | SrcMem | ModRM)),
/* 0x50 - 0x5F */
N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N,
/* 0x60 - 0x6F */
N, N, N, N,
N, N, N, N,
N, N, N, N,
N, N, N, GP(SrcMem | DstReg | ModRM | Mov, &pfx_0f_6f_0f_7f),
/* 0x70 - 0x7F */
N, N, N, N,
N, N, N, N,
N, N, N, N,
N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_6f_0f_7f),
/* 0x80 - 0x8F */
X16(D(SrcImm | NearBranch)),
/* 0x90 - 0x9F */
X16(D(ByteOp | DstMem | SrcNone | ModRM| Mov)),
/* 0xA0 - 0xA7 */
I(Stack | Src2FS, em_push_sreg), I(Stack | Src2FS, em_pop_sreg),
II(ImplicitOps, em_cpuid, cpuid),
F(DstMem | SrcReg | ModRM | BitOp | NoWrite, em_bt),
F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shld),
F(DstMem | SrcReg | Src2CL | ModRM, em_shld), N, N,
/* 0xA8 - 0xAF */
I(Stack | Src2GS, em_push_sreg), I(Stack | Src2GS, em_pop_sreg),
II(EmulateOnUD | ImplicitOps, em_rsm, rsm),
F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_bts),
F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shrd),
F(DstMem | SrcReg | Src2CL | ModRM, em_shrd),
GD(0, &group15), F(DstReg | SrcMem | ModRM, em_imul),
/* 0xB0 - 0xB7 */
I2bv(DstMem | SrcReg | ModRM | Lock | PageTable | SrcWrite, em_cmpxchg),
I(DstReg | SrcMemFAddr | ModRM | Src2SS, em_lseg),
F(DstMem | SrcReg | ModRM | BitOp | Lock, em_btr),
I(DstReg | SrcMemFAddr | ModRM | Src2FS, em_lseg),
I(DstReg | SrcMemFAddr | ModRM | Src2GS, em_lseg),
D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov),
/* 0xB8 - 0xBF */
N, N,
G(BitOp, group8),
F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_btc),
I(DstReg | SrcMem | ModRM, em_bsf_c),
I(DstReg | SrcMem | ModRM, em_bsr_c),
D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov),
/* 0xC0 - 0xC7 */
F2bv(DstMem | SrcReg | ModRM | SrcWrite | Lock, em_xadd),
N, ID(0, &instr_dual_0f_c3),
N, N, N, GD(0, &group9),
/* 0xC8 - 0xCF */
X8(I(DstReg, em_bswap)),
/* 0xD0 - 0xDF */
N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N,
/* 0xE0 - 0xEF */
N, N, N, N, N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_e7),
N, N, N, N, N, N, N, N,
/* 0xF0 - 0xFF */
N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N
};
static const struct instr_dual instr_dual_0f_38_f0 = {
I(DstReg | SrcMem | Mov, em_movbe), N
};
static const struct instr_dual instr_dual_0f_38_f1 = {
I(DstMem | SrcReg | Mov, em_movbe), N
};
static const struct gprefix three_byte_0f_38_f0 = {
ID(0, &instr_dual_0f_38_f0), N, N, N
};
static const struct gprefix three_byte_0f_38_f1 = {
ID(0, &instr_dual_0f_38_f1), N, N, N
};
/*
* Insns below are selected by the prefix which indexed by the third opcode
* byte.
*/
static const struct opcode opcode_map_0f_38[256] = {
/* 0x00 - 0x7f */
X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N),
/* 0x80 - 0xef */
X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N),
/* 0xf0 - 0xf1 */
GP(EmulateOnUD | ModRM, &three_byte_0f_38_f0),
GP(EmulateOnUD | ModRM, &three_byte_0f_38_f1),
/* 0xf2 - 0xff */
N, N, X4(N), X8(N)
};
#undef D
#undef N
#undef G
#undef GD
#undef I
#undef GP
#undef EXT
#undef MD
#undef ID
#undef D2bv
#undef D2bvIP
#undef I2bv
#undef I2bvIP
#undef I6ALU
static unsigned imm_size(struct x86_emulate_ctxt *ctxt)
{
unsigned size;
size = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
if (size == 8)
size = 4;
return size;
}
static int decode_imm(struct x86_emulate_ctxt *ctxt, struct operand *op,
unsigned size, bool sign_extension)
{
int rc = X86EMUL_CONTINUE;
op->type = OP_IMM;
op->bytes = size;
op->addr.mem.ea = ctxt->_eip;
/* NB. Immediates are sign-extended as necessary. */
switch (op->bytes) {
case 1:
op->val = insn_fetch(s8, ctxt);
break;
case 2:
op->val = insn_fetch(s16, ctxt);
break;
case 4:
op->val = insn_fetch(s32, ctxt);
break;
case 8:
op->val = insn_fetch(s64, ctxt);
break;
}
if (!sign_extension) {
switch (op->bytes) {
case 1:
op->val &= 0xff;
break;
case 2:
op->val &= 0xffff;
break;
case 4:
op->val &= 0xffffffff;
break;
}
}
done:
return rc;
}
static int decode_operand(struct x86_emulate_ctxt *ctxt, struct operand *op,
unsigned d)
{
int rc = X86EMUL_CONTINUE;
switch (d) {
case OpReg:
decode_register_operand(ctxt, op);
break;
case OpImmUByte:
rc = decode_imm(ctxt, op, 1, false);
break;
case OpMem:
ctxt->memop.bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
mem_common:
*op = ctxt->memop;
ctxt->memopp = op;
if (ctxt->d & BitOp)
fetch_bit_operand(ctxt);
op->orig_val = op->val;
break;
case OpMem64:
ctxt->memop.bytes = (ctxt->op_bytes == 8) ? 16 : 8;
goto mem_common;
case OpAcc:
op->type = OP_REG;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
fetch_register_operand(op);
op->orig_val = op->val;
break;
case OpAccLo:
op->type = OP_REG;
op->bytes = (ctxt->d & ByteOp) ? 2 : ctxt->op_bytes;
op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
fetch_register_operand(op);
op->orig_val = op->val;
break;
case OpAccHi:
if (ctxt->d & ByteOp) {
op->type = OP_NONE;
break;
}
op->type = OP_REG;
op->bytes = ctxt->op_bytes;
op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
fetch_register_operand(op);
op->orig_val = op->val;
break;
case OpDI:
op->type = OP_MEM;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.mem.ea =
register_address(ctxt, VCPU_REGS_RDI);
op->addr.mem.seg = VCPU_SREG_ES;
op->val = 0;
op->count = 1;
break;
case OpDX:
op->type = OP_REG;
op->bytes = 2;
op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
fetch_register_operand(op);
break;
case OpCL:
op->type = OP_IMM;
op->bytes = 1;
op->val = reg_read(ctxt, VCPU_REGS_RCX) & 0xff;
break;
case OpImmByte:
rc = decode_imm(ctxt, op, 1, true);
break;
case OpOne:
op->type = OP_IMM;
op->bytes = 1;
op->val = 1;
break;
case OpImm:
rc = decode_imm(ctxt, op, imm_size(ctxt), true);
break;
case OpImm64:
rc = decode_imm(ctxt, op, ctxt->op_bytes, true);
break;
case OpMem8:
ctxt->memop.bytes = 1;
if (ctxt->memop.type == OP_REG) {
ctxt->memop.addr.reg = decode_register(ctxt,
ctxt->modrm_rm, true);
fetch_register_operand(&ctxt->memop);
}
goto mem_common;
case OpMem16:
ctxt->memop.bytes = 2;
goto mem_common;
case OpMem32:
ctxt->memop.bytes = 4;
goto mem_common;
case OpImmU16:
rc = decode_imm(ctxt, op, 2, false);
break;
case OpImmU:
rc = decode_imm(ctxt, op, imm_size(ctxt), false);
break;
case OpSI:
op->type = OP_MEM;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.mem.ea =
register_address(ctxt, VCPU_REGS_RSI);
op->addr.mem.seg = ctxt->seg_override;
op->val = 0;
op->count = 1;
break;
case OpXLat:
op->type = OP_MEM;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.mem.ea =
address_mask(ctxt,
reg_read(ctxt, VCPU_REGS_RBX) +
(reg_read(ctxt, VCPU_REGS_RAX) & 0xff));
op->addr.mem.seg = ctxt->seg_override;
op->val = 0;
break;
case OpImmFAddr:
op->type = OP_IMM;
op->addr.mem.ea = ctxt->_eip;
op->bytes = ctxt->op_bytes + 2;
insn_fetch_arr(op->valptr, op->bytes, ctxt);
break;
case OpMemFAddr:
ctxt->memop.bytes = ctxt->op_bytes + 2;
goto mem_common;
case OpES:
op->type = OP_IMM;
op->val = VCPU_SREG_ES;
break;
case OpCS:
op->type = OP_IMM;
op->val = VCPU_SREG_CS;
break;
case OpSS:
op->type = OP_IMM;
op->val = VCPU_SREG_SS;
break;
case OpDS:
op->type = OP_IMM;
op->val = VCPU_SREG_DS;
break;
case OpFS:
op->type = OP_IMM;
op->val = VCPU_SREG_FS;
break;
case OpGS:
op->type = OP_IMM;
op->val = VCPU_SREG_GS;
break;
case OpImplicit:
/* Special instructions do their own operand decoding. */
default:
op->type = OP_NONE; /* Disable writeback. */
break;
}
done:
return rc;
}
int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len)
{
int rc = X86EMUL_CONTINUE;
int mode = ctxt->mode;
int def_op_bytes, def_ad_bytes, goffset, simd_prefix;
bool op_prefix = false;
bool has_seg_override = false;
struct opcode opcode;
ctxt->memop.type = OP_NONE;
ctxt->memopp = NULL;
ctxt->_eip = ctxt->eip;
ctxt->fetch.ptr = ctxt->fetch.data;
ctxt->fetch.end = ctxt->fetch.data + insn_len;
ctxt->opcode_len = 1;
if (insn_len > 0)
memcpy(ctxt->fetch.data, insn, insn_len);
else {
rc = __do_insn_fetch_bytes(ctxt, 1);
if (rc != X86EMUL_CONTINUE)
return rc;
}
switch (mode) {
case X86EMUL_MODE_REAL:
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
def_op_bytes = def_ad_bytes = 2;
break;
case X86EMUL_MODE_PROT32:
def_op_bytes = def_ad_bytes = 4;
break;
#ifdef CONFIG_X86_64
case X86EMUL_MODE_PROT64:
def_op_bytes = 4;
def_ad_bytes = 8;
break;
#endif
default:
return EMULATION_FAILED;
}
ctxt->op_bytes = def_op_bytes;
ctxt->ad_bytes = def_ad_bytes;
/* Legacy prefixes. */
for (;;) {
switch (ctxt->b = insn_fetch(u8, ctxt)) {
case 0x66: /* operand-size override */
op_prefix = true;
/* switch between 2/4 bytes */
ctxt->op_bytes = def_op_bytes ^ 6;
break;
case 0x67: /* address-size override */
if (mode == X86EMUL_MODE_PROT64)
/* switch between 4/8 bytes */
ctxt->ad_bytes = def_ad_bytes ^ 12;
else
/* switch between 2/4 bytes */
ctxt->ad_bytes = def_ad_bytes ^ 6;
break;
case 0x26: /* ES override */
case 0x2e: /* CS override */
case 0x36: /* SS override */
case 0x3e: /* DS override */
has_seg_override = true;
ctxt->seg_override = (ctxt->b >> 3) & 3;
break;
case 0x64: /* FS override */
case 0x65: /* GS override */
has_seg_override = true;
ctxt->seg_override = ctxt->b & 7;
break;
case 0x40 ... 0x4f: /* REX */
if (mode != X86EMUL_MODE_PROT64)
goto done_prefixes;
ctxt->rex_prefix = ctxt->b;
continue;
case 0xf0: /* LOCK */
ctxt->lock_prefix = 1;
break;
case 0xf2: /* REPNE/REPNZ */
case 0xf3: /* REP/REPE/REPZ */
ctxt->rep_prefix = ctxt->b;
break;
default:
goto done_prefixes;
}
/* Any legacy prefix after a REX prefix nullifies its effect. */
ctxt->rex_prefix = 0;
}
done_prefixes:
/* REX prefix. */
if (ctxt->rex_prefix & 8)
ctxt->op_bytes = 8; /* REX.W */
/* Opcode byte(s). */
opcode = opcode_table[ctxt->b];
/* Two-byte opcode? */
if (ctxt->b == 0x0f) {
ctxt->opcode_len = 2;
ctxt->b = insn_fetch(u8, ctxt);
opcode = twobyte_table[ctxt->b];
/* 0F_38 opcode map */
if (ctxt->b == 0x38) {
ctxt->opcode_len = 3;
ctxt->b = insn_fetch(u8, ctxt);
opcode = opcode_map_0f_38[ctxt->b];
}
}
ctxt->d = opcode.flags;
if (ctxt->d & ModRM)
ctxt->modrm = insn_fetch(u8, ctxt);
/* vex-prefix instructions are not implemented */
if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) &&
(mode == X86EMUL_MODE_PROT64 || (ctxt->modrm & 0xc0) == 0xc0)) {
ctxt->d = NotImpl;
}
while (ctxt->d & GroupMask) {
switch (ctxt->d & GroupMask) {
case Group:
goffset = (ctxt->modrm >> 3) & 7;
opcode = opcode.u.group[goffset];
break;
case GroupDual:
goffset = (ctxt->modrm >> 3) & 7;
if ((ctxt->modrm >> 6) == 3)
opcode = opcode.u.gdual->mod3[goffset];
else
opcode = opcode.u.gdual->mod012[goffset];
break;
case RMExt:
goffset = ctxt->modrm & 7;
opcode = opcode.u.group[goffset];
break;
case Prefix:
if (ctxt->rep_prefix && op_prefix)
return EMULATION_FAILED;
simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix;
switch (simd_prefix) {
case 0x00: opcode = opcode.u.gprefix->pfx_no; break;
case 0x66: opcode = opcode.u.gprefix->pfx_66; break;
case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break;
case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break;
}
break;
case Escape:
if (ctxt->modrm > 0xbf)
opcode = opcode.u.esc->high[ctxt->modrm - 0xc0];
else
opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7];
break;
case InstrDual:
if ((ctxt->modrm >> 6) == 3)
opcode = opcode.u.idual->mod3;
else
opcode = opcode.u.idual->mod012;
break;
case ModeDual:
if (ctxt->mode == X86EMUL_MODE_PROT64)
opcode = opcode.u.mdual->mode64;
else
opcode = opcode.u.mdual->mode32;
break;
default:
return EMULATION_FAILED;
}
ctxt->d &= ~(u64)GroupMask;
ctxt->d |= opcode.flags;
}
/* Unrecognised? */
if (ctxt->d == 0)
return EMULATION_FAILED;
ctxt->execute = opcode.u.execute;
if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD)))
return EMULATION_FAILED;
if (unlikely(ctxt->d &
(NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm|NearBranch|
No16))) {
/*
* These are copied unconditionally here, and checked unconditionally
* in x86_emulate_insn.
*/
ctxt->check_perm = opcode.check_perm;
ctxt->intercept = opcode.intercept;
if (ctxt->d & NotImpl)
return EMULATION_FAILED;
if (mode == X86EMUL_MODE_PROT64) {
if (ctxt->op_bytes == 4 && (ctxt->d & Stack))
ctxt->op_bytes = 8;
else if (ctxt->d & NearBranch)
ctxt->op_bytes = 8;
}
if (ctxt->d & Op3264) {
if (mode == X86EMUL_MODE_PROT64)
ctxt->op_bytes = 8;
else
ctxt->op_bytes = 4;
}
if ((ctxt->d & No16) && ctxt->op_bytes == 2)
ctxt->op_bytes = 4;
if (ctxt->d & Sse)
ctxt->op_bytes = 16;
else if (ctxt->d & Mmx)
ctxt->op_bytes = 8;
}
/* ModRM and SIB bytes. */
if (ctxt->d & ModRM) {
rc = decode_modrm(ctxt, &ctxt->memop);
if (!has_seg_override) {
has_seg_override = true;
ctxt->seg_override = ctxt->modrm_seg;
}
} else if (ctxt->d & MemAbs)
rc = decode_abs(ctxt, &ctxt->memop);
if (rc != X86EMUL_CONTINUE)
goto done;
if (!has_seg_override)
ctxt->seg_override = VCPU_SREG_DS;
ctxt->memop.addr.mem.seg = ctxt->seg_override;
/*
* Decode and fetch the source operand: register, memory
* or immediate.
*/
rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask);
if (rc != X86EMUL_CONTINUE)
goto done;
/*
* Decode and fetch the second source operand: register, memory
* or immediate.
*/
rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask);
if (rc != X86EMUL_CONTINUE)
goto done;
/* Decode and fetch the destination operand: register or memory. */
rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask);
if (ctxt->rip_relative && likely(ctxt->memopp))
ctxt->memopp->addr.mem.ea = address_mask(ctxt,
ctxt->memopp->addr.mem.ea + ctxt->_eip);
done:
return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK;
}
bool x86_page_table_writing_insn(struct x86_emulate_ctxt *ctxt)
{
return ctxt->d & PageTable;
}
static bool string_insn_completed(struct x86_emulate_ctxt *ctxt)
{
/* The second termination condition only applies for REPE
* and REPNE. Test if the repeat string operation prefix is
* REPE/REPZ or REPNE/REPNZ and if it's the case it tests the
* corresponding termination condition according to:
* - if REPE/REPZ and ZF = 0 then done
* - if REPNE/REPNZ and ZF = 1 then done
*/
if (((ctxt->b == 0xa6) || (ctxt->b == 0xa7) ||
(ctxt->b == 0xae) || (ctxt->b == 0xaf))
&& (((ctxt->rep_prefix == REPE_PREFIX) &&
((ctxt->eflags & X86_EFLAGS_ZF) == 0))
|| ((ctxt->rep_prefix == REPNE_PREFIX) &&
((ctxt->eflags & X86_EFLAGS_ZF) == X86_EFLAGS_ZF))))
return true;
return false;
}
static int flush_pending_x87_faults(struct x86_emulate_ctxt *ctxt)
{
bool fault = false;
ctxt->ops->get_fpu(ctxt);
asm volatile("1: fwait \n\t"
"2: \n\t"
".pushsection .fixup,\"ax\" \n\t"
"3: \n\t"
"movb $1, %[fault] \n\t"
"jmp 2b \n\t"
".popsection \n\t"
_ASM_EXTABLE(1b, 3b)
: [fault]"+qm"(fault));
ctxt->ops->put_fpu(ctxt);
if (unlikely(fault))
return emulate_exception(ctxt, MF_VECTOR, 0, false);
return X86EMUL_CONTINUE;
}
static void fetch_possible_mmx_operand(struct x86_emulate_ctxt *ctxt,
struct operand *op)
{
if (op->type == OP_MM)
read_mmx_reg(ctxt, &op->mm_val, op->addr.mm);
}
static int fastop(struct x86_emulate_ctxt *ctxt, void (*fop)(struct fastop *))
{
register void *__sp asm(_ASM_SP);
ulong flags = (ctxt->eflags & EFLAGS_MASK) | X86_EFLAGS_IF;
if (!(ctxt->d & ByteOp))
fop += __ffs(ctxt->dst.bytes) * FASTOP_SIZE;
asm("push %[flags]; popf; call *%[fastop]; pushf; pop %[flags]\n"
: "+a"(ctxt->dst.val), "+d"(ctxt->src.val), [flags]"+D"(flags),
[fastop]"+S"(fop), "+r"(__sp)
: "c"(ctxt->src2.val));
ctxt->eflags = (ctxt->eflags & ~EFLAGS_MASK) | (flags & EFLAGS_MASK);
if (!fop) /* exception is returned in fop variable */
return emulate_de(ctxt);
return X86EMUL_CONTINUE;
}
void init_decode_cache(struct x86_emulate_ctxt *ctxt)
{
memset(&ctxt->rip_relative, 0,
(void *)&ctxt->modrm - (void *)&ctxt->rip_relative);
ctxt->io_read.pos = 0;
ctxt->io_read.end = 0;
ctxt->mem_read.end = 0;
}
int x86_emulate_insn(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
int rc = X86EMUL_CONTINUE;
int saved_dst_type = ctxt->dst.type;
ctxt->mem_read.pos = 0;
/* LOCK prefix is allowed only with some instructions */
if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) {
rc = emulate_ud(ctxt);
goto done;
}
if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) {
rc = emulate_ud(ctxt);
goto done;
}
if (unlikely(ctxt->d &
(No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) {
if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) ||
(ctxt->d & Undefined)) {
rc = emulate_ud(ctxt);
goto done;
}
if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM)))
|| ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) {
rc = emulate_ud(ctxt);
goto done;
}
if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) {
rc = emulate_nm(ctxt);
goto done;
}
if (ctxt->d & Mmx) {
rc = flush_pending_x87_faults(ctxt);
if (rc != X86EMUL_CONTINUE)
goto done;
/*
* Now that we know the fpu is exception safe, we can fetch
* operands from it.
*/
fetch_possible_mmx_operand(ctxt, &ctxt->src);
fetch_possible_mmx_operand(ctxt, &ctxt->src2);
if (!(ctxt->d & Mov))
fetch_possible_mmx_operand(ctxt, &ctxt->dst);
}
if (unlikely(ctxt->emul_flags & X86EMUL_GUEST_MASK) && ctxt->intercept) {
rc = emulator_check_intercept(ctxt, ctxt->intercept,
X86_ICPT_PRE_EXCEPT);
if (rc != X86EMUL_CONTINUE)
goto done;
}
/* Instruction can only be executed in protected mode */
if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) {
rc = emulate_ud(ctxt);
goto done;
}
/* Privileged instruction can be executed only in CPL=0 */
if ((ctxt->d & Priv) && ops->cpl(ctxt)) {
if (ctxt->d & PrivUD)
rc = emulate_ud(ctxt);
else
rc = emulate_gp(ctxt, 0);
goto done;
}
/* Do instruction specific permission checks */
if (ctxt->d & CheckPerm) {
rc = ctxt->check_perm(ctxt);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if (unlikely(ctxt->emul_flags & X86EMUL_GUEST_MASK) && (ctxt->d & Intercept)) {
rc = emulator_check_intercept(ctxt, ctxt->intercept,
X86_ICPT_POST_EXCEPT);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if (ctxt->rep_prefix && (ctxt->d & String)) {
/* All REP prefixes have the same first termination condition */
if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) {
string_registers_quirk(ctxt);
ctxt->eip = ctxt->_eip;
ctxt->eflags &= ~X86_EFLAGS_RF;
goto done;
}
}
}
if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) {
rc = segmented_read(ctxt, ctxt->src.addr.mem,
ctxt->src.valptr, ctxt->src.bytes);
if (rc != X86EMUL_CONTINUE)
goto done;
ctxt->src.orig_val64 = ctxt->src.val64;
}
if (ctxt->src2.type == OP_MEM) {
rc = segmented_read(ctxt, ctxt->src2.addr.mem,
&ctxt->src2.val, ctxt->src2.bytes);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if ((ctxt->d & DstMask) == ImplicitOps)
goto special_insn;
if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) {
/* optimisation - avoid slow emulated read if Mov */
rc = segmented_read(ctxt, ctxt->dst.addr.mem,
&ctxt->dst.val, ctxt->dst.bytes);
if (rc != X86EMUL_CONTINUE) {
if (!(ctxt->d & NoWrite) &&
rc == X86EMUL_PROPAGATE_FAULT &&
ctxt->exception.vector == PF_VECTOR)
ctxt->exception.error_code |= PFERR_WRITE_MASK;
goto done;
}
}
/* Copy full 64-bit value for CMPXCHG8B. */
ctxt->dst.orig_val64 = ctxt->dst.val64;
special_insn:
if (unlikely(ctxt->emul_flags & X86EMUL_GUEST_MASK) && (ctxt->d & Intercept)) {
rc = emulator_check_intercept(ctxt, ctxt->intercept,
X86_ICPT_POST_MEMACCESS);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if (ctxt->rep_prefix && (ctxt->d & String))
ctxt->eflags |= X86_EFLAGS_RF;
else
ctxt->eflags &= ~X86_EFLAGS_RF;
if (ctxt->execute) {
if (ctxt->d & Fastop) {
void (*fop)(struct fastop *) = (void *)ctxt->execute;
rc = fastop(ctxt, fop);
if (rc != X86EMUL_CONTINUE)
goto done;
goto writeback;
}
rc = ctxt->execute(ctxt);
if (rc != X86EMUL_CONTINUE)
goto done;
goto writeback;
}
if (ctxt->opcode_len == 2)
goto twobyte_insn;
else if (ctxt->opcode_len == 3)
goto threebyte_insn;
switch (ctxt->b) {
case 0x70 ... 0x7f: /* jcc (short) */
if (test_cc(ctxt->b, ctxt->eflags))
rc = jmp_rel(ctxt, ctxt->src.val);
break;
case 0x8d: /* lea r16/r32, m */
ctxt->dst.val = ctxt->src.addr.mem.ea;
break;
case 0x90 ... 0x97: /* nop / xchg reg, rax */
if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX))
ctxt->dst.type = OP_NONE;
else
rc = em_xchg(ctxt);
break;
case 0x98: /* cbw/cwde/cdqe */
switch (ctxt->op_bytes) {
case 2: ctxt->dst.val = (s8)ctxt->dst.val; break;
case 4: ctxt->dst.val = (s16)ctxt->dst.val; break;
case 8: ctxt->dst.val = (s32)ctxt->dst.val; break;
}
break;
case 0xcc: /* int3 */
rc = emulate_int(ctxt, 3);
break;
case 0xcd: /* int n */
rc = emulate_int(ctxt, ctxt->src.val);
break;
case 0xce: /* into */
if (ctxt->eflags & X86_EFLAGS_OF)
rc = emulate_int(ctxt, 4);
break;
case 0xe9: /* jmp rel */
case 0xeb: /* jmp rel short */
rc = jmp_rel(ctxt, ctxt->src.val);
ctxt->dst.type = OP_NONE; /* Disable writeback. */
break;
case 0xf4: /* hlt */
ctxt->ops->halt(ctxt);
break;
case 0xf5: /* cmc */
/* complement carry flag from eflags reg */
ctxt->eflags ^= X86_EFLAGS_CF;
break;
case 0xf8: /* clc */
ctxt->eflags &= ~X86_EFLAGS_CF;
break;
case 0xf9: /* stc */
ctxt->eflags |= X86_EFLAGS_CF;
break;
case 0xfc: /* cld */
ctxt->eflags &= ~X86_EFLAGS_DF;
break;
case 0xfd: /* std */
ctxt->eflags |= X86_EFLAGS_DF;
break;
default:
goto cannot_emulate;
}
if (rc != X86EMUL_CONTINUE)
goto done;
writeback:
if (ctxt->d & SrcWrite) {
BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR);
rc = writeback(ctxt, &ctxt->src);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if (!(ctxt->d & NoWrite)) {
rc = writeback(ctxt, &ctxt->dst);
if (rc != X86EMUL_CONTINUE)
goto done;
}
/*
* restore dst type in case the decoding will be reused
* (happens for string instruction )
*/
ctxt->dst.type = saved_dst_type;
if ((ctxt->d & SrcMask) == SrcSI)
string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src);
if ((ctxt->d & DstMask) == DstDI)
string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst);
if (ctxt->rep_prefix && (ctxt->d & String)) {
unsigned int count;
struct read_cache *r = &ctxt->io_read;
if ((ctxt->d & SrcMask) == SrcSI)
count = ctxt->src.count;
else
count = ctxt->dst.count;
register_address_increment(ctxt, VCPU_REGS_RCX, -count);
if (!string_insn_completed(ctxt)) {
/*
* Re-enter guest when pio read ahead buffer is empty
* or, if it is not used, after each 1024 iteration.
*/
if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) &&
(r->end == 0 || r->end != r->pos)) {
/*
* Reset read cache. Usually happens before
* decode, but since instruction is restarted
* we have to do it here.
*/
ctxt->mem_read.end = 0;
writeback_registers(ctxt);
return EMULATION_RESTART;
}
goto done; /* skip rip writeback */
}
ctxt->eflags &= ~X86_EFLAGS_RF;
}
ctxt->eip = ctxt->_eip;
done:
if (rc == X86EMUL_PROPAGATE_FAULT) {
WARN_ON(ctxt->exception.vector > 0x1f);
ctxt->have_exception = true;
}
if (rc == X86EMUL_INTERCEPTED)
return EMULATION_INTERCEPTED;
if (rc == X86EMUL_CONTINUE)
writeback_registers(ctxt);
return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK;
twobyte_insn:
switch (ctxt->b) {
case 0x09: /* wbinvd */
(ctxt->ops->wbinvd)(ctxt);
break;
case 0x08: /* invd */
case 0x0d: /* GrpP (prefetch) */
case 0x18: /* Grp16 (prefetch/nop) */
case 0x1f: /* nop */
break;
case 0x20: /* mov cr, reg */
ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg);
break;
case 0x21: /* mov from dr to reg */
ops->get_dr(ctxt, ctxt->modrm_reg, &ctxt->dst.val);
break;
case 0x40 ... 0x4f: /* cmov */
if (test_cc(ctxt->b, ctxt->eflags))
ctxt->dst.val = ctxt->src.val;
else if (ctxt->op_bytes != 4)
ctxt->dst.type = OP_NONE; /* no writeback */
break;
case 0x80 ... 0x8f: /* jnz rel, etc*/
if (test_cc(ctxt->b, ctxt->eflags))
rc = jmp_rel(ctxt, ctxt->src.val);
break;
case 0x90 ... 0x9f: /* setcc r/m8 */
ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags);
break;
case 0xb6 ... 0xb7: /* movzx */
ctxt->dst.bytes = ctxt->op_bytes;
ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val
: (u16) ctxt->src.val;
break;
case 0xbe ... 0xbf: /* movsx */
ctxt->dst.bytes = ctxt->op_bytes;
ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val :
(s16) ctxt->src.val;
break;
default:
goto cannot_emulate;
}
threebyte_insn:
if (rc != X86EMUL_CONTINUE)
goto done;
goto writeback;
cannot_emulate:
return EMULATION_FAILED;
}
void emulator_invalidate_register_cache(struct x86_emulate_ctxt *ctxt)
{
invalidate_registers(ctxt);
}
void emulator_writeback_register_cache(struct x86_emulate_ctxt *ctxt)
{
writeback_registers(ctxt);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5345_0 |
crossvul-cpp_data_good_5485_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP RRRR OOO PPPP EEEEE RRRR TTTTT Y Y %
% P P R R O O P P E R R T Y Y %
% PPPP RRRR O O PPPP EEE RRRR T Y %
% P R R O O P E R R T Y %
% P R R OOO P EEEEE R R T Y %
% %
% %
% MagickCore Property Methods %
% %
% Software Design %
% Cristy %
% March 2000 %
% %
% %
% 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 "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/compare.h"
#include "MagickCore/constitute.h"
#include "MagickCore/draw.h"
#include "MagickCore/effect.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/fx-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image.h"
#include "MagickCore/layer.h"
#include "MagickCore/locale-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/montage.h"
#include "MagickCore/option.h"
#include "MagickCore/policy.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/signature.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/token.h"
#include "MagickCore/token-private.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/version.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
#if defined(MAGICKCORE_LCMS_DELEGATE)
#if defined(MAGICKCORE_HAVE_LCMS2_LCMS2_H)
#include <lcms2/lcms2.h>
#elif defined(MAGICKCORE_HAVE_LCMS2_H)
#include "lcms2.h"
#elif defined(MAGICKCORE_HAVE_LCMS_LCMS_H)
#include <lcms/lcms.h>
#else
#include "lcms.h"
#endif
#endif
/*
Define declarations.
*/
#if defined(MAGICKCORE_LCMS_DELEGATE)
#if defined(LCMS_VERSION) && (LCMS_VERSION < 2000)
#define cmsUInt32Number DWORD
#endif
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e P r o p e r t i e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageProperties() clones all the image properties to another image.
%
% The format of the CloneImageProperties method is:
%
% MagickBooleanType CloneImageProperties(Image *image,
% const Image *clone_image)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o clone_image: the clone image.
%
*/
MagickExport MagickBooleanType CloneImageProperties(Image *image,
const Image *clone_image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(clone_image != (const Image *) NULL);
assert(clone_image->signature == MagickCoreSignature);
if (clone_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
clone_image->filename);
(void) CopyMagickString(image->filename,clone_image->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,clone_image->magick_filename,
MagickPathExtent);
image->compression=clone_image->compression;
image->quality=clone_image->quality;
image->depth=clone_image->depth;
image->alpha_color=clone_image->alpha_color;
image->background_color=clone_image->background_color;
image->border_color=clone_image->border_color;
image->transparent_color=clone_image->transparent_color;
image->gamma=clone_image->gamma;
image->chromaticity=clone_image->chromaticity;
image->rendering_intent=clone_image->rendering_intent;
image->black_point_compensation=clone_image->black_point_compensation;
image->units=clone_image->units;
image->montage=(char *) NULL;
image->directory=(char *) NULL;
(void) CloneString(&image->geometry,clone_image->geometry);
image->offset=clone_image->offset;
image->resolution.x=clone_image->resolution.x;
image->resolution.y=clone_image->resolution.y;
image->page=clone_image->page;
image->tile_offset=clone_image->tile_offset;
image->extract_info=clone_image->extract_info;
image->filter=clone_image->filter;
image->fuzz=clone_image->fuzz;
image->intensity=clone_image->intensity;
image->interlace=clone_image->interlace;
image->interpolate=clone_image->interpolate;
image->endian=clone_image->endian;
image->gravity=clone_image->gravity;
image->compose=clone_image->compose;
image->orientation=clone_image->orientation;
image->scene=clone_image->scene;
image->dispose=clone_image->dispose;
image->delay=clone_image->delay;
image->ticks_per_second=clone_image->ticks_per_second;
image->iterations=clone_image->iterations;
image->total_colors=clone_image->total_colors;
image->taint=clone_image->taint;
image->progress_monitor=clone_image->progress_monitor;
image->client_data=clone_image->client_data;
image->start_loop=clone_image->start_loop;
image->error=clone_image->error;
image->signature=clone_image->signature;
if (clone_image->properties != (void *) NULL)
{
if (image->properties != (void *) NULL)
DestroyImageProperties(image);
image->properties=CloneSplayTree((SplayTreeInfo *)
clone_image->properties,(void *(*)(void *)) ConstantString,
(void *(*)(void *)) ConstantString);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e f i n e I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefineImageProperty() associates an assignment string of the form
% "key=value" with an artifact or options. It is equivelent to
% SetImageProperty().
%
% The format of the DefineImageProperty method is:
%
% MagickBooleanType DefineImageProperty(Image *image,const char *property,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o property: the image property.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DefineImageProperty(Image *image,
const char *property,ExceptionInfo *exception)
{
char
key[MagickPathExtent],
value[MagickPathExtent];
register char
*p;
assert(image != (Image *) NULL);
assert(property != (const char *) NULL);
(void) CopyMagickString(key,property,MagickPathExtent-1);
for (p=key; *p != '\0'; p++)
if (*p == '=')
break;
*value='\0';
if (*p == '=')
(void) CopyMagickString(value,p+1,MagickPathExtent);
*p='\0';
return(SetImageProperty(image,key,value,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e l e t e I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DeleteImageProperty() deletes an image property.
%
% The format of the DeleteImageProperty method is:
%
% MagickBooleanType DeleteImageProperty(Image *image,const char *property)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o property: the image property.
%
*/
MagickExport MagickBooleanType DeleteImageProperty(Image *image,
const char *property)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties == (void *) NULL)
return(MagickFalse);
return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->properties,property));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e P r o p e r t i e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageProperties() destroys all properties and associated memory
% attached to the given image.
%
% The format of the DestroyDefines method is:
%
% void DestroyImageProperties(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DestroyImageProperties(Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties != (void *) NULL)
image->properties=(void *) DestroySplayTree((SplayTreeInfo *)
image->properties);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r m a t I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FormatImageProperty() permits formatted property/value pairs to be saved as
% an image property.
%
% The format of the FormatImageProperty method is:
%
% MagickBooleanType FormatImageProperty(Image *image,const char *property,
% const char *format,...)
%
% A description of each parameter follows.
%
% o image: The image.
%
% o property: The attribute property.
%
% o format: A string describing the format to use to write the remaining
% arguments.
%
*/
MagickExport MagickBooleanType FormatImageProperty(Image *image,
const char *property,const char *format,...)
{
char
value[MagickPathExtent];
ExceptionInfo
*exception;
MagickBooleanType
status;
ssize_t
n;
va_list
operands;
va_start(operands,format);
n=FormatLocaleStringList(value,MagickPathExtent,format,operands);
(void) n;
va_end(operands);
exception=AcquireExceptionInfo();
status=SetImageProperty(image,property,value,exception);
exception=DestroyExceptionInfo(exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageProperty() gets a value associated with an image property.
%
% This includes, profile prefixes, such as "exif:", "iptc:" and "8bim:"
% It does not handle non-prifile prefixes, such as "fx:", "option:", or
% "artifact:".
%
% The returned string is stored as a properity of the same name for faster
% lookup later. It should NOT be freed by the caller.
%
% The format of the GetImageProperty method is:
%
% const char *GetImageProperty(const Image *image,const char *key,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o key: the key.
%
% o exception: return any errors or warnings in this structure.
%
*/
static char
*TracePSClippath(const unsigned char *,size_t),
*TraceSVGClippath(const unsigned char *,size_t,const size_t,
const size_t);
static MagickBooleanType GetIPTCProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
*message;
const StringInfo
*profile;
long
count,
dataset,
record;
register ssize_t
i;
size_t
length;
profile=GetImageProfile(image,"iptc");
if (profile == (StringInfo *) NULL)
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=sscanf(key,"IPTC:%ld:%ld",&dataset,&record);
if (count != 2)
return(MagickFalse);
attribute=(char *) NULL;
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=(ssize_t) length)
{
length=1;
if ((ssize_t) GetStringInfoDatum(profile)[i] != 0x1c)
continue;
length=(size_t) (GetStringInfoDatum(profile)[i+3] << 8);
length|=GetStringInfoDatum(profile)[i+4];
if (((long) GetStringInfoDatum(profile)[i+1] == dataset) &&
((long) GetStringInfoDatum(profile)[i+2] == record))
{
message=(char *) NULL;
if (~length >= 1)
message=(char *) AcquireQuantumMemory(length+1UL,sizeof(*message));
if (message != (char *) NULL)
{
(void) CopyMagickString(message,(char *) GetStringInfoDatum(
profile)+i+5,length+1);
(void) ConcatenateString(&attribute,message);
(void) ConcatenateString(&attribute,";");
message=DestroyString(message);
}
}
i+=5;
}
if ((attribute == (char *) NULL) || (*attribute == ';'))
{
if (attribute != (char *) NULL)
attribute=DestroyString(attribute);
return(MagickFalse);
}
attribute[strlen(attribute)-1]='\0';
(void) SetImageProperty((Image *) image,key,(const char *) attribute,
exception);
attribute=DestroyString(attribute);
return(MagickTrue);
}
static inline int ReadPropertyByte(const unsigned char **p,size_t *length)
{
int
c;
if (*length < 1)
return(EOF);
c=(int) (*(*p)++);
(*length)--;
return(c);
}
static inline signed int ReadPropertyMSBLong(const unsigned char **p,
size_t *length)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[4];
unsigned int
value;
if (*length < 4)
return(-1);
for (i=0; i < 4; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
static inline signed short ReadPropertyMSBShort(const unsigned char **p,
size_t *length)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[2];
unsigned short
value;
if (*length < 2)
return((unsigned short) ~0);
for (i=0; i < 2; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((count < 0) || ((size_t) count > length))
{
length=0;
continue;
}
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
}
static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian,
const unsigned char *buffer)
{
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
return(value & 0xffffffff);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
return(value & 0xffffffff);
}
static inline signed short ReadPropertySignedShort(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian,
const unsigned char *buffer)
{
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
return(value & 0xffff);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
return(value & 0xffff);
}
static MagickBooleanType GetEXIFProperty(const Image *image,
const char *property,ExceptionInfo *exception)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define EXIF_FMT_BYTE 1
#define EXIF_FMT_STRING 2
#define EXIF_FMT_USHORT 3
#define EXIF_FMT_ULONG 4
#define EXIF_FMT_URATIONAL 5
#define EXIF_FMT_SBYTE 6
#define EXIF_FMT_UNDEFINED 7
#define EXIF_FMT_SSHORT 8
#define EXIF_FMT_SLONG 9
#define EXIF_FMT_SRATIONAL 10
#define EXIF_FMT_SINGLE 11
#define EXIF_FMT_DOUBLE 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_GPS_OFFSET 0x8825
#define TAG_INTEROP_OFFSET 0xa005
#define EXIFMultipleValues(size,format,arg) \
{ \
ssize_t \
component; \
\
size_t \
length; \
\
unsigned char \
*p1; \
\
length=0; \
p1=p; \
for (component=0; component < components; component++) \
{ \
length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \
format", ",arg); \
if (length >= (MagickPathExtent-1)) \
length=MagickPathExtent-1; \
p1+=size; \
} \
if (length > 1) \
buffer[length-2]='\0'; \
value=AcquireString(buffer); \
}
#define EXIFMultipleFractions(size,format,arg1,arg2) \
{ \
ssize_t \
component; \
\
size_t \
length; \
\
unsigned char \
*p1; \
\
length=0; \
p1=p; \
for (component=0; component < components; component++) \
{ \
length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \
format", ",(arg1),(arg2)); \
if (length >= (MagickPathExtent-1)) \
length=MagickPathExtent-1; \
p1+=size; \
} \
if (length > 1) \
buffer[length-2]='\0'; \
value=AcquireString(buffer); \
}
typedef struct _DirectoryInfo
{
const unsigned char
*directory;
size_t
entry;
ssize_t
offset;
} DirectoryInfo;
typedef struct _TagInfo
{
size_t
tag;
const char
*description;
} TagInfo;
static TagInfo
EXIFTag[] =
{
{ 0x001, "exif:InteroperabilityIndex" },
{ 0x002, "exif:InteroperabilityVersion" },
{ 0x100, "exif:ImageWidth" },
{ 0x101, "exif:ImageLength" },
{ 0x102, "exif:BitsPerSample" },
{ 0x103, "exif:Compression" },
{ 0x106, "exif:PhotometricInterpretation" },
{ 0x10a, "exif:FillOrder" },
{ 0x10d, "exif:DocumentName" },
{ 0x10e, "exif:ImageDescription" },
{ 0x10f, "exif:Make" },
{ 0x110, "exif:Model" },
{ 0x111, "exif:StripOffsets" },
{ 0x112, "exif:Orientation" },
{ 0x115, "exif:SamplesPerPixel" },
{ 0x116, "exif:RowsPerStrip" },
{ 0x117, "exif:StripByteCounts" },
{ 0x11a, "exif:XResolution" },
{ 0x11b, "exif:YResolution" },
{ 0x11c, "exif:PlanarConfiguration" },
{ 0x11d, "exif:PageName" },
{ 0x11e, "exif:XPosition" },
{ 0x11f, "exif:YPosition" },
{ 0x118, "exif:MinSampleValue" },
{ 0x119, "exif:MaxSampleValue" },
{ 0x120, "exif:FreeOffsets" },
{ 0x121, "exif:FreeByteCounts" },
{ 0x122, "exif:GrayResponseUnit" },
{ 0x123, "exif:GrayResponseCurve" },
{ 0x124, "exif:T4Options" },
{ 0x125, "exif:T6Options" },
{ 0x128, "exif:ResolutionUnit" },
{ 0x12d, "exif:TransferFunction" },
{ 0x131, "exif:Software" },
{ 0x132, "exif:DateTime" },
{ 0x13b, "exif:Artist" },
{ 0x13e, "exif:WhitePoint" },
{ 0x13f, "exif:PrimaryChromaticities" },
{ 0x140, "exif:ColorMap" },
{ 0x141, "exif:HalfToneHints" },
{ 0x142, "exif:TileWidth" },
{ 0x143, "exif:TileLength" },
{ 0x144, "exif:TileOffsets" },
{ 0x145, "exif:TileByteCounts" },
{ 0x14a, "exif:SubIFD" },
{ 0x14c, "exif:InkSet" },
{ 0x14d, "exif:InkNames" },
{ 0x14e, "exif:NumberOfInks" },
{ 0x150, "exif:DotRange" },
{ 0x151, "exif:TargetPrinter" },
{ 0x152, "exif:ExtraSample" },
{ 0x153, "exif:SampleFormat" },
{ 0x154, "exif:SMinSampleValue" },
{ 0x155, "exif:SMaxSampleValue" },
{ 0x156, "exif:TransferRange" },
{ 0x157, "exif:ClipPath" },
{ 0x158, "exif:XClipPathUnits" },
{ 0x159, "exif:YClipPathUnits" },
{ 0x15a, "exif:Indexed" },
{ 0x15b, "exif:JPEGTables" },
{ 0x15f, "exif:OPIProxy" },
{ 0x200, "exif:JPEGProc" },
{ 0x201, "exif:JPEGInterchangeFormat" },
{ 0x202, "exif:JPEGInterchangeFormatLength" },
{ 0x203, "exif:JPEGRestartInterval" },
{ 0x205, "exif:JPEGLosslessPredictors" },
{ 0x206, "exif:JPEGPointTransforms" },
{ 0x207, "exif:JPEGQTables" },
{ 0x208, "exif:JPEGDCTables" },
{ 0x209, "exif:JPEGACTables" },
{ 0x211, "exif:YCbCrCoefficients" },
{ 0x212, "exif:YCbCrSubSampling" },
{ 0x213, "exif:YCbCrPositioning" },
{ 0x214, "exif:ReferenceBlackWhite" },
{ 0x2bc, "exif:ExtensibleMetadataPlatform" },
{ 0x301, "exif:Gamma" },
{ 0x302, "exif:ICCProfileDescriptor" },
{ 0x303, "exif:SRGBRenderingIntent" },
{ 0x320, "exif:ImageTitle" },
{ 0x5001, "exif:ResolutionXUnit" },
{ 0x5002, "exif:ResolutionYUnit" },
{ 0x5003, "exif:ResolutionXLengthUnit" },
{ 0x5004, "exif:ResolutionYLengthUnit" },
{ 0x5005, "exif:PrintFlags" },
{ 0x5006, "exif:PrintFlagsVersion" },
{ 0x5007, "exif:PrintFlagsCrop" },
{ 0x5008, "exif:PrintFlagsBleedWidth" },
{ 0x5009, "exif:PrintFlagsBleedWidthScale" },
{ 0x500A, "exif:HalftoneLPI" },
{ 0x500B, "exif:HalftoneLPIUnit" },
{ 0x500C, "exif:HalftoneDegree" },
{ 0x500D, "exif:HalftoneShape" },
{ 0x500E, "exif:HalftoneMisc" },
{ 0x500F, "exif:HalftoneScreen" },
{ 0x5010, "exif:JPEGQuality" },
{ 0x5011, "exif:GridSize" },
{ 0x5012, "exif:ThumbnailFormat" },
{ 0x5013, "exif:ThumbnailWidth" },
{ 0x5014, "exif:ThumbnailHeight" },
{ 0x5015, "exif:ThumbnailColorDepth" },
{ 0x5016, "exif:ThumbnailPlanes" },
{ 0x5017, "exif:ThumbnailRawBytes" },
{ 0x5018, "exif:ThumbnailSize" },
{ 0x5019, "exif:ThumbnailCompressedSize" },
{ 0x501a, "exif:ColorTransferFunction" },
{ 0x501b, "exif:ThumbnailData" },
{ 0x5020, "exif:ThumbnailImageWidth" },
{ 0x5021, "exif:ThumbnailImageHeight" },
{ 0x5022, "exif:ThumbnailBitsPerSample" },
{ 0x5023, "exif:ThumbnailCompression" },
{ 0x5024, "exif:ThumbnailPhotometricInterp" },
{ 0x5025, "exif:ThumbnailImageDescription" },
{ 0x5026, "exif:ThumbnailEquipMake" },
{ 0x5027, "exif:ThumbnailEquipModel" },
{ 0x5028, "exif:ThumbnailStripOffsets" },
{ 0x5029, "exif:ThumbnailOrientation" },
{ 0x502a, "exif:ThumbnailSamplesPerPixel" },
{ 0x502b, "exif:ThumbnailRowsPerStrip" },
{ 0x502c, "exif:ThumbnailStripBytesCount" },
{ 0x502d, "exif:ThumbnailResolutionX" },
{ 0x502e, "exif:ThumbnailResolutionY" },
{ 0x502f, "exif:ThumbnailPlanarConfig" },
{ 0x5030, "exif:ThumbnailResolutionUnit" },
{ 0x5031, "exif:ThumbnailTransferFunction" },
{ 0x5032, "exif:ThumbnailSoftwareUsed" },
{ 0x5033, "exif:ThumbnailDateTime" },
{ 0x5034, "exif:ThumbnailArtist" },
{ 0x5035, "exif:ThumbnailWhitePoint" },
{ 0x5036, "exif:ThumbnailPrimaryChromaticities" },
{ 0x5037, "exif:ThumbnailYCbCrCoefficients" },
{ 0x5038, "exif:ThumbnailYCbCrSubsampling" },
{ 0x5039, "exif:ThumbnailYCbCrPositioning" },
{ 0x503A, "exif:ThumbnailRefBlackWhite" },
{ 0x503B, "exif:ThumbnailCopyRight" },
{ 0x5090, "exif:LuminanceTable" },
{ 0x5091, "exif:ChrominanceTable" },
{ 0x5100, "exif:FrameDelay" },
{ 0x5101, "exif:LoopCount" },
{ 0x5110, "exif:PixelUnit" },
{ 0x5111, "exif:PixelPerUnitX" },
{ 0x5112, "exif:PixelPerUnitY" },
{ 0x5113, "exif:PaletteHistogram" },
{ 0x1000, "exif:RelatedImageFileFormat" },
{ 0x1001, "exif:RelatedImageLength" },
{ 0x1002, "exif:RelatedImageWidth" },
{ 0x800d, "exif:ImageID" },
{ 0x80e3, "exif:Matteing" },
{ 0x80e4, "exif:DataType" },
{ 0x80e5, "exif:ImageDepth" },
{ 0x80e6, "exif:TileDepth" },
{ 0x828d, "exif:CFARepeatPatternDim" },
{ 0x828e, "exif:CFAPattern2" },
{ 0x828f, "exif:BatteryLevel" },
{ 0x8298, "exif:Copyright" },
{ 0x829a, "exif:ExposureTime" },
{ 0x829d, "exif:FNumber" },
{ 0x83bb, "exif:IPTC/NAA" },
{ 0x84e3, "exif:IT8RasterPadding" },
{ 0x84e5, "exif:IT8ColorTable" },
{ 0x8649, "exif:ImageResourceInformation" },
{ 0x8769, "exif:ExifOffset" },
{ 0x8773, "exif:InterColorProfile" },
{ 0x8822, "exif:ExposureProgram" },
{ 0x8824, "exif:SpectralSensitivity" },
{ 0x8825, "exif:GPSInfo" },
{ 0x8827, "exif:ISOSpeedRatings" },
{ 0x8828, "exif:OECF" },
{ 0x8829, "exif:Interlace" },
{ 0x882a, "exif:TimeZoneOffset" },
{ 0x882b, "exif:SelfTimerMode" },
{ 0x9000, "exif:ExifVersion" },
{ 0x9003, "exif:DateTimeOriginal" },
{ 0x9004, "exif:DateTimeDigitized" },
{ 0x9101, "exif:ComponentsConfiguration" },
{ 0x9102, "exif:CompressedBitsPerPixel" },
{ 0x9201, "exif:ShutterSpeedValue" },
{ 0x9202, "exif:ApertureValue" },
{ 0x9203, "exif:BrightnessValue" },
{ 0x9204, "exif:ExposureBiasValue" },
{ 0x9205, "exif:MaxApertureValue" },
{ 0x9206, "exif:SubjectDistance" },
{ 0x9207, "exif:MeteringMode" },
{ 0x9208, "exif:LightSource" },
{ 0x9209, "exif:Flash" },
{ 0x920a, "exif:FocalLength" },
{ 0x920b, "exif:FlashEnergy" },
{ 0x920c, "exif:SpatialFrequencyResponse" },
{ 0x920d, "exif:Noise" },
{ 0x9211, "exif:ImageNumber" },
{ 0x9212, "exif:SecurityClassification" },
{ 0x9213, "exif:ImageHistory" },
{ 0x9214, "exif:SubjectArea" },
{ 0x9215, "exif:ExposureIndex" },
{ 0x9216, "exif:TIFF-EPStandardID" },
{ 0x927c, "exif:MakerNote" },
{ 0x9C9b, "exif:WinXP-Title" },
{ 0x9C9c, "exif:WinXP-Comments" },
{ 0x9C9d, "exif:WinXP-Author" },
{ 0x9C9e, "exif:WinXP-Keywords" },
{ 0x9C9f, "exif:WinXP-Subject" },
{ 0x9286, "exif:UserComment" },
{ 0x9290, "exif:SubSecTime" },
{ 0x9291, "exif:SubSecTimeOriginal" },
{ 0x9292, "exif:SubSecTimeDigitized" },
{ 0xa000, "exif:FlashPixVersion" },
{ 0xa001, "exif:ColorSpace" },
{ 0xa002, "exif:ExifImageWidth" },
{ 0xa003, "exif:ExifImageLength" },
{ 0xa004, "exif:RelatedSoundFile" },
{ 0xa005, "exif:InteroperabilityOffset" },
{ 0xa20b, "exif:FlashEnergy" },
{ 0xa20c, "exif:SpatialFrequencyResponse" },
{ 0xa20d, "exif:Noise" },
{ 0xa20e, "exif:FocalPlaneXResolution" },
{ 0xa20f, "exif:FocalPlaneYResolution" },
{ 0xa210, "exif:FocalPlaneResolutionUnit" },
{ 0xa214, "exif:SubjectLocation" },
{ 0xa215, "exif:ExposureIndex" },
{ 0xa216, "exif:TIFF/EPStandardID" },
{ 0xa217, "exif:SensingMethod" },
{ 0xa300, "exif:FileSource" },
{ 0xa301, "exif:SceneType" },
{ 0xa302, "exif:CFAPattern" },
{ 0xa401, "exif:CustomRendered" },
{ 0xa402, "exif:ExposureMode" },
{ 0xa403, "exif:WhiteBalance" },
{ 0xa404, "exif:DigitalZoomRatio" },
{ 0xa405, "exif:FocalLengthIn35mmFilm" },
{ 0xa406, "exif:SceneCaptureType" },
{ 0xa407, "exif:GainControl" },
{ 0xa408, "exif:Contrast" },
{ 0xa409, "exif:Saturation" },
{ 0xa40a, "exif:Sharpness" },
{ 0xa40b, "exif:DeviceSettingDescription" },
{ 0xa40c, "exif:SubjectDistanceRange" },
{ 0xa420, "exif:ImageUniqueID" },
{ 0xc4a5, "exif:PrintImageMatching" },
{ 0xa500, "exif:Gamma" },
{ 0xc640, "exif:CR2Slice" },
{ 0x10000, "exif:GPSVersionID" },
{ 0x10001, "exif:GPSLatitudeRef" },
{ 0x10002, "exif:GPSLatitude" },
{ 0x10003, "exif:GPSLongitudeRef" },
{ 0x10004, "exif:GPSLongitude" },
{ 0x10005, "exif:GPSAltitudeRef" },
{ 0x10006, "exif:GPSAltitude" },
{ 0x10007, "exif:GPSTimeStamp" },
{ 0x10008, "exif:GPSSatellites" },
{ 0x10009, "exif:GPSStatus" },
{ 0x1000a, "exif:GPSMeasureMode" },
{ 0x1000b, "exif:GPSDop" },
{ 0x1000c, "exif:GPSSpeedRef" },
{ 0x1000d, "exif:GPSSpeed" },
{ 0x1000e, "exif:GPSTrackRef" },
{ 0x1000f, "exif:GPSTrack" },
{ 0x10010, "exif:GPSImgDirectionRef" },
{ 0x10011, "exif:GPSImgDirection" },
{ 0x10012, "exif:GPSMapDatum" },
{ 0x10013, "exif:GPSDestLatitudeRef" },
{ 0x10014, "exif:GPSDestLatitude" },
{ 0x10015, "exif:GPSDestLongitudeRef" },
{ 0x10016, "exif:GPSDestLongitude" },
{ 0x10017, "exif:GPSDestBearingRef" },
{ 0x10018, "exif:GPSDestBearing" },
{ 0x10019, "exif:GPSDestDistanceRef" },
{ 0x1001a, "exif:GPSDestDistance" },
{ 0x1001b, "exif:GPSProcessingMethod" },
{ 0x1001c, "exif:GPSAreaInformation" },
{ 0x1001d, "exif:GPSDateStamp" },
{ 0x1001e, "exif:GPSDifferential" },
{ 0x00000, (const char *) NULL }
};
const StringInfo
*profile;
const unsigned char
*directory,
*exif;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
MagickBooleanType
status;
register ssize_t
i;
size_t
entry,
length,
number_entries,
tag,
tag_value;
SplayTreeInfo
*exif_resources;
ssize_t
all,
id,
level,
offset,
tag_offset;
static int
tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
/*
If EXIF data exists, then try to parse the request for a tag.
*/
profile=GetImageProfile(image,"exif");
if (profile == (const StringInfo *) NULL)
return(MagickFalse);
if ((property == (const char *) NULL) || (*property == '\0'))
return(MagickFalse);
while (isspace((int) ((unsigned char) *property)) != 0)
property++;
if (strlen(property) <= 5)
return(MagickFalse);
all=0;
tag=(~0UL);
switch (*(property+5))
{
case '*':
{
/*
Caller has asked for all the tags in the EXIF data.
*/
tag=0;
all=1; /* return the data in description=value format */
break;
}
case '!':
{
tag=0;
all=2; /* return the data in tagid=value format */
break;
}
case '#':
case '@':
{
int
c;
size_t
n;
/*
Check for a hex based tag specification first.
*/
tag=(*(property+5) == '@') ? 1UL : 0UL;
property+=6;
n=strlen(property);
if (n != 4)
return(MagickFalse);
/*
Parse tag specification as a hex number.
*/
n/=4;
do
{
for (i=(ssize_t) n-1L; i >= 0; i--)
{
c=(*property++);
tag<<=4;
if ((c >= '0') && (c <= '9'))
tag|=(c-'0');
else
if ((c >= 'A') && (c <= 'F'))
tag|=(c-('A'-10));
else
if ((c >= 'a') && (c <= 'f'))
tag|=(c-('a'-10));
else
return(MagickFalse);
}
} while (*property != '\0');
break;
}
default:
{
/*
Try to match the text with a tag name instead.
*/
for (i=0; ; i++)
{
if (EXIFTag[i].tag == 0)
break;
if (LocaleCompare(EXIFTag[i].description,property) == 0)
{
tag=(size_t) EXIFTag[i].tag;
break;
}
}
break;
}
}
if (tag == (~0UL))
return(MagickFalse);
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
while (length != 0)
{
if (ReadPropertyByte(&exif,&length) != 0x45)
continue;
if (ReadPropertyByte(&exif,&length) != 0x78)
continue;
if (ReadPropertyByte(&exif,&length) != 0x69)
continue;
if (ReadPropertyByte(&exif,&length) != 0x66)
continue;
if (ReadPropertyByte(&exif,&length) != 0x00)
continue;
if (ReadPropertyByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif);
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ReadPropertySignedLong(endian,exif+4);
if ((offset < 0) || (size_t) offset >= length)
return(MagickFalse);
/*
Set the pointer to the first IFD and follow it were it leads.
*/
status=MagickFalse;
directory=exif+offset;
level=0;
entry=0;
tag_offset=0;
exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,
(void *(*)(void *)) NULL,(void *(*)(void *)) NULL);
do
{
/*
If there is anything on the stack then pop it off.
*/
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
tag_offset=directory_stack[level].offset;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
register unsigned char
*p,
*q;
size_t
format;
ssize_t
number_bytes,
components;
q=(unsigned char *) (directory+(12*entry)+2);
if (q > (exif+length-12))
break; /* corrupt EXIF */
if (GetValueFromSplayTree(exif_resources,q) == q)
break;
(void) AddValueToSplayTree(exif_resources,q,q);
tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset;
format=(size_t) ReadPropertyUnsignedShort(endian,q+2);
if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes)))
break;
components=(ssize_t) ReadPropertySignedLong(endian,q+4);
if (components < 0)
break; /* corrupt EXIF */
number_bytes=(size_t) components*tag_bytes[format];
if (number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
ssize_t
offset;
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ReadPropertySignedLong(endian,q+8);
if ((offset < 0) || (size_t) offset >= length)
continue;
if ((ssize_t) (offset+number_bytes) < offset)
continue; /* prevent overflow */
if ((size_t) (offset+number_bytes) > length)
continue;
p=(unsigned char *) (exif+offset);
}
if ((all != 0) || (tag == (size_t) tag_value))
{
char
buffer[MagickPathExtent],
*value;
value=(char *) NULL;
*buffer='\0';
switch (format)
{
case EXIF_FMT_BYTE:
case EXIF_FMT_UNDEFINED:
{
EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1));
break;
}
case EXIF_FMT_SBYTE:
{
EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1));
break;
}
case EXIF_FMT_SSHORT:
{
EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1));
break;
}
case EXIF_FMT_USHORT:
{
EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1));
break;
}
case EXIF_FMT_ULONG:
{
EXIFMultipleValues(4,"%.20g",(double)
ReadPropertyUnsignedLong(endian,p1));
break;
}
case EXIF_FMT_SLONG:
{
EXIFMultipleValues(4,"%.20g",(double)
ReadPropertySignedLong(endian,p1));
break;
}
case EXIF_FMT_URATIONAL:
{
EXIFMultipleFractions(8,"%.20g/%.20g",(double)
ReadPropertyUnsignedLong(endian,p1),(double)
ReadPropertyUnsignedLong(endian,p1+4));
break;
}
case EXIF_FMT_SRATIONAL:
{
EXIFMultipleFractions(8,"%.20g/%.20g",(double)
ReadPropertySignedLong(endian,p1),(double)
ReadPropertySignedLong(endian,p1+4));
break;
}
case EXIF_FMT_SINGLE:
{
EXIFMultipleValues(4,"%f",(double) *(float *) p1);
break;
}
case EXIF_FMT_DOUBLE:
{
EXIFMultipleValues(8,"%f",*(double *) p1);
break;
}
default:
case EXIF_FMT_STRING:
{
value=(char *) NULL;
if (~((size_t) number_bytes) >= 1)
value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL,
sizeof(*value));
if (value != (char *) NULL)
{
register ssize_t
i;
for (i=0; i < (ssize_t) number_bytes; i++)
{
value[i]='.';
if ((isprint((int) p[i]) != 0) || (p[i] == '\0'))
value[i]=(char) p[i];
}
value[i]='\0';
}
break;
}
}
if (value != (char *) NULL)
{
char
*key;
register const char
*p;
key=AcquireString(property);
switch (all)
{
case 1:
{
const char
*description;
register ssize_t
i;
description="unknown";
for (i=0; ; i++)
{
if (EXIFTag[i].tag == 0)
break;
if (EXIFTag[i].tag == tag_value)
{
description=EXIFTag[i].description;
break;
}
}
(void) FormatLocaleString(key,MagickPathExtent,"%s",
description);
if (level == 2)
(void) SubstituteString(&key,"exif:","exif:thumbnail:");
break;
}
case 2:
{
if (tag_value < 0x10000)
(void) FormatLocaleString(key,MagickPathExtent,"#%04lx",
(unsigned long) tag_value);
else
if (tag_value < 0x20000)
(void) FormatLocaleString(key,MagickPathExtent,"@%04lx",
(unsigned long) (tag_value & 0xffff));
else
(void) FormatLocaleString(key,MagickPathExtent,"unknown");
break;
}
default:
{
if (level == 2)
(void) SubstituteString(&key,"exif:","exif:thumbnail:");
}
}
p=(const char *) NULL;
if (image->properties != (void *) NULL)
p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)
image->properties,key);
if (p == (const char *) NULL)
(void) SetImageProperty((Image *) image,key,value,exception);
value=DestroyString(value);
key=DestroyString(key);
status=MagickTrue;
}
}
if ((tag_value == TAG_EXIF_OFFSET) ||
(tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET))
{
ssize_t
offset;
offset=(ssize_t) ReadPropertySignedLong(endian,p);
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
ssize_t
tag_offset1;
tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 :
0);
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
directory_stack[level].offset=tag_offset;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].offset=tag_offset1;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12*
number_entries));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
directory_stack[level].offset=tag_offset1;
level++;
}
}
break;
}
}
} while (level > 0);
exif_resources=DestroySplayTree(exif_resources);
return(status);
}
static MagickBooleanType GetICCProperty(const Image *image,const char *property,
ExceptionInfo *exception)
{
const StringInfo
*profile;
magick_unreferenced(property);
profile=GetImageProfile(image,"icc");
if (profile == (StringInfo *) NULL)
profile=GetImageProfile(image,"icm");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
if (GetStringInfoLength(profile) < 128)
return(MagickFalse); /* minimum ICC profile length */
#if defined(MAGICKCORE_LCMS_DELEGATE)
{
cmsHPROFILE
icc_profile;
icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile),
(cmsUInt32Number) GetStringInfoLength(profile));
if (icc_profile != (cmsHPROFILE *) NULL)
{
#if defined(LCMS_VERSION) && (LCMS_VERSION < 2000)
const char
*name;
name=cmsTakeProductName(icc_profile);
if (name != (const char *) NULL)
(void) SetImageProperty((Image *) image,"icc:name",name,exception);
#else
char
info[MagickPathExtent];
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription,"en","US",
info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:description",info,
exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoManufacturer,"en","US",
info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:manufacturer",info,
exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoModel,"en","US",info,
MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:model",info,exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoCopyright,"en","US",
info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:copyright",info,exception);
#endif
(void) cmsCloseProfile(icc_profile);
}
}
#endif
return(MagickTrue);
}
static MagickBooleanType SkipXMPValue(const char *value)
{
if (value == (const char*) NULL)
return(MagickTrue);
while (*value != '\0')
{
if (isspace((int) ((unsigned char) *value)) == 0)
return(MagickFalse);
value++;
}
return(MagickTrue);
}
static MagickBooleanType GetXMPProperty(const Image *image,const char *property)
{
char
*xmp_profile;
const char
*content;
const StringInfo
*profile;
ExceptionInfo
*exception;
MagickBooleanType
status;
register const char
*p;
XMLTreeInfo
*child,
*description,
*node,
*rdf,
*xmp;
profile=GetImageProfile(image,"xmp");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
if ((property == (const char *) NULL) || (*property == '\0'))
return(MagickFalse);
xmp_profile=StringInfoToString(profile);
if (xmp_profile == (char *) NULL)
return(MagickFalse);
for (p=xmp_profile; *p != '\0'; p++)
if ((*p == '<') && (*(p+1) == 'x'))
break;
exception=AcquireExceptionInfo();
xmp=NewXMLTree((char *) p,exception);
xmp_profile=DestroyString(xmp_profile);
exception=DestroyExceptionInfo(exception);
if (xmp == (XMLTreeInfo *) NULL)
return(MagickFalse);
status=MagickFalse;
rdf=GetXMLTreeChild(xmp,"rdf:RDF");
if (rdf != (XMLTreeInfo *) NULL)
{
if (image->properties == (void *) NULL)
((Image *) image)->properties=NewSplayTree(CompareSplayTreeString,
RelinquishMagickMemory,RelinquishMagickMemory);
description=GetXMLTreeChild(rdf,"rdf:Description");
while (description != (XMLTreeInfo *) NULL)
{
node=GetXMLTreeChild(description,(const char *) NULL);
while (node != (XMLTreeInfo *) NULL)
{
child=GetXMLTreeChild(node,(const char *) NULL);
content=GetXMLTreeContent(node);
if ((child == (XMLTreeInfo *) NULL) &&
(SkipXMPValue(content) == MagickFalse))
(void) AddValueToSplayTree((SplayTreeInfo *) image->properties,
ConstantString(GetXMLTreeTag(node)),ConstantString(content));
while (child != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(child);
if (SkipXMPValue(content) == MagickFalse)
(void) AddValueToSplayTree((SplayTreeInfo *) image->properties,
ConstantString(GetXMLTreeTag(child)),ConstantString(content));
child=GetXMLTreeSibling(child);
}
node=GetXMLTreeSibling(node);
}
description=GetNextXMLTreeTag(description);
}
}
xmp=DestroyXMLTree(xmp);
return(status);
}
static char *TracePSClippath(const unsigned char *blob,size_t length)
{
char
*path,
*message;
MagickBooleanType
in_subpath;
PointInfo
first[3],
last[3],
point[3];
register ssize_t
i,
x;
ssize_t
knot_count,
selector,
y;
path=AcquireString((char *) NULL);
if (path == (char *) NULL)
return((char *) NULL);
message=AcquireString((char *) NULL);
(void) FormatLocaleString(message,MagickPathExtent,"/ClipImage\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,"{\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /c {curveto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /l {lineto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /m {moveto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /v {currentpoint 6 2 roll curveto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /y {2 copy curveto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /z {closepath} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent," newpath\n");
(void) ConcatenateString(&path,message);
/*
The clipping path format is defined in "Adobe Photoshop File Formats
Specification" version 6.0 downloadable from adobe.com.
*/
(void) ResetMagickMemory(point,0,sizeof(point));
(void) ResetMagickMemory(first,0,sizeof(first));
(void) ResetMagickMemory(last,0,sizeof(last));
knot_count=0;
in_subpath=MagickFalse;
while (length > 0)
{
selector=(ssize_t) ReadPropertyMSBShort(&blob,&length);
switch (selector)
{
case 0:
case 3:
{
if (knot_count != 0)
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Expected subpath length record.
*/
knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length);
blob+=22;
length-=MagickMin(22,(ssize_t) length);
break;
}
case 1:
case 2:
case 4:
case 5:
{
if (knot_count == 0)
{
/*
Unexpected subpath knot
*/
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Add sub-path knot
*/
for (i=0; i < 3; i++)
{
size_t
xx,
yy;
yy=(size_t) ReadPropertyMSBLong(&blob,&length);
xx=(size_t) ReadPropertyMSBLong(&blob,&length);
x=(ssize_t) xx;
if (xx > 2147483647)
x=(ssize_t) xx-4294967295U-1;
y=(ssize_t) yy;
if (yy > 2147483647)
y=(ssize_t) yy-4294967295U-1;
point[i].x=(double) x/4096/4096;
point[i].y=1.0-(double) y/4096/4096;
}
if (in_subpath == MagickFalse)
{
(void) FormatLocaleString(message,MagickPathExtent," %g %g m\n",
point[1].x,point[1].y);
for (i=0; i < 3; i++)
{
first[i]=point[i];
last[i]=point[i];
}
}
else
{
/*
Handle special cases when Bezier curves are used to describe
corners and straight lines.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(point[0].x == point[1].x) && (point[0].y == point[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g l\n",point[1].x,point[1].y);
else
if ((last[1].x == last[2].x) && (last[1].y == last[2].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g v\n",point[0].x,point[0].y,
point[1].x,point[1].y);
else
if ((point[0].x == point[1].x) && (point[0].y == point[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g y\n",last[2].x,last[2].y,
point[1].x,point[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g %g %g c\n",last[2].x,
last[2].y,point[0].x,point[0].y,point[1].x,point[1].y);
for (i=0; i < 3; i++)
last[i]=point[i];
}
(void) ConcatenateString(&path,message);
in_subpath=MagickTrue;
knot_count--;
/*
Close the subpath if there are no more knots.
*/
if (knot_count == 0)
{
/*
Same special handling as above except we compare to the
first point in the path and close the path.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(first[0].x == first[1].x) && (first[0].y == first[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g l z\n",first[1].x,first[1].y);
else
if ((last[1].x == last[2].x) && (last[1].y == last[2].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g v z\n",first[0].x,first[0].y,
first[1].x,first[1].y);
else
if ((first[0].x == first[1].x) && (first[0].y == first[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g y z\n",last[2].x,last[2].y,
first[1].x,first[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g %g %g c z\n",last[2].x,
last[2].y,first[0].x,first[0].y,first[1].x,first[1].y);
(void) ConcatenateString(&path,message);
in_subpath=MagickFalse;
}
break;
}
case 6:
case 7:
case 8:
default:
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
}
}
/*
Returns an empty PS path if the path has no knots.
*/
(void) FormatLocaleString(message,MagickPathExtent," eoclip\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,"} bind def");
(void) ConcatenateString(&path,message);
message=DestroyString(message);
return(path);
}
static char *TraceSVGClippath(const unsigned char *blob,size_t length,
const size_t columns,const size_t rows)
{
char
*path,
*message;
MagickBooleanType
in_subpath;
PointInfo
first[3],
last[3],
point[3];
register ssize_t
i;
ssize_t
knot_count,
selector,
x,
y;
path=AcquireString((char *) NULL);
if (path == (char *) NULL)
return((char *) NULL);
message=AcquireString((char *) NULL);
(void) FormatLocaleString(message,MagickPathExtent,(
"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
"<svg xmlns=\"http://www.w3.org/2000/svg\""
" width=\"%.20g\" height=\"%.20g\">\n"
"<g>\n"
"<path fill-rule=\"evenodd\" style=\"fill:#00000000;stroke:#00000000;"
"stroke-width:0;stroke-antialiasing:false\" d=\"\n"),(double) columns,
(double) rows);
(void) ConcatenateString(&path,message);
(void) ResetMagickMemory(point,0,sizeof(point));
(void) ResetMagickMemory(first,0,sizeof(first));
(void) ResetMagickMemory(last,0,sizeof(last));
knot_count=0;
in_subpath=MagickFalse;
while (length != 0)
{
selector=(ssize_t) ReadPropertyMSBShort(&blob,&length);
switch (selector)
{
case 0:
case 3:
{
if (knot_count != 0)
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Expected subpath length record.
*/
knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length);
blob+=22;
length-=MagickMin(22,(ssize_t) length);
break;
}
case 1:
case 2:
case 4:
case 5:
{
if (knot_count == 0)
{
/*
Unexpected subpath knot.
*/
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Add sub-path knot
*/
for (i=0; i < 3; i++)
{
unsigned int
xx,
yy;
yy=(unsigned int) ReadPropertyMSBLong(&blob,&length);
xx=(unsigned int) ReadPropertyMSBLong(&blob,&length);
x=(ssize_t) xx;
if (xx > 2147483647)
x=(ssize_t) xx-4294967295U-1;
y=(ssize_t) yy;
if (yy > 2147483647)
y=(ssize_t) yy-4294967295U-1;
point[i].x=(double) x*columns/4096/4096;
point[i].y=(double) y*rows/4096/4096;
}
if (in_subpath == MagickFalse)
{
(void) FormatLocaleString(message,MagickPathExtent,"M %g %g\n",
point[1].x,point[1].y);
for (i=0; i < 3; i++)
{
first[i]=point[i];
last[i]=point[i];
}
}
else
{
/*
Handle special cases when Bezier curves are used to describe
corners and straight lines.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(point[0].x == point[1].x) && (point[0].y == point[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
"L %g %g\n",point[1].x,point[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
"C %g %g %g %g %g %g\n",last[2].x,
last[2].y,point[0].x,point[0].y,point[1].x,point[1].y);
for (i=0; i < 3; i++)
last[i]=point[i];
}
(void) ConcatenateString(&path,message);
in_subpath=MagickTrue;
knot_count--;
/*
Close the subpath if there are no more knots.
*/
if (knot_count == 0)
{
/*
Same special handling as above except we compare to the
first point in the path and close the path.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(first[0].x == first[1].x) && (first[0].y == first[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
"L %g %g Z\n",first[1].x,first[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
"C %g %g %g %g %g %g Z\n",last[2].x,
last[2].y,first[0].x,first[0].y,first[1].x,first[1].y);
(void) ConcatenateString(&path,message);
in_subpath=MagickFalse;
}
break;
}
case 6:
case 7:
case 8:
default:
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
}
}
/*
Return an empty SVG image if the path does not have knots.
*/
(void) ConcatenateString(&path,"\"/>\n</g>\n</svg>\n");
message=DestroyString(message);
return(path);
}
MagickExport const char *GetImageProperty(const Image *image,
const char *property,ExceptionInfo *exception)
{
register const char
*p;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
p=(const char *) NULL;
if (image->properties != (void *) NULL)
{
if (property == (const char *) NULL)
{
ResetSplayTreeIterator((SplayTreeInfo *) image->properties);
p=(const char *) GetNextValueInSplayTree((SplayTreeInfo *)
image->properties);
return(p);
}
p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)
image->properties,property);
if (p != (const char *) NULL)
return(p);
}
if ((property == (const char *) NULL) ||
(strchr(property,':') == (char *) NULL))
return(p);
switch (*property)
{
case '8':
{
if (LocaleNCompare("8bim:",property,5) == 0)
{
(void) Get8BIMProperty(image,property,exception);
break;
}
break;
}
case 'E':
case 'e':
{
if (LocaleNCompare("exif:",property,5) == 0)
{
(void) GetEXIFProperty(image,property,exception);
break;
}
break;
}
case 'I':
case 'i':
{
if ((LocaleNCompare("icc:",property,4) == 0) ||
(LocaleNCompare("icm:",property,4) == 0))
{
(void) GetICCProperty(image,property,exception);
break;
}
if (LocaleNCompare("iptc:",property,5) == 0)
{
(void) GetIPTCProperty(image,property,exception);
break;
}
break;
}
case 'X':
case 'x':
{
if (LocaleNCompare("xmp:",property,4) == 0)
{
(void) GetXMPProperty(image,property);
break;
}
break;
}
default:
break;
}
if (image->properties != (void *) NULL)
{
p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)
image->properties,property);
return(p);
}
return((const char *) NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t M a g i c k P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMagickProperty() gets attributes or calculated values that is associated
% with a fixed known property name, or single letter property. It may be
% called if no image is defined (IMv7), in which case only global image_info
% values are available:
%
% \n newline
% \r carriage return
% < less-than character.
% > greater-than character.
% & ampersand character.
% %% a percent sign
% %b file size of image read in
% %c comment meta-data property
% %d directory component of path
% %e filename extension or suffix
% %f filename (including suffix)
% %g layer canvas page geometry (equivalent to "%Wx%H%X%Y")
% %h current image height in pixels
% %i image filename (note: becomes output filename for "info:")
% %k CALCULATED: number of unique colors
% %l label meta-data property
% %m image file format (file magic)
% %n number of images in current image sequence
% %o output filename (used for delegates)
% %p index of image in current image list
% %q quantum depth (compile-time constant)
% %r image class and colorspace
% %s scene number (from input unless re-assigned)
% %t filename without directory or extension (suffix)
% %u unique temporary filename (used for delegates)
% %w current width in pixels
% %x x resolution (density)
% %y y resolution (density)
% %z image depth (as read in unless modified, image save depth)
% %A image transparency channel enabled (true/false)
% %C image compression type
% %D image GIF dispose method
% %G original image size (%wx%h; before any resizes)
% %H page (canvas) height
% %M Magick filename (original file exactly as given, including read mods)
% %O page (canvas) offset ( = %X%Y )
% %P page (canvas) size ( = %Wx%H )
% %Q image compression quality ( 0 = default )
% %S ?? scenes ??
% %T image time delay (in centi-seconds)
% %U image resolution units
% %W page (canvas) width
% %X page (canvas) x offset (including sign)
% %Y page (canvas) y offset (including sign)
% %Z unique filename (used for delegates)
% %@ CALCULATED: trim bounding box (without actually trimming)
% %# CALCULATED: 'signature' hash of image values
%
% This routine only handles specifically known properties. It does not
% handle special prefixed properties, profiles, or expressions. Nor does
% it return any free-form property strings.
%
% The returned string is stored in a structure somewhere, and should not be
% directly freed. If the string was generated (common) the string will be
% stored as as either as artifact or option 'get-property'. These may be
% deleted (cleaned up) when no longer required, but neither artifact or
% option is guranteed to exist.
%
% The format of the GetMagickProperty method is:
%
% const char *GetMagickProperty(ImageInfo *image_info,Image *image,
% const char *property,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info (optional)
%
% o image: the image (optional)
%
% o key: the key.
%
% o exception: return any errors or warnings in this structure.
%
*/
static const char *GetMagickPropertyLetter(ImageInfo *image_info,
Image *image,const char letter,ExceptionInfo *exception)
{
#define WarnNoImageReturn(format,arg) \
if (image == (Image *) NULL ) { \
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \
"NoImageForProperty",format,arg); \
return((const char *) NULL); \
}
#define WarnNoImageInfoReturn(format,arg) \
if (image_info == (ImageInfo *) NULL ) { \
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \
"NoImageInfoForProperty",format,arg); \
return((const char *) NULL); \
}
char
value[MagickPathExtent]; /* formatted string to store as an artifact */
const char
*string; /* return a string already stored somewher */
if ((image != (Image *) NULL) && (image->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
else
if ((image_info != (ImageInfo *) NULL) &&
(image_info->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images");
*value='\0'; /* formatted string */
string=(char *) NULL; /* constant string reference */
/*
Get properities that are directly defined by images.
*/
switch (letter)
{
case 'b': /* image size read in - in bytes */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatMagickSize(image->extent,MagickFalse,"B",MagickPathExtent,
value);
if (image->extent == 0)
(void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B",
MagickPathExtent,value);
break;
}
case 'c': /* image comment property - empty string by default */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=GetImageProperty(image,"comment",exception);
if ( string == (const char *) NULL )
string="";
break;
}
case 'd': /* Directory component of filename */
{
WarnNoImageReturn("\"%%%c\"",letter);
GetPathComponent(image->magick_filename,HeadPath,value);
if (*value == '\0')
string="";
break;
}
case 'e': /* Filename extension (suffix) of image file */
{
WarnNoImageReturn("\"%%%c\"",letter);
GetPathComponent(image->magick_filename,ExtensionPath,value);
if (*value == '\0')
string="";
break;
}
case 'f': /* Filename without directory component */
{
WarnNoImageReturn("\"%%%c\"",letter);
GetPathComponent(image->magick_filename,TailPath,value);
if (*value == '\0')
string="";
break;
}
case 'g': /* Image geometry, canvas and offset %Wx%H+%X+%Y */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
image->page.height,(double) image->page.x,(double) image->page.y);
break;
}
case 'h': /* Image height (current) */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image->rows != 0 ? image->rows : image->magick_rows));
break;
}
case 'i': /* Filename last used for an image (read or write) */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=image->filename;
break;
}
case 'k': /* Number of unique colors */
{
/*
FUTURE: ensure this does not generate the formatted comment!
*/
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetNumberColors(image,(FILE *) NULL,exception));
break;
}
case 'l': /* Image label property - empty string by default */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=GetImageProperty(image,"label",exception);
if (string == (const char *) NULL)
string="";
break;
}
case 'm': /* Image format (file magick) */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=image->magick;
break;
}
case 'n': /* Number of images in the list. */
{
if ( image != (Image *) NULL )
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetImageListLength(image));
else
string="0"; /* no images or scenes */
break;
}
case 'o': /* Output Filename - for delegate use only */
WarnNoImageInfoReturn("\"%%%c\"",letter);
string=image_info->filename;
break;
case 'p': /* Image index in current image list */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetImageIndexInList(image));
break;
}
case 'q': /* Quantum depth of image in memory */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
MAGICKCORE_QUANTUM_DEPTH);
break;
}
case 'r': /* Image storage class, colorspace, and alpha enabled. */
{
ColorspaceType
colorspace;
WarnNoImageReturn("\"%%%c\"",letter);
colorspace=image->colorspace;
if (SetImageGray(image,exception) != MagickFalse)
colorspace=GRAYColorspace; /* FUTURE: this is IMv6 not IMv7 */
(void) FormatLocaleString(value,MagickPathExtent,"%s %s %s",
CommandOptionToMnemonic(MagickClassOptions,(ssize_t)
image->storage_class),CommandOptionToMnemonic(MagickColorspaceOptions,
(ssize_t) colorspace),image->alpha_trait != UndefinedPixelTrait ?
"Alpha" : "");
break;
}
case 's': /* Image scene number */
{
#if 0 /* this seems non-sensical -- simplifing */
if (image_info->number_scenes != 0)
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image_info->scene);
else if (image != (Image *) NULL)
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->scene);
else
string="0";
#else
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->scene);
#endif
break;
}
case 't': /* Base filename without directory or extention */
{
WarnNoImageReturn("\"%%%c\"",letter);
GetPathComponent(image->magick_filename,BasePath,value);
if (*value == '\0')
string="";
break;
}
case 'u': /* Unique filename */
{
WarnNoImageInfoReturn("\"%%%c\"",letter);
string=image_info->unique;
break;
}
case 'w': /* Image width (current) */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image->columns != 0 ? image->columns : image->magick_columns));
break;
}
case 'x': /* Image horizontal resolution (with units) */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",
fabs(image->resolution.x) > MagickEpsilon ? image->resolution.x : 72.0);
break;
}
case 'y': /* Image vertical resolution (with units) */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",
fabs(image->resolution.y) > MagickEpsilon ? image->resolution.y : 72.0);
break;
}
case 'z': /* Image depth as read in */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->depth);
break;
}
case 'A': /* Image alpha channel */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=CommandOptionToMnemonic(MagickPixelTraitOptions,(ssize_t)
image->alpha_trait);
break;
}
case 'C': /* Image compression method. */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=CommandOptionToMnemonic(MagickCompressOptions,(ssize_t)
image->compression);
break;
}
case 'D': /* Image dispose method. */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=CommandOptionToMnemonic(MagickDisposeOptions,(ssize_t)
image->dispose);
break;
}
case 'G': /* Image size as geometry = "%wx%h" */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g",(double)
image->magick_columns,(double) image->magick_rows);
break;
}
case 'H': /* layer canvas height */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->page.height);
break;
}
case 'M': /* Magick filename - filename given incl. coder & read mods */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=image->magick_filename;
break;
}
case 'O': /* layer canvas offset with sign = "+%X+%Y" */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%+ld%+ld",(long)
image->page.x,(long) image->page.y);
break;
}
case 'P': /* layer canvas page size = "%Wx%H" */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g",(double)
image->page.width,(double) image->page.height);
break;
}
case 'Q': /* image compression quality */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image->quality == 0 ? 92 : image->quality));
break;
}
case 'S': /* Number of scenes in image list. */
{
WarnNoImageInfoReturn("\"%%%c\"",letter);
#if 0 /* What is this number? -- it makes no sense - simplifing */
if (image_info->number_scenes == 0)
string="2147483647";
else if ( image != (Image *) NULL )
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image_info->scene+image_info->number_scenes);
else
string="0";
#else
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image_info->number_scenes == 0 ? 2147483647 :
image_info->number_scenes));
#endif
break;
}
case 'T': /* image time delay for animations */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->delay);
break;
}
case 'U': /* Image resolution units. */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t)
image->units);
break;
}
case 'W': /* layer canvas width */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->page.width);
break;
}
case 'X': /* layer canvas X offset */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double)
image->page.x);
break;
}
case 'Y': /* layer canvas Y offset */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double)
image->page.y);
break;
}
case '%': /* percent escaped */
{
string="%";
break;
}
case '@': /* Trim bounding box, without actually Trimming! */
{
RectangleInfo
page;
WarnNoImageReturn("\"%%%c\"",letter);
page=GetImageBoundingBox(image,exception);
(void) FormatLocaleString(value,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) page.width,(double) page.height,
(double) page.x,(double)page.y);
break;
}
case '#':
{
/*
Image signature.
*/
WarnNoImageReturn("\"%%%c\"",letter);
(void) SignatureImage(image,exception);
string=GetImageProperty(image,"signature",exception);
break;
}
}
if (string != (char *) NULL)
return(string);
if (*value != '\0')
{
/*
Create a cloned copy of result.
*/
if (image != (Image *) NULL)
{
(void) SetImageArtifact(image,"get-property",value);
return(GetImageArtifact(image,"get-property"));
}
else
{
(void) SetImageOption(image_info,"get-property",value);
return(GetImageOption(image_info,"get-property"));
}
}
return((char *) NULL);
}
MagickExport const char *GetMagickProperty(ImageInfo *image_info,
Image *image,const char *property,ExceptionInfo *exception)
{
char
value[MagickPathExtent];
const char
*string;
assert(property[0] != '\0');
assert(image != (Image *) NULL || image_info != (ImageInfo *) NULL );
if (property[1] == '\0') /* single letter property request */
return(GetMagickPropertyLetter(image_info,image,*property,exception));
if ((image != (Image *) NULL) && (image->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
else
if ((image_info != (ImageInfo *) NULL) &&
(image_info->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images");
*value='\0'; /* formated string */
string=(char *) NULL; /* constant string reference */
switch (*property)
{
case 'b':
{
if (LocaleCompare("basename",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
GetPathComponent(image->magick_filename,BasePath,value);
if (*value == '\0')
string="";
break;
}
if (LocaleCompare("bit-depth",property) == 0)
{
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetImageDepth(image,exception));
break;
}
break;
}
case 'c':
{
if (LocaleCompare("channels",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
/* FUTURE: return actual image channels */
(void) FormatLocaleString(value,MagickPathExtent,"%s",
CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t)
image->colorspace));
LocaleLower(value);
if( image->alpha_trait != UndefinedPixelTrait )
(void) ConcatenateMagickString(value,"a",MagickPathExtent);
break;
}
if (LocaleCompare("colorspace",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
/* FUTURE: return actual colorspace - no 'gray' stuff */
string=CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t)
image->colorspace);
break;
}
if (LocaleCompare("compose",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickComposeOptions,(ssize_t)
image->compose);
break;
}
if (LocaleCompare("copyright",property) == 0)
{
(void) CopyMagickString(value,GetMagickCopyright(),MagickPathExtent);
break;
}
break;
}
case 'd':
{
if (LocaleCompare("depth",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->depth);
break;
}
if (LocaleCompare("directory",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
GetPathComponent(image->magick_filename,HeadPath,value);
if (*value == '\0')
string="";
break;
}
break;
}
case 'e':
{
if (LocaleCompare("entropy",property) == 0)
{
double
entropy;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageEntropy(image,&entropy,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),entropy);
break;
}
if (LocaleCompare("extension",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
GetPathComponent(image->magick_filename,ExtensionPath,value);
if (*value == '\0')
string="";
break;
}
break;
}
case 'g':
{
if (LocaleCompare("gamma",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),image->gamma);
break;
}
break;
}
case 'h':
{
if (LocaleCompare("height",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",
image->magick_rows != 0 ? (double) image->magick_rows : 256.0);
break;
}
break;
}
case 'i':
{
if (LocaleCompare("input",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=image->filename;
break;
}
break;
}
case 'k':
{
if (LocaleCompare("kurtosis",property) == 0)
{
double
kurtosis,
skewness;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),kurtosis);
break;
}
break;
}
case 'm':
{
if (LocaleCompare("magick",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=image->magick;
break;
}
if ((LocaleCompare("maxima",property) == 0) ||
(LocaleCompare("max",property) == 0))
{
double
maximum,
minimum;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageRange(image,&minimum,&maximum,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),maximum);
break;
}
if (LocaleCompare("mean",property) == 0)
{
double
mean,
standard_deviation;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageMean(image,&mean,&standard_deviation,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),mean);
break;
}
if ((LocaleCompare("minima",property) == 0) ||
(LocaleCompare("min",property) == 0))
{
double
maximum,
minimum;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageRange(image,&minimum,&maximum,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),minimum);
break;
}
break;
}
case 'o':
{
if (LocaleCompare("opaque",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t)
IsImageOpaque(image,exception));
break;
}
if (LocaleCompare("orientation",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickOrientationOptions,(ssize_t)
image->orientation);
break;
}
if (LocaleCompare("output",property) == 0)
{
WarnNoImageInfoReturn("\"%%[%s]\"",property);
(void) CopyMagickString(value,image_info->filename,MagickPathExtent);
break;
}
break;
}
case 'p':
{
#if defined(MAGICKCORE_LCMS_DELEGATE)
if (LocaleCompare("profile:icc",property) == 0 ||
LocaleCompare("profile:icm",property) == 0)
{
#if !defined(LCMS_VERSION) || (LCMS_VERSION < 2000)
#define cmsUInt32Number DWORD
#endif
const StringInfo
*profile;
cmsHPROFILE
icc_profile;
profile=GetImageProfile(image,property+8);
if (profile == (StringInfo *) NULL)
break;
icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile),
(cmsUInt32Number) GetStringInfoLength(profile));
if (icc_profile != (cmsHPROFILE *) NULL)
{
#if defined(LCMS_VERSION) && (LCMS_VERSION < 2000)
string=cmsTakeProductName(icc_profile);
#else
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription,
"en","US",value,MagickPathExtent);
#endif
(void) cmsCloseProfile(icc_profile);
}
}
#endif
if (LocaleCompare("profiles",property) == 0)
{
const char
*name;
ResetImageProfileIterator(image);
name=GetNextImageProfile(image);
if (name != (char *) NULL)
{
(void) CopyMagickString(value,name,MagickPathExtent);
name=GetNextImageProfile(image);
while (name != (char *) NULL)
{
ConcatenateMagickString(value,",",MagickPathExtent);
ConcatenateMagickString(value,name,MagickPathExtent);
name=GetNextImageProfile(image);
}
}
break;
}
break;
}
case 'r':
{
if (LocaleCompare("resolution.x",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%g",
image->resolution.x);
break;
}
if (LocaleCompare("resolution.y",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%g",
image->resolution.y);
break;
}
break;
}
case 's':
{
if (LocaleCompare("scene",property) == 0)
{
WarnNoImageInfoReturn("\"%%[%s]\"",property);
if (image_info->number_scenes != 0)
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image_info->scene);
else {
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->scene);
}
break;
}
if (LocaleCompare("scenes",property) == 0)
{
/* FUTURE: equivelent to %n? */
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetImageListLength(image));
break;
}
if (LocaleCompare("size",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B",
MagickPathExtent,value);
break;
}
if (LocaleCompare("skewness",property) == 0)
{
double
kurtosis,
skewness;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),skewness);
break;
}
if (LocaleCompare("standard-deviation",property) == 0)
{
double
mean,
standard_deviation;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageMean(image,&mean,&standard_deviation,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),standard_deviation);
break;
}
break;
}
case 't':
{
if (LocaleCompare("type",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickTypeOptions,(ssize_t)
IdentifyImageType(image,exception));
break;
}
break;
}
case 'u':
{
if (LocaleCompare("unique",property) == 0)
{
WarnNoImageInfoReturn("\"%%[%s]\"",property);
string=image_info->unique;
break;
}
if (LocaleCompare("units",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t)
image->units);
break;
}
break;
}
case 'v':
{
if (LocaleCompare("version",property) == 0)
{
string=GetMagickVersion((size_t *) NULL);
break;
}
break;
}
case 'w':
{
if (LocaleCompare("width",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image->magick_columns != 0 ? image->magick_columns : 256));
break;
}
break;
}
}
if (string != (char *) NULL)
return(string);
if (*value != '\0')
{
/*
Create a cloned copy of result, that will get cleaned up, eventually.
*/
if (image != (Image *) NULL)
{
(void) SetImageArtifact(image,"get-property",value);
return(GetImageArtifact(image,"get-property"));
}
else
{
(void) SetImageOption(image_info,"get-property",value);
return(GetImageOption(image_info,"get-property"));
}
}
return((char *) NULL);
}
#undef WarnNoImageReturn
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t N e x t I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNextImageProperty() gets the next free-form string property name.
%
% The format of the GetNextImageProperty method is:
%
% char *GetNextImageProperty(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport const char *GetNextImageProperty(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image->filename);
if (image->properties == (void *) NULL)
return((const char *) NULL);
return((const char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->properties));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p r e t I m a g e P r o p e r t i e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpretImageProperties() replaces any embedded formatting characters with
% the appropriate image property and returns the interpreted text.
%
% This searches for and replaces
% \n \r \% replaced by newline, return, and percent resp.
% < > & replaced by '<', '>', '&' resp.
% %% replaced by percent
%
% %x %[x] where 'x' is a single letter properity, case sensitive).
% %[type:name] where 'type' a is special and known prefix.
% %[name] where 'name' is a specifically known attribute, calculated
% value, or a per-image property string name, or a per-image
% 'artifact' (as generated from a global option).
% It may contain ':' as long as the prefix is not special.
%
% Single letter % substitutions will only happen if the character before the
% percent is NOT a number. But braced substitutions will always be performed.
% This prevents the typical usage of percent in a interpreted geometry
% argument from being substituted when the percent is a geometry flag.
%
% If 'glob-expresions' ('*' or '?' characters) is used for 'name' it may be
% used as a search pattern to print multiple lines of "name=value\n" pairs of
% the associacted set of properties.
%
% The returned string must be freed using DestoryString() by the caller.
%
% The format of the InterpretImageProperties method is:
%
% char *InterpretImageProperties(ImageInfo *image_info,
% Image *image,const char *embed_text,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info. (required)
%
% o image: the image. (optional)
%
% o embed_text: the address of a character string containing the embedded
% formatting characters.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport char *InterpretImageProperties(ImageInfo *image_info,Image *image,
const char *embed_text,ExceptionInfo *exception)
{
#define ExtendInterpretText(string_length) \
DisableMSCWarning(4127) \
{ \
size_t length=(string_length); \
if ((size_t) (q-interpret_text+length+1) >= extent) \
{ \
extent+=length; \
interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \
MaxTextExtent,sizeof(*interpret_text)); \
if (interpret_text == (char *) NULL) \
return((char *) NULL); \
q=interpret_text+strlen(interpret_text); \
} \
} \
RestoreMSCWarning
#define AppendKeyValue2Text(key,value)\
DisableMSCWarning(4127) \
{ \
size_t length=strlen(key)+strlen(value)+2; \
if ((size_t) (q-interpret_text+length+1) >= extent) \
{ \
extent+=length; \
interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \
MaxTextExtent,sizeof(*interpret_text)); \
if (interpret_text == (char *) NULL) \
return((char *) NULL); \
q=interpret_text+strlen(interpret_text); \
} \
q+=FormatLocaleString(q,extent,"%s=%s\n",(key),(value)); \
} \
RestoreMSCWarning
#define AppendString2Text(string) \
DisableMSCWarning(4127) \
{ \
size_t length=strlen((string)); \
if ((size_t) (q-interpret_text+length+1) >= extent) \
{ \
extent+=length; \
interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \
MaxTextExtent,sizeof(*interpret_text)); \
if (interpret_text == (char *) NULL) \
return((char *) NULL); \
q=interpret_text+strlen(interpret_text); \
} \
(void) CopyMagickString(q,(string),extent); \
q+=length; \
} \
RestoreMSCWarning
char
*interpret_text;
MagickBooleanType
number;
register char
*q; /* current position in interpret_text */
register const char
*p; /* position in embed_text string being expanded */
size_t
extent; /* allocated length of interpret_text */
assert(image == NULL || image->signature == MagickCoreSignature);
assert(image_info == NULL || image_info->signature == MagickCoreSignature);
if ((image != (Image *) NULL) && (image->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
else
if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-image");
if (embed_text == (const char *) NULL)
return(ConstantString(""));
p=embed_text;
while ((isspace((int) ((unsigned char) *p)) != 0) && (*p != '\0'))
p++;
if (*p == '\0')
return(ConstantString(""));
if ((*p == '@') && (IsPathAccessible(p+1) != MagickFalse))
{
/*
Handle a '@' replace string from file.
*/
if (IsRightsAuthorized(PathPolicyDomain,ReadPolicyRights,p) == MagickFalse)
{
errno=EPERM;
(void) ThrowMagickException(exception,GetMagickModule(),PolicyError,
"NotAuthorized","`%s'",p);
return(ConstantString(""));
}
interpret_text=FileToString(p+1,~0UL,exception);
if (interpret_text != (char *) NULL)
return(interpret_text);
}
/*
Translate any embedded format characters.
*/
interpret_text=AcquireString(embed_text); /* new string with extra space */
extent=MagickPathExtent; /* allocated space in string */
number=MagickFalse; /* is last char a number? */
for (q=interpret_text; *p!='\0'; number=isdigit(*p) ? MagickTrue : MagickFalse,p++)
{
/*
Look for the various escapes, (and handle other specials)
*/
*q='\0';
ExtendInterpretText(MagickPathExtent);
switch (*p)
{
case '\\':
{
switch (*(p+1))
{
case '\0':
continue;
case 'r': /* convert to RETURN */
{
*q++='\r';
p++;
continue;
}
case 'n': /* convert to NEWLINE */
{
*q++='\n';
p++;
continue;
}
case '\n': /* EOL removal UNIX,MacOSX */
{
p++;
continue;
}
case '\r': /* EOL removal DOS,Windows */
{
p++;
if (*p == '\n') /* return-newline EOL */
p++;
continue;
}
default:
{
p++;
*q++=(*p);
}
}
continue;
}
case '&':
{
if (LocaleNCompare("<",p,4) == 0)
{
*q++='<';
p+=3;
}
else
if (LocaleNCompare(">",p,4) == 0)
{
*q++='>';
p+=3;
}
else
if (LocaleNCompare("&",p,5) == 0)
{
*q++='&';
p+=4;
}
else
*q++=(*p);
continue;
}
case '%':
break; /* continue to next set of handlers */
default:
{
*q++=(*p); /* any thing else is 'as normal' */
continue;
}
}
p++; /* advance beyond the percent */
/*
Doubled Percent - or percent at end of string.
*/
if ((*p == '\0') || (*p == '\'') || (*p == '"'))
p--;
if (*p == '%')
{
*q++='%';
continue;
}
/*
Single letter escapes %c.
*/
if (*p != '[')
{
const char
*string;
if (number != MagickFalse)
{
/*
But only if not preceeded by a number!
*/
*q++='%'; /* do NOT substitute the percent */
p--; /* back up one */
continue;
}
string=GetMagickPropertyLetter(image_info,image,*p, exception);
if (string != (char *) NULL)
{
AppendString2Text(string);
if (image != (Image *) NULL)
(void) DeleteImageArtifact(image,"get-property");
if (image_info != (ImageInfo *) NULL)
(void) DeleteImageOption(image_info,"get-property");
continue;
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"UnknownImageProperty","\"%%%c\"",*p);
continue;
}
{
char
pattern[2*MagickPathExtent];
const char
*key,
*string;
register ssize_t
len;
ssize_t
depth;
/*
Braced Percent Escape %[...].
*/
p++; /* advance p to just inside the opening brace */
depth=1;
if (*p == ']')
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"UnknownImageProperty","\"%%[]\"");
break;
}
for (len=0; len<(MagickPathExtent-1L) && (*p != '\0');)
{
if ((*p == '\\') && (*(p+1) != '\0'))
{
/*
Skip escaped braces within braced pattern.
*/
pattern[len++]=(*p++);
pattern[len++]=(*p++);
continue;
}
if (*p == '[')
depth++;
if (*p == ']')
depth--;
if (depth <= 0)
break;
pattern[len++]=(*p++);
}
pattern[len]='\0';
if (depth != 0)
{
/*
Check for unmatched final ']' for "%[...]".
*/
if (len >= 64)
{
pattern[61] = '.'; /* truncate string for error message */
pattern[62] = '.';
pattern[63] = '.';
pattern[64] = '\0';
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnbalancedBraces","\"%%[%s\"",pattern);
interpret_text=DestroyString(interpret_text);
return((char *) NULL);
}
/*
Special Lookup Prefixes %[prefix:...].
*/
if (LocaleNCompare("fx:",pattern,3) == 0)
{
double
value;
FxInfo
*fx_info;
MagickBooleanType
status;
/*
FX - value calculator.
*/
if (image == (Image *) NULL )
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
fx_info=AcquireFxInfo(image,pattern+3,exception);
status=FxEvaluateChannelExpression(fx_info,IntensityPixelChannel,0,0,
&value,exception);
fx_info=DestroyFxInfo(fx_info);
if (status != MagickFalse)
{
char
result[MagickPathExtent];
(void) FormatLocaleString(result,MagickPathExtent,"%.*g",
GetMagickPrecision(),(double) value);
AppendString2Text(result);
}
continue;
}
if (LocaleNCompare("pixel:",pattern,6) == 0)
{
FxInfo
*fx_info;
double
value;
MagickStatusType
status;
PixelInfo
pixel;
/*
Pixel - color value calculator.
*/
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
GetPixelInfo(image,&pixel);
fx_info=AcquireFxInfo(image,pattern+6,exception);
status=FxEvaluateChannelExpression(fx_info,RedPixelChannel,0,0,
&value,exception);
pixel.red=(double) QuantumRange*value;
status&=FxEvaluateChannelExpression(fx_info,GreenPixelChannel,0,0,
&value,exception);
pixel.green=(double) QuantumRange*value;
status&=FxEvaluateChannelExpression(fx_info,BluePixelChannel,0,0,
&value,exception);
pixel.blue=(double) QuantumRange*value;
if (image->colorspace == CMYKColorspace)
{
status&=FxEvaluateChannelExpression(fx_info,BlackPixelChannel,0,0,
&value,exception);
pixel.black=(double) QuantumRange*value;
}
status&=FxEvaluateChannelExpression(fx_info,AlphaPixelChannel,0,0,
&value,exception);
pixel.alpha=(double) QuantumRange*value;
fx_info=DestroyFxInfo(fx_info);
if (status != MagickFalse)
{
char
name[MagickPathExtent];
(void) QueryColorname(image,&pixel,SVGCompliance,name,
exception);
AppendString2Text(name);
}
continue;
}
if (LocaleNCompare("option:",pattern,7) == 0)
{
/*
Option - direct global option lookup (with globbing).
*/
if (image_info == (ImageInfo *) NULL )
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
if (IsGlob(pattern+7) != MagickFalse)
{
ResetImageOptionIterator(image_info);
while ((key=GetNextImageOption(image_info)) != (const char *) NULL)
if (GlobExpression(key,pattern+7,MagickTrue) != MagickFalse)
{
string=GetImageOption(image_info,key);
if (string != (const char *) NULL)
AppendKeyValue2Text(key,string);
/* else - assertion failure? key found but no string value! */
}
continue;
}
string=GetImageOption(image_info,pattern+7);
if (string == (char *) NULL)
goto PropertyLookupFailure; /* no artifact of this specifc name */
AppendString2Text(string);
continue;
}
if (LocaleNCompare("artifact:",pattern,9) == 0)
{
/*
Artifact - direct image artifact lookup (with glob).
*/
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
if (IsGlob(pattern+9) != MagickFalse)
{
ResetImageArtifactIterator(image);
while ((key=GetNextImageArtifact(image)) != (const char *) NULL)
if (GlobExpression(key,pattern+9,MagickTrue) != MagickFalse)
{
string=GetImageArtifact(image,key);
if (string != (const char *) NULL)
AppendKeyValue2Text(key,string);
/* else - assertion failure? key found but no string value! */
}
continue;
}
string=GetImageArtifact(image,pattern+9);
if (string == (char *) NULL)
goto PropertyLookupFailure; /* no artifact of this specifc name */
AppendString2Text(string);
continue;
}
if (LocaleNCompare("property:",pattern,9) == 0)
{
/*
Property - direct image property lookup (with glob).
*/
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
if (IsGlob(pattern+9) != MagickFalse)
{
ResetImagePropertyIterator(image);
while ((key=GetNextImageProperty(image)) != (const char *) NULL)
if (GlobExpression(key,pattern,MagickTrue) != MagickFalse)
{
string=GetImageProperty(image,key,exception);
if (string != (const char *) NULL)
AppendKeyValue2Text(key,string);
/* else - assertion failure? */
}
continue;
}
string=GetImageProperty(image,pattern+9,exception);
if (string == (char *) NULL)
goto PropertyLookupFailure; /* no artifact of this specifc name */
AppendString2Text(string);
continue;
}
if (image != (Image *) NULL)
{
/*
Properties without special prefix. This handles attributes,
properties, and profiles such as %[exif:...]. Note the profile
properties may also include a glob expansion pattern.
*/
string=GetImageProperty(image,pattern,exception);
if (string != (const char *) NULL)
{
AppendString2Text(string);
if (image != (Image *) NULL)
(void)DeleteImageArtifact(image,"get-property");
if (image_info != (ImageInfo *) NULL)
(void)DeleteImageOption(image_info,"get-property");
continue;
}
}
if (IsGlob(pattern) != MagickFalse)
{
/*
Handle property 'glob' patterns such as:
%[*] %[user:array_??] %[filename:e*]>
*/
if (image == (Image *) NULL)
continue; /* else no image to retrieve proprty - no list */
ResetImagePropertyIterator(image);
while ((key=GetNextImageProperty(image)) != (const char *) NULL)
if (GlobExpression(key,pattern,MagickTrue) != MagickFalse)
{
string=GetImageProperty(image,key,exception);
if (string != (const char *) NULL)
AppendKeyValue2Text(key,string);
/* else - assertion failure? */
}
continue;
}
/*
Look for a known property or image attribute such as
%[basename] %[denisty] %[delay]. Also handles a braced single
letter: %[b] %[G] %[g].
*/
string=GetMagickProperty(image_info,image,pattern,exception);
if (string != (const char *) NULL)
{
AppendString2Text(string);
continue;
}
/*
Look for a per-image artifact. This includes option lookup
(FUTURE: interpreted according to image).
*/
if (image != (Image *) NULL)
{
string=GetImageArtifact(image,pattern);
if (string != (char *) NULL)
{
AppendString2Text(string);
continue;
}
}
else
if (image_info != (ImageInfo *) NULL)
{
/*
No image, so direct 'option' lookup (no delayed percent escapes).
*/
string=GetImageOption(image_info,pattern);
if (string != (char *) NULL)
{
AppendString2Text(string);
continue;
}
}
PropertyLookupFailure:
/*
Failed to find any match anywhere!
*/
if (len >= 64)
{
pattern[61] = '.'; /* truncate string for error message */
pattern[62] = '.';
pattern[63] = '.';
pattern[64] = '\0';
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"UnknownImageProperty","\"%%[%s]\"",pattern);
}
}
*q='\0';
return(interpret_text);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m o v e I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemoveImageProperty() removes a property from the image and returns its
% value.
%
% In this case the ConstantString() value returned should be freed by the
% caller when finished.
%
% The format of the RemoveImageProperty method is:
%
% char *RemoveImageProperty(Image *image,const char *property)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o property: the image property.
%
*/
MagickExport char *RemoveImageProperty(Image *image,const char *property)
{
char
*value;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties == (void *) NULL)
return((char *) NULL);
value=(char *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->properties,
property);
return(value);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t I m a g e P r o p e r t y I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImagePropertyIterator() resets the image properties iterator. Use it
% in conjunction with GetNextImageProperty() to iterate over all the values
% associated with an image property.
%
% The format of the ResetImagePropertyIterator method is:
%
% ResetImagePropertyIterator(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void ResetImagePropertyIterator(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties == (void *) NULL)
return;
ResetSplayTreeIterator((SplayTreeInfo *) image->properties);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageProperty() saves the given string value either to specific known
% attribute or to a freeform property string.
%
% Attempting to set a property that is normally calculated will produce
% an exception.
%
% The format of the SetImageProperty method is:
%
% MagickBooleanType SetImageProperty(Image *image,const char *property,
% const char *value,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o property: the image property.
%
% o values: the image property values.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageProperty(Image *image,
const char *property,const char *value,ExceptionInfo *exception)
{
MagickBooleanType
status;
MagickStatusType
flags;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties == (void *) NULL)
image->properties=NewSplayTree(CompareSplayTreeString,
RelinquishMagickMemory,RelinquishMagickMemory); /* create splay-tree */
if (value == (const char *) NULL)
return(DeleteImageProperty(image,property)); /* delete if NULL */
status=MagickTrue;
if (strlen(property) <= 1)
{
/*
Do not 'set' single letter properties - read only shorthand.
*/
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
/* FUTURE: binary chars or quotes in key should produce a error */
/* Set attributes with known names or special prefixes
return result is found, or break to set a free form properity
*/
switch (*property)
{
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
case '8':
{
if (LocaleNCompare("8bim:",property,5) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break;
}
#endif
case 'B':
case 'b':
{
if (LocaleCompare("background",property) == 0)
{
(void) QueryColorCompliance(value,AllCompliance,
&image->background_color,exception);
/* check for FUTURE: value exception?? */
/* also add user input to splay tree */
}
break; /* not an attribute, add as a property */
}
case 'C':
case 'c':
{
if (LocaleCompare("channels",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
if (LocaleCompare("colorspace",property) == 0)
{
ssize_t
colorspace;
colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,
value);
if (colorspace < 0)
return(MagickFalse); /* FUTURE: value exception?? */
return(SetImageColorspace(image,(ColorspaceType) colorspace,exception));
}
if (LocaleCompare("compose",property) == 0)
{
ssize_t
compose;
compose=ParseCommandOption(MagickComposeOptions,MagickFalse,value);
if (compose < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->compose=(CompositeOperator) compose;
return(MagickTrue);
}
if (LocaleCompare("compress",property) == 0)
{
ssize_t
compression;
compression=ParseCommandOption(MagickCompressOptions,MagickFalse,
value);
if (compression < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->compression=(CompressionType) compression;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'D':
case 'd':
{
if (LocaleCompare("delay",property) == 0)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(value,&geometry_info);
if ((flags & GreaterValue) != 0)
{
if (image->delay > (size_t) floor(geometry_info.rho+0.5))
image->delay=(size_t) floor(geometry_info.rho+0.5);
}
else
if ((flags & LessValue) != 0)
{
if (image->delay < (size_t) floor(geometry_info.rho+0.5))
image->delay=(ssize_t)
floor(geometry_info.sigma+0.5);
}
else
image->delay=(size_t) floor(geometry_info.rho+0.5);
if ((flags & SigmaValue) != 0)
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
return(MagickTrue);
}
if (LocaleCompare("delay_units",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
if (LocaleCompare("density",property) == 0)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(value,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
return(MagickTrue);
}
if (LocaleCompare("depth",property) == 0)
{
image->depth=StringToUnsignedLong(value);
return(MagickTrue);
}
if (LocaleCompare("dispose",property) == 0)
{
ssize_t
dispose;
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,value);
if (dispose < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->dispose=(DisposeType) dispose;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
case 'E':
case 'e':
{
if (LocaleNCompare("exif:",property,5) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
case 'F':
case 'f':
{
if (LocaleNCompare("fx:",property,3) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
#endif
case 'G':
case 'g':
{
if (LocaleCompare("gamma",property) == 0)
{
image->gamma=StringToDouble(value,(char **) NULL);
return(MagickTrue);
}
if (LocaleCompare("gravity",property) == 0)
{
ssize_t
gravity;
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value);
if (gravity < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->gravity=(GravityType) gravity;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'H':
case 'h':
{
if (LocaleCompare("height",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
case 'I':
case 'i':
{
if (LocaleCompare("intensity",property) == 0)
{
ssize_t
intensity;
intensity=ParseCommandOption(MagickIntentOptions,MagickFalse,value);
if (intensity < 0)
return(MagickFalse);
image->intensity=(PixelIntensityMethod) intensity;
return(MagickTrue);
}
if (LocaleCompare("intent",property) == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse,
value);
if (rendering_intent < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->rendering_intent=(RenderingIntent) rendering_intent;
return(MagickTrue);
}
if (LocaleCompare("interpolate",property) == 0)
{
ssize_t
interpolate;
interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse,
value);
if (interpolate < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->interpolate=(PixelInterpolateMethod) interpolate;
return(MagickTrue);
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
if (LocaleNCompare("iptc:",property,5) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
#endif
break; /* not an attribute, add as a property */
}
case 'K':
case 'k':
if (LocaleCompare("kurtosis",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'L':
case 'l':
{
if (LocaleCompare("loop",property) == 0)
{
image->iterations=StringToUnsignedLong(value);
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'M':
case 'm':
if ((LocaleCompare("magick",property) == 0) ||
(LocaleCompare("max",property) == 0) ||
(LocaleCompare("mean",property) == 0) ||
(LocaleCompare("min",property) == 0) ||
(LocaleCompare("min",property) == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'O':
case 'o':
if (LocaleCompare("opaque",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'P':
case 'p':
{
if (LocaleCompare("page",property) == 0)
{
char
*geometry;
geometry=GetPageGeometry(value);
flags=ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
return(MagickTrue);
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
if (LocaleNCompare("pixel:",property,6) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
#endif
if (LocaleCompare("profile",property) == 0)
{
ImageInfo
*image_info;
StringInfo
*profile;
image_info=AcquireImageInfo();
(void) CopyMagickString(image_info->filename,value,MagickPathExtent);
(void) SetImageInfo(image_info,1,exception);
profile=FileToStringInfo(image_info->filename,~0UL,exception);
if (profile != (StringInfo *) NULL)
status=SetImageProfile(image,image_info->magick,profile,exception);
image_info=DestroyImageInfo(image_info);
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'R':
case 'r':
{
if (LocaleCompare("rendering-intent",property) == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse,
value);
if (rendering_intent < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->rendering_intent=(RenderingIntent) rendering_intent;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'S':
case 's':
if ((LocaleCompare("size",property) == 0) ||
(LocaleCompare("skewness",property) == 0) ||
(LocaleCompare("scenes",property) == 0) ||
(LocaleCompare("standard-deviation",property) == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'T':
case 't':
{
if (LocaleCompare("tile-offset",property) == 0)
{
char
*geometry;
geometry=GetPageGeometry(value);
flags=ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'U':
case 'u':
{
if (LocaleCompare("units",property) == 0)
{
ssize_t
units;
units=ParseCommandOption(MagickResolutionOptions,MagickFalse,value);
if (units < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->units=(ResolutionType) units;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'V':
case 'v':
{
if (LocaleCompare("version",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
case 'W':
case 'w':
{
if (LocaleCompare("width",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
case 'X':
case 'x':
{
if (LocaleNCompare("xmp:",property,4) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
#endif
}
/* Default: not an attribute, add as a property */
status=AddValueToSplayTree((SplayTreeInfo *) image->properties,
ConstantString(property),ConstantString(value));
/* FUTURE: error if status is bad? */
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5485_0 |
crossvul-cpp_data_good_862_0 | /* $Id: upnpsoap.c,v 1.151 2018/03/13 10:32:53 nanard Exp $ */
/* vim: tabstop=4 shiftwidth=4 noexpandtab
* MiniUPnP project
* http://miniupnp.free.fr/ or https://miniupnp.tuxfamily.org/
* (c) 2006-2018 Thomas Bernard
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <unistd.h>
#include <syslog.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <ctype.h>
#include "macros.h"
#include "config.h"
#include "upnpglobalvars.h"
#include "upnphttp.h"
#include "upnpsoap.h"
#include "upnpreplyparse.h"
#include "upnpredirect.h"
#include "upnppinhole.h"
#include "getifaddr.h"
#include "getifstats.h"
#include "getconnstatus.h"
#include "upnpurns.h"
#include "upnputils.h"
/* utility function */
static int is_numeric(const char * s)
{
while(*s) {
if(*s < '0' || *s > '9') return 0;
s++;
}
return 1;
}
static void
BuildSendAndCloseSoapResp(struct upnphttp * h,
const char * body, int bodylen)
{
static const char beforebody[] =
"<?xml version=\"1.0\"?>\r\n"
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body>";
static const char afterbody[] =
"</s:Body>"
"</s:Envelope>\r\n";
int r = BuildHeader_upnphttp(h, 200, "OK", sizeof(beforebody) - 1
+ sizeof(afterbody) - 1 + bodylen );
if(r >= 0) {
memcpy(h->res_buf + h->res_buflen, beforebody, sizeof(beforebody) - 1);
h->res_buflen += sizeof(beforebody) - 1;
memcpy(h->res_buf + h->res_buflen, body, bodylen);
h->res_buflen += bodylen;
memcpy(h->res_buf + h->res_buflen, afterbody, sizeof(afterbody) - 1);
h->res_buflen += sizeof(afterbody) - 1;
} else {
BuildResp2_upnphttp(h, 500, "Internal Server Error", NULL, 0);
}
SendRespAndClose_upnphttp(h);
}
static void
GetConnectionTypeInfo(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:GetConnectionTypeInfoResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"<NewConnectionType>IP_Routed</NewConnectionType>"
"<NewPossibleConnectionTypes>IP_Routed</NewPossibleConnectionTypes>"
"</u:GetConnectionTypeInfoResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewConnectionType>IP_Routed</NewConnectionType>"
"<NewPossibleConnectionTypes>IP_Routed</NewPossibleConnectionTypes>"
"</u:%sResponse>";
char body[512];
int bodylen;
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
/* maximum value for a UPNP ui4 type variable */
#define UPNP_UI4_MAX (4294967295ul)
static void
GetTotalBytesSent(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalBytesSent>%lu</NewTotalBytesSent>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.obytes & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.obytes, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalBytesReceived(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalBytesReceived>%lu</NewTotalBytesReceived>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
/* TotalBytesReceived
* This variable represents the cumulative counter for total number of
* bytes received downstream across all connection service instances on
* WANDevice. The count rolls over to 0 after it reaching the maximum
* value (2^32)-1. */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.ibytes & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.ibytes, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalPacketsSent(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalPacketsSent>%lu</NewTotalPacketsSent>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1",*/
#ifdef UPNP_STRICT
r<0?0:(data.opackets & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.opackets, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalPacketsReceived(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalPacketsReceived>%lu</NewTotalPacketsReceived>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.ipackets & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.ipackets, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetCommonLinkProperties(struct upnphttp * h, const char * action, const char * ns)
{
/* WANAccessType : set depending on the hardware :
* DSL, POTS (plain old Telephone service), Cable, Ethernet */
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewWANAccessType>%s</NewWANAccessType>"
"<NewLayer1UpstreamMaxBitRate>%lu</NewLayer1UpstreamMaxBitRate>"
"<NewLayer1DownstreamMaxBitRate>%lu</NewLayer1DownstreamMaxBitRate>"
"<NewPhysicalLinkStatus>%s</NewPhysicalLinkStatus>"
"</u:%sResponse>";
char body[2048];
int bodylen;
struct ifdata data;
const char * status = "Up"; /* Up, Down (Required),
* Initializing, Unavailable (Optional) */
const char * wan_access_type = "Cable"; /* DSL, POTS, Cable, Ethernet */
char ext_ip_addr[INET_ADDRSTRLEN];
if((downstream_bitrate == 0) || (upstream_bitrate == 0))
{
if(getifstats(ext_if_name, &data) >= 0)
{
if(downstream_bitrate == 0) downstream_bitrate = data.baudrate;
if(upstream_bitrate == 0) upstream_bitrate = data.baudrate;
}
}
if(getifaddr(ext_if_name, ext_ip_addr, INET_ADDRSTRLEN, NULL, NULL) < 0) {
status = "Down";
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
wan_access_type,
upstream_bitrate, downstream_bitrate,
status, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetStatusInfo(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewConnectionStatus>%s</NewConnectionStatus>"
"<NewLastConnectionError>ERROR_NONE</NewLastConnectionError>"
"<NewUptime>%ld</NewUptime>"
"</u:%sResponse>";
char body[512];
int bodylen;
time_t uptime;
const char * status;
/* ConnectionStatus possible values :
* Unconfigured, Connecting, Connected, PendingDisconnect,
* Disconnecting, Disconnected */
status = get_wan_connection_status_str(ext_if_name);
uptime = upnp_get_uptime();
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
status, (long)uptime, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetNATRSIPStatus(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:GetNATRSIPStatusResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"<NewRSIPAvailable>0</NewRSIPAvailable>"
"<NewNATEnabled>1</NewNATEnabled>"
"</u:GetNATRSIPStatusResponse>";
UNUSED(action);
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewRSIPAvailable>0</NewRSIPAvailable>"
"<NewNATEnabled>1</NewNATEnabled>"
"</u:%sResponse>";
char body[512];
int bodylen;
/* 2.2.9. RSIPAvailable
* This variable indicates if Realm-specific IP (RSIP) is available
* as a feature on the InternetGatewayDevice. RSIP is being defined
* in the NAT working group in the IETF to allow host-NATing using
* a standard set of message exchanges. It also allows end-to-end
* applications that otherwise break if NAT is introduced
* (e.g. IPsec-based VPNs).
* A gateway that does not support RSIP should set this variable to 0. */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetExternalIPAddress(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewExternalIPAddress>%s</NewExternalIPAddress>"
"</u:%sResponse>";
char body[512];
int bodylen;
char ext_ip_addr[INET_ADDRSTRLEN];
/* Does that method need to work with IPv6 ?
* There is usually no NAT with IPv6 */
#ifndef MULTIPLE_EXTERNAL_IP
struct in_addr addr;
if(use_ext_ip_addr)
{
strncpy(ext_ip_addr, use_ext_ip_addr, INET_ADDRSTRLEN);
ext_ip_addr[INET_ADDRSTRLEN - 1] = '\0';
}
else if(getifaddr(ext_if_name, ext_ip_addr, INET_ADDRSTRLEN, &addr, NULL) < 0)
{
syslog(LOG_ERR, "Failed to get ip address for interface %s",
ext_if_name);
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
}
if (addr_is_reserved(&addr))
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
#else
struct lan_addr_s * lan_addr;
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
for(lan_addr = lan_addrs.lh_first; lan_addr != NULL; lan_addr = lan_addr->list.le_next)
{
if( (h->clientaddr.s_addr & lan_addr->mask.s_addr)
== (lan_addr->addr.s_addr & lan_addr->mask.s_addr))
{
strncpy(ext_ip_addr, lan_addr->ext_ip_str, INET_ADDRSTRLEN);
break;
}
}
#endif
if (strcmp(ext_ip_addr, "0.0.0.0") == 0)
{
SoapError(h, 501, "Action Failed");
return;
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
ext_ip_addr, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
/* AddPortMapping method of WANIPConnection Service
* Ignored argument : NewEnabled */
static void
AddPortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
/*static const char resp[] =
"<u:AddPortMappingResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\"/>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\"/>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * ext_port, * protocol, * desc;
char * leaseduration_str;
unsigned int leaseduration;
char * r_host;
unsigned short iport, eport;
struct hostent *hp; /* getbyhostname() */
char ** ptr; /* getbyhostname() */
struct in_addr result_ip;/*unsigned char result_ip[16];*/ /* inet_pton() */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "NewInternalClient");
if (int_ip) {
/* trim */
while(int_ip[0] == ' ')
int_ip++;
}
#ifdef UPNP_STRICT
if (!int_ip || int_ip[0] == '\0')
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#endif
/* IGD 2 MUST support both wildcard and specific IP address values
* for RemoteHost (only the wildcard value was REQUIRED in release 1.0) */
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
#ifndef UPNP_STRICT
/* if <NewInternalClient> arg is empty, use client address
* see https://github.com/miniupnp/miniupnp/issues/236 */
if (!int_ip || int_ip[0] == '\0')
{
int_ip = h->clientaddr_str;
memcpy(&result_ip, &(h->clientaddr), sizeof(struct in_addr));
}
else
#endif
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET, int_ip, &result_ip) <= 0)
{
hp = gethostbyname(int_ip);
if(hp && hp->h_addrtype == AF_INET)
{
for(ptr = hp->h_addr_list; ptr && *ptr; ptr++)
{
int_ip = inet_ntoa(*((struct in_addr *) *ptr));
result_ip = *((struct in_addr *) *ptr);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
}
/* check if NewInternalAddress is the client address */
if(GETFLAG(SECUREMODEMASK))
{
if(h->clientaddr.s_addr != result_ip.s_addr)
{
syslog(LOG_INFO, "Client %s tried to redirect port to %s",
inet_ntoa(h->clientaddr), int_ip);
ClearNameValueList(&data);
SoapError(h, 718, "ConflictInMappingEntry");
return;
}
}
int_port = GetValueFromNameValueList(&data, "NewInternalPort");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
desc = GetValueFromNameValueList(&data, "NewPortMappingDescription");
leaseduration_str = GetValueFromNameValueList(&data, "NewLeaseDuration");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
eport = (unsigned short)atoi(ext_port);
iport = (unsigned short)atoi(int_port);
if (strcmp(ext_port, "*") == 0 || eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 716, "Wildcard not permited in ExtPort");
return;
}
leaseduration = leaseduration_str ? atoi(leaseduration_str) : 0;
#ifdef IGD_V2
/* PortMappingLeaseDuration can be either a value between 1 and
* 604800 seconds or the zero value (for infinite lease time).
* Note that an infinite lease time can be only set by out-of-band
* mechanisms like WWW-administration, remote management or local
* management.
* If a control point uses the value 0 to indicate an infinite lease
* time mapping, it is REQUIRED that gateway uses the maximum value
* instead (e.g. 604800 seconds) */
if(leaseduration == 0 || leaseduration > 604800)
leaseduration = 604800;
#endif
syslog(LOG_INFO, "%s: ext port %hu to %s:%hu protocol %s for: %s leaseduration=%u rhost=%s",
action, eport, int_ip, iport, protocol, desc, leaseduration,
r_host ? r_host : "NULL");
r = upnp_redirect(r_host, eport, int_ip, iport, protocol, desc, leaseduration);
ClearNameValueList(&data);
/* possible error codes for AddPortMapping :
* 402 - Invalid Args
* 501 - Action Failed
* 715 - Wildcard not permited in SrcAddr
* 716 - Wildcard not permited in ExtPort
* 718 - ConflictInMappingEntry
* 724 - SamePortValuesRequired (deprecated in IGD v2)
* 725 - OnlyPermanentLeasesSupported
The NAT implementation only supports permanent lease times on
port mappings (deprecated in IGD v2)
* 726 - RemoteHostOnlySupportsWildcard
RemoteHost must be a wildcard and cannot be a specific IP
address or DNS name (deprecated in IGD v2)
* 727 - ExternalPortOnlySupportsWildcard
ExternalPort must be a wildcard and cannot be a specific port
value (deprecated in IGD v2)
* 728 - NoPortMapsAvailable
There are not enough free ports available to complete the mapping
(added in IGD v2)
* 729 - ConflictWithOtherMechanisms (added in IGD v2) */
switch(r)
{
case 0: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*SERVICE_TYPE_WANIPC*/);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -4:
#ifdef IGD_V2
SoapError(h, 729, "ConflictWithOtherMechanisms");
break;
#endif /* IGD_V2 */
case -2: /* already redirected */
case -3: /* not permitted */
SoapError(h, 718, "ConflictInMappingEntry");
break;
default:
SoapError(h, 501, "ActionFailed");
}
}
/* AddAnyPortMapping was added in WANIPConnection v2 */
static void
AddAnyPortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewReservedPort>%hu</NewReservedPort>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * int_ip, * int_port, * ext_port, * protocol, * desc;
const char * r_host;
unsigned short iport, eport;
const char * leaseduration_str;
unsigned int leaseduration;
struct hostent *hp; /* getbyhostname() */
char ** ptr; /* getbyhostname() */
struct in_addr result_ip;/*unsigned char result_ip[16];*/ /* inet_pton() */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
int_port = GetValueFromNameValueList(&data, "NewInternalPort");
int_ip = GetValueFromNameValueList(&data, "NewInternalClient");
/* NewEnabled */
desc = GetValueFromNameValueList(&data, "NewPortMappingDescription");
leaseduration_str = GetValueFromNameValueList(&data, "NewLeaseDuration");
leaseduration = leaseduration_str ? atoi(leaseduration_str) : 0;
if(leaseduration == 0)
leaseduration = 604800;
if (!int_ip || !ext_port || !int_port)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
eport = (unsigned short)atoi(ext_port);
iport = (unsigned short)atoi(int_port);
if(iport == 0 || !is_numeric(ext_port)) {
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET, int_ip, &result_ip) <= 0)
{
hp = gethostbyname(int_ip);
if(hp && hp->h_addrtype == AF_INET)
{
for(ptr = hp->h_addr_list; ptr && *ptr; ptr++)
{
int_ip = inet_ntoa(*((struct in_addr *) *ptr));
result_ip = *((struct in_addr *) *ptr);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
}
/* check if NewInternalAddress is the client address */
if(GETFLAG(SECUREMODEMASK))
{
if(h->clientaddr.s_addr != result_ip.s_addr)
{
syslog(LOG_INFO, "Client %s tried to redirect port to %s",
inet_ntoa(h->clientaddr), int_ip);
ClearNameValueList(&data);
SoapError(h, 606, "Action not authorized");
return;
}
}
/* TODO : accept a different external port
* have some smart strategy to choose the port */
for(;;) {
r = upnp_redirect(r_host, eport, int_ip, iport, protocol, desc, leaseduration);
if(r==-2 && eport < 65535) {
eport++;
} else {
break;
}
}
ClearNameValueList(&data);
switch(r)
{
case 0: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
eport, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -2: /* already redirected */
SoapError(h, 718, "ConflictInMappingEntry");
break;
case -3: /* not permitted */
SoapError(h, 606, "Action not authorized");
break;
default:
SoapError(h, 501, "ActionFailed");
}
}
static void
GetSpecificPortMappingEntry(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewInternalPort>%u</NewInternalPort>"
"<NewInternalClient>%s</NewInternalClient>"
"<NewEnabled>1</NewEnabled>"
"<NewPortMappingDescription>%s</NewPortMappingDescription>"
"<NewLeaseDuration>%u</NewLeaseDuration>"
"</u:%sResponse>";
char body[1024];
int bodylen;
struct NameValueParserData data;
const char * r_host, * ext_port, * protocol;
unsigned short eport, iport;
char int_ip[32];
char desc[64];
unsigned int leaseduration = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
#ifdef UPNP_STRICT
if(!ext_port || !protocol || !r_host)
#else
if(!ext_port || !protocol)
#endif
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
eport = (unsigned short)atoi(ext_port);
if(eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
/* TODO : add r_host as an input parameter ...
* We prevent several Port Mapping with same external port
* but different remoteHost to be set up, so that is not
* a priority. */
r = upnp_get_redirection_infos(eport, protocol, &iport,
int_ip, sizeof(int_ip),
desc, sizeof(desc),
NULL, 0,
&leaseduration);
if(r < 0)
{
SoapError(h, 714, "NoSuchEntryInArray");
}
else
{
syslog(LOG_INFO, "%s: rhost='%s' %s %s found => %s:%u desc='%s'",
action,
r_host ? r_host : "NULL", ext_port, protocol, int_ip,
(unsigned int)iport, desc);
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*SERVICE_TYPE_WANIPC*/,
(unsigned int)iport, int_ip, desc, leaseduration,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
static void
DeletePortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
/*static const char resp[] =
"<u:DeletePortMappingResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"</u:DeletePortMappingResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * ext_port, * protocol;
unsigned short eport;
#ifdef UPNP_STRICT
const char * r_host;
#endif /* UPNP_STRICT */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
#ifdef UPNP_STRICT
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
#endif /* UPNP_STRICT */
#ifdef UPNP_STRICT
if(!ext_port || !protocol || !r_host)
#else
if(!ext_port || !protocol)
#endif /* UPNP_STRICT */
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif /* UPNP_STRICT */
#endif /* SUPPORT_REMOTEHOST */
eport = (unsigned short)atoi(ext_port);
if(eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
syslog(LOG_INFO, "%s: external port: %hu, protocol: %s",
action, eport, protocol);
/* if in secure mode, check the IP
* Removing a redirection is not a security threat,
* just an annoyance for the user using it. So this is not
* a priority. */
if(GETFLAG(SECUREMODEMASK))
{
char int_ip[32];
struct in_addr int_ip_addr;
unsigned short iport;
unsigned int leaseduration = 0;
r = upnp_get_redirection_infos(eport, protocol, &iport,
int_ip, sizeof(int_ip),
NULL, 0, NULL, 0,
&leaseduration);
if(r >= 0)
{
if(inet_pton(AF_INET, int_ip, &int_ip_addr) > 0)
{
if(h->clientaddr.s_addr != int_ip_addr.s_addr)
{
SoapError(h, 606, "Action not authorized");
/*SoapError(h, 714, "NoSuchEntryInArray");*/
ClearNameValueList(&data);
return;
}
}
}
}
r = upnp_delete_redirection(eport, protocol);
if(r < 0)
{
SoapError(h, 714, "NoSuchEntryInArray");
}
else
{
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
/* DeletePortMappingRange was added in IGD spec v2 */
static void
DeletePortMappingRange(struct upnphttp * h, const char * action, const char * ns)
{
int r = -1;
/*static const char resp[] =
"<u:DeletePortMappingRangeResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"</u:DeletePortMappingRangeResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * protocol;
const char * startport_s, * endport_s;
unsigned short startport, endport;
/*int manage;*/
unsigned short * port_list;
unsigned int i, number = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
startport_s = GetValueFromNameValueList(&data, "NewStartPort");
endport_s = GetValueFromNameValueList(&data, "NewEndPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
/*manage = atoi(GetValueFromNameValueList(&data, "NewManage"));*/
if(startport_s == NULL || endport_s == NULL || protocol == NULL ||
!is_numeric(startport_s) || !is_numeric(endport_s)) {
SoapError(h, 402, "Invalid Args");
ClearNameValueList(&data);
return;
}
startport = (unsigned short)atoi(startport_s);
endport = (unsigned short)atoi(endport_s);
/* possible errors :
606 - Action not authorized
730 - PortMappingNotFound
733 - InconsistentParameter
*/
if(startport > endport)
{
SoapError(h, 733, "InconsistentParameter");
ClearNameValueList(&data);
return;
}
syslog(LOG_INFO, "%s: deleting external ports: %hu-%hu, protocol: %s",
action, startport, endport, protocol);
port_list = upnp_get_portmappings_in_range(startport, endport,
protocol, &number);
if(number == 0)
{
SoapError(h, 730, "PortMappingNotFound");
ClearNameValueList(&data);
free(port_list);
return;
}
for(i = 0; i < number; i++)
{
r = upnp_delete_redirection(port_list[i], protocol);
syslog(LOG_INFO, "%s: deleting external port: %hu, protocol: %s: %s",
action, port_list[i], protocol, r < 0 ? "failed" : "ok");
}
free(port_list);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
ClearNameValueList(&data);
}
static void
GetGenericPortMappingEntry(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewRemoteHost>%s</NewRemoteHost>"
"<NewExternalPort>%u</NewExternalPort>"
"<NewProtocol>%s</NewProtocol>"
"<NewInternalPort>%u</NewInternalPort>"
"<NewInternalClient>%s</NewInternalClient>"
"<NewEnabled>1</NewEnabled>"
"<NewPortMappingDescription>%s</NewPortMappingDescription>"
"<NewLeaseDuration>%u</NewLeaseDuration>"
"</u:%sResponse>";
long int index = 0;
unsigned short eport, iport;
const char * m_index;
char * endptr;
char protocol[8], iaddr[32];
char desc[64];
char rhost[40];
unsigned int leaseduration = 0;
struct NameValueParserData data;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
m_index = GetValueFromNameValueList(&data, "NewPortMappingIndex");
if(!m_index)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
errno = 0; /* To distinguish success/failure after call */
index = strtol(m_index, &endptr, 10);
if((errno == ERANGE && (index == LONG_MAX || index == LONG_MIN))
|| (errno != 0 && index == 0) || (m_index == endptr))
{
/* should condition (*endptr != '\0') be also an error ? */
if(m_index == endptr)
syslog(LOG_WARNING, "%s: no digits were found in <%s>",
"GetGenericPortMappingEntry", "NewPortMappingIndex");
else
syslog(LOG_WARNING, "%s: strtol('%s'): %m",
"GetGenericPortMappingEntry", m_index);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
syslog(LOG_INFO, "%s: index=%d", action, (int)index);
rhost[0] = '\0';
r = upnp_get_redirection_infos_by_index((int)index, &eport, protocol, &iport,
iaddr, sizeof(iaddr),
desc, sizeof(desc),
rhost, sizeof(rhost),
&leaseduration);
if(r < 0)
{
SoapError(h, 713, "SpecifiedArrayIndexInvalid");
}
else
{
int bodylen;
char body[2048];
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/ rhost,
(unsigned int)eport, protocol, (unsigned int)iport, iaddr, desc,
leaseduration, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
/* GetListOfPortMappings was added in the IGD v2 specification */
static void
GetListOfPortMappings(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp_start[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewPortListing><![CDATA[";
static const char resp_end[] =
"]]></NewPortListing>"
"</u:%sResponse>";
static const char list_start[] =
"<p:PortMappingList xmlns:p=\"urn:schemas-upnp-org:gw:WANIPConnection\""
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
" xsi:schemaLocation=\"urn:schemas-upnp-org:gw:WANIPConnection"
" http://www.upnp.org/schemas/gw/WANIPConnection-v2.xsd\">";
static const char list_end[] =
"</p:PortMappingList>";
static const char entry[] =
"<p:PortMappingEntry>"
"<p:NewRemoteHost>%s</p:NewRemoteHost>"
"<p:NewExternalPort>%hu</p:NewExternalPort>"
"<p:NewProtocol>%s</p:NewProtocol>"
"<p:NewInternalPort>%hu</p:NewInternalPort>"
"<p:NewInternalClient>%s</p:NewInternalClient>"
"<p:NewEnabled>1</p:NewEnabled>"
"<p:NewDescription>%s</p:NewDescription>"
"<p:NewLeaseTime>%u</p:NewLeaseTime>"
"</p:PortMappingEntry>";
char * body;
size_t bodyalloc;
int bodylen;
int r = -1;
unsigned short iport;
char int_ip[32];
char desc[64];
char rhost[64];
unsigned int leaseduration = 0;
struct NameValueParserData data;
const char * startport_s, * endport_s;
unsigned short startport, endport;
const char * protocol;
/*int manage;*/
const char * number_s;
int number;
unsigned short * port_list;
unsigned int i, list_size = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
startport_s = GetValueFromNameValueList(&data, "NewStartPort");
endport_s = GetValueFromNameValueList(&data, "NewEndPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
/*manage_s = GetValueFromNameValueList(&data, "NewManage");*/
number_s = GetValueFromNameValueList(&data, "NewNumberOfPorts");
if(startport_s == NULL || endport_s == NULL || protocol == NULL ||
number_s == NULL || !is_numeric(number_s) ||
!is_numeric(startport_s) || !is_numeric(endport_s)) {
SoapError(h, 402, "Invalid Args");
ClearNameValueList(&data);
return;
}
startport = (unsigned short)atoi(startport_s);
endport = (unsigned short)atoi(endport_s);
/*manage = atoi(manage_s);*/
number = atoi(number_s);
if(number == 0) number = 1000; /* return up to 1000 mappings by default */
if(startport > endport)
{
SoapError(h, 733, "InconsistentParameter");
ClearNameValueList(&data);
return;
}
/*
build the PortMappingList xml document :
<p:PortMappingList xmlns:p="urn:schemas-upnp-org:gw:WANIPConnection"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:schemas-upnp-org:gw:WANIPConnection
http://www.upnp.org/schemas/gw/WANIPConnection-v2.xsd">
<p:PortMappingEntry>
<p:NewRemoteHost>202.233.2.1</p:NewRemoteHost>
<p:NewExternalPort>2345</p:NewExternalPort>
<p:NewProtocol>TCP</p:NewProtocol>
<p:NewInternalPort>2345</p:NewInternalPort>
<p:NewInternalClient>192.168.1.137</p:NewInternalClient>
<p:NewEnabled>1</p:NewEnabled>
<p:NewDescription>dooom</p:NewDescription>
<p:NewLeaseTime>345</p:NewLeaseTime>
</p:PortMappingEntry>
</p:PortMappingList>
*/
bodyalloc = 4096;
body = malloc(bodyalloc);
if(!body)
{
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
return;
}
bodylen = snprintf(body, bodyalloc, resp_start,
action, ns/*SERVICE_TYPE_WANIPC*/);
if(bodylen < 0)
{
SoapError(h, 501, "ActionFailed");
free(body);
return;
}
memcpy(body+bodylen, list_start, sizeof(list_start));
bodylen += (sizeof(list_start) - 1);
port_list = upnp_get_portmappings_in_range(startport, endport,
protocol, &list_size);
/* loop through port mappings */
for(i = 0; number > 0 && i < list_size; i++)
{
/* have a margin of 1024 bytes to store the new entry */
if((unsigned int)bodylen + 1024 > bodyalloc)
{
char * body_sav = body;
bodyalloc += 4096;
body = realloc(body, bodyalloc);
if(!body)
{
syslog(LOG_CRIT, "realloc(%p, %u) FAILED", body_sav, (unsigned)bodyalloc);
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
free(body_sav);
free(port_list);
return;
}
}
rhost[0] = '\0';
r = upnp_get_redirection_infos(port_list[i], protocol, &iport,
int_ip, sizeof(int_ip),
desc, sizeof(desc),
rhost, sizeof(rhost),
&leaseduration);
if(r == 0)
{
bodylen += snprintf(body+bodylen, bodyalloc-bodylen, entry,
rhost, port_list[i], protocol,
iport, int_ip, desc, leaseduration);
number--;
}
}
free(port_list);
port_list = NULL;
if((bodylen + sizeof(list_end) + 1024) > bodyalloc)
{
char * body_sav = body;
bodyalloc += (sizeof(list_end) + 1024);
body = realloc(body, bodyalloc);
if(!body)
{
syslog(LOG_CRIT, "realloc(%p, %u) FAILED", body_sav, (unsigned)bodyalloc);
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
free(body_sav);
return;
}
}
memcpy(body+bodylen, list_end, sizeof(list_end));
bodylen += (sizeof(list_end) - 1);
bodylen += snprintf(body+bodylen, bodyalloc-bodylen, resp_end,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
free(body);
ClearNameValueList(&data);
}
#ifdef ENABLE_L3F_SERVICE
static void
SetDefaultConnectionService(struct upnphttp * h, const char * action, const char * ns)
{
/*static const char resp[] =
"<u:SetDefaultConnectionServiceResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:Layer3Forwarding:1\">"
"</u:SetDefaultConnectionServiceResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * p;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
p = GetValueFromNameValueList(&data, "NewDefaultConnectionService");
if(p) {
/* 720 InvalidDeviceUUID
* 721 InvalidServiceID
* 723 InvalidConnServiceSelection */
#ifdef UPNP_STRICT
char * service;
service = strchr(p, ',');
if(0 != memcmp(uuidvalue_wcd, p, sizeof("uuid:00000000-0000-0000-0000-000000000000") - 1)) {
SoapError(h, 720, "InvalidDeviceUUID");
} else if(service == NULL || 0 != strcmp(service+1, SERVICE_ID_WANIPC)) {
SoapError(h, 721, "InvalidServiceID");
} else
#endif
{
syslog(LOG_INFO, "%s(%s) : Ignored", action, p);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
} else {
/* missing argument */
SoapError(h, 402, "Invalid Args");
}
ClearNameValueList(&data);
}
static void
GetDefaultConnectionService(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
#ifdef IGD_V2
"<NewDefaultConnectionService>%s:WANConnectionDevice:2,"
#else
"<NewDefaultConnectionService>%s:WANConnectionDevice:1,"
#endif
SERVICE_ID_WANIPC "</NewDefaultConnectionService>"
"</u:%sResponse>";
/* example from UPnP_IGD_Layer3Forwarding 1.0.pdf :
* uuid:44f5824f-c57d-418c-a131-f22b34e14111:WANConnectionDevice:1,
* urn:upnp-org:serviceId:WANPPPConn1 */
char body[1024];
int bodylen;
/* namespace : urn:schemas-upnp-org:service:Layer3Forwarding:1 */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, uuidvalue_wcd, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
/* Added for compliance with WANIPConnection v2 */
static void
SetConnectionType(struct upnphttp * h, const char * action, const char * ns)
{
#ifdef UPNP_STRICT
const char * connection_type;
#endif /* UPNP_STRICT */
struct NameValueParserData data;
UNUSED(action);
UNUSED(ns);
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
#ifdef UPNP_STRICT
connection_type = GetValueFromNameValueList(&data, "NewConnectionType");
if(!connection_type) {
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#endif /* UPNP_STRICT */
/* Unconfigured, IP_Routed, IP_Bridged */
ClearNameValueList(&data);
/* always return a ReadOnly error */
SoapError(h, 731, "ReadOnly");
}
/* Added for compliance with WANIPConnection v2 */
static void
RequestConnection(struct upnphttp * h, const char * action, const char * ns)
{
UNUSED(action);
UNUSED(ns);
SoapError(h, 606, "Action not authorized");
}
/* Added for compliance with WANIPConnection v2 */
static void
ForceTermination(struct upnphttp * h, const char * action, const char * ns)
{
UNUSED(action);
UNUSED(ns);
SoapError(h, 606, "Action not authorized");
}
/*
If a control point calls QueryStateVariable on a state variable that is not
buffered in memory within (or otherwise available from) the service,
the service must return a SOAP fault with an errorCode of 404 Invalid Var.
QueryStateVariable remains useful as a limited test tool but may not be
part of some future versions of UPnP.
*/
static void
QueryStateVariable(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<return>%s</return>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * var_name;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
/*var_name = GetValueFromNameValueList(&data, "QueryStateVariable"); */
/*var_name = GetValueFromNameValueListIgnoreNS(&data, "varName");*/
var_name = GetValueFromNameValueList(&data, "varName");
/*syslog(LOG_INFO, "QueryStateVariable(%.40s)", var_name); */
if(!var_name)
{
SoapError(h, 402, "Invalid Args");
}
else if(strcmp(var_name, "ConnectionStatus") == 0)
{
const char * status;
status = get_wan_connection_status_str(ext_if_name);
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:control-1-0",*/
status, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#if 0
/* not useful */
else if(strcmp(var_name, "ConnectionType") == 0)
{
bodylen = snprintf(body, sizeof(body), resp, "IP_Routed");
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else if(strcmp(var_name, "LastConnectionError") == 0)
{
bodylen = snprintf(body, sizeof(body), resp, "ERROR_NONE");
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
else if(strcmp(var_name, "PortMappingNumberOfEntries") == 0)
{
char strn[10];
snprintf(strn, sizeof(strn), "%i",
upnp_get_portmapping_number_of_entries());
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:control-1-0",*/
strn, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else
{
syslog(LOG_NOTICE, "%s: Unknown: %s", action, var_name?var_name:"");
SoapError(h, 404, "Invalid Var");
}
ClearNameValueList(&data);
}
#ifdef ENABLE_6FC_SERVICE
#ifndef ENABLE_IPV6
#error "ENABLE_6FC_SERVICE needs ENABLE_IPV6"
#endif
/* WANIPv6FirewallControl actions */
static void
GetFirewallStatus(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<FirewallEnabled>%d</FirewallEnabled>"
"<InboundPinholeAllowed>%d</InboundPinholeAllowed>"
"</u:%sResponse>";
char body[512];
int bodylen;
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1",*/
GETFLAG(IPV6FCFWDISABLEDMASK) ? 0 : 1,
GETFLAG(IPV6FCINBOUNDDISALLOWEDMASK) ? 0 : 1,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static int
CheckStatus(struct upnphttp * h)
{
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return 0;
}
else if(GETFLAG(IPV6FCINBOUNDDISALLOWEDMASK))
{
SoapError(h, 703, "InboundPinholeNotAllowed");
return 0;
}
else
return 1;
}
#if 0
static int connecthostport(const char * host, unsigned short port, char * result)
{
int s, n;
char hostname[INET6_ADDRSTRLEN];
char port_str[8], ifname[8], tmp[4];
struct addrinfo *ai, *p;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
/* hints.ai_flags = AI_ADDRCONFIG; */
#ifdef AI_NUMERICSERV
hints.ai_flags = AI_NUMERICSERV;
#endif
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC; /* AF_INET, AF_INET6 or AF_UNSPEC */
/* hints.ai_protocol = IPPROTO_TCP; */
snprintf(port_str, sizeof(port_str), "%hu", port);
strcpy(hostname, host);
if(!strncmp(host, "fe80", 4))
{
printf("Using an linklocal address\n");
strcpy(ifname, "%");
snprintf(tmp, sizeof(tmp), "%d", linklocal_index);
strcat(ifname, tmp);
strcat(hostname, ifname);
printf("host: %s\n", hostname);
}
n = getaddrinfo(hostname, port_str, &hints, &ai);
if(n != 0)
{
fprintf(stderr, "getaddrinfo() error : %s\n", gai_strerror(n));
return -1;
}
s = -1;
for(p = ai; p; p = p->ai_next)
{
#ifdef DEBUG
char tmp_host[256];
char tmp_service[256];
printf("ai_family=%d ai_socktype=%d ai_protocol=%d ai_addrlen=%d\n ",
p->ai_family, p->ai_socktype, p->ai_protocol, p->ai_addrlen);
getnameinfo(p->ai_addr, p->ai_addrlen, tmp_host, sizeof(tmp_host),
tmp_service, sizeof(tmp_service),
NI_NUMERICHOST | NI_NUMERICSERV);
printf(" host=%s service=%s\n", tmp_host, tmp_service);
#endif
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr), result, INET6_ADDRSTRLEN);
return 0;
}
freeaddrinfo(ai);
}
#endif
/* Check the security policy right */
static int
PinholeVerification(struct upnphttp * h, char * int_ip, unsigned short int_port)
{
int n;
char senderAddr[INET6_ADDRSTRLEN]="";
struct addrinfo hints, *ai, *p;
struct in6_addr result_ip;
/* Pinhole InternalClient address must correspond to the action sender */
syslog(LOG_INFO, "Checking internal IP@ and port (Security policy purpose)");
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET6, int_ip, &result_ip) <= 0)
{
n = getaddrinfo(int_ip, NULL, &hints, &ai);
if(!n && ai->ai_family == AF_INET6)
{
for(p = ai; p; p = p->ai_next)
{
inet_ntop(AF_INET6, (struct in6_addr *) p, int_ip, sizeof(struct in6_addr));
result_ip = *((struct in6_addr *) p);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
SoapError(h, 402, "Invalid Args");
return -1;
}
freeaddrinfo(p);
}
if(inet_ntop(AF_INET6, &(h->clientaddr_v6), senderAddr, INET6_ADDRSTRLEN) == NULL)
{
syslog(LOG_ERR, "inet_ntop: %m");
}
#ifdef DEBUG
printf("\tPinholeVerification:\n\t\tCompare sender @: %s\n\t\t to intClient @: %s\n", senderAddr, int_ip);
#endif
if(strcmp(senderAddr, int_ip) != 0)
if(h->clientaddr_v6.s6_addr != result_ip.s6_addr)
{
syslog(LOG_INFO, "Client %s tried to access pinhole for internal %s and is not authorized to do it",
senderAddr, int_ip);
SoapError(h, 606, "Action not authorized");
return 0;
}
/* Pinhole InternalPort must be greater than or equal to 1024 */
if (int_port < 1024)
{
syslog(LOG_INFO, "Client %s tried to access pinhole with port < 1024 and is not authorized to do it",
senderAddr);
SoapError(h, 606, "Action not authorized");
return 0;
}
return 1;
}
static void
AddPinhole(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<UniqueID>%d</UniqueID>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * rem_host, * rem_port, * int_ip, * int_port, * protocol, * leaseTime;
int uid = 0;
unsigned short iport, rport;
int ltime;
long proto;
char rem_ip[INET6_ADDRSTRLEN];
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
protocol = GetValueFromNameValueList(&data, "Protocol");
leaseTime = GetValueFromNameValueList(&data, "LeaseTime");
rport = (unsigned short)(rem_port ? atoi(rem_port) : 0);
iport = (unsigned short)(int_port ? atoi(int_port) : 0);
ltime = leaseTime ? atoi(leaseTime) : -1;
errno = 0;
proto = protocol ? strtol(protocol, NULL, 0) : -1;
if(errno != 0 || proto > 65535 || proto < 0)
{
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
}
if(iport == 0)
{
SoapError(h, 706, "InternalPortWilcardingNotAllowed");
goto clear_and_exit;
}
/* In particular, [IGD2] RECOMMENDS that unauthenticated and
* unauthorized control points are only allowed to invoke
* this action with:
* - InternalPort value greater than or equal to 1024,
* - InternalClient value equals to the control point's IP address.
* It is REQUIRED that InternalClient cannot be one of IPv6
* addresses used by the gateway. */
if(!int_ip || int_ip[0] == '\0' || 0 == strcmp(int_ip, "*"))
{
SoapError(h, 708, "WildCardNotPermittedInSrcIP");
goto clear_and_exit;
}
/* I guess it is useless to convert int_ip to literal ipv6 address */
if(rem_host)
{
/* trim */
while(isspace(rem_host[0]))
rem_host++;
}
/* rem_host should be converted to literal ipv6 : */
if(rem_host && (rem_host[0] != '\0') && (rem_host[0] != '*'))
{
struct addrinfo *ai, *p;
struct addrinfo hints;
int err;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET6;
/*hints.ai_flags = */
/* hints.ai_protocol = proto; */
err = getaddrinfo(rem_host, rem_port, &hints, &ai);
if(err == 0)
{
/* take the 1st IPv6 address */
for(p = ai; p; p = p->ai_next)
{
if(p->ai_family == AF_INET6)
{
inet_ntop(AF_INET6,
&(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr),
rem_ip, sizeof(rem_ip));
syslog(LOG_INFO, "resolved '%s' to '%s'", rem_host, rem_ip);
rem_host = rem_ip;
break;
}
}
freeaddrinfo(ai);
}
else
{
syslog(LOG_WARNING, "AddPinhole : getaddrinfo(%s) : %s",
rem_host, gai_strerror(err));
#if 0
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
#endif
}
}
if(proto == 65535)
{
SoapError(h, 707, "ProtocolWilcardingNotAllowed");
goto clear_and_exit;
}
if(proto != IPPROTO_UDP && proto != IPPROTO_TCP
#ifdef IPPROTO_UDPITE
&& atoi(protocol) != IPPROTO_UDPLITE
#endif
)
{
SoapError(h, 705, "ProtocolNotSupported");
goto clear_and_exit;
}
if(ltime < 1 || ltime > 86400)
{
syslog(LOG_WARNING, "%s: LeaseTime=%d not supported, (ip=%s)",
action, ltime, int_ip);
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
}
if(PinholeVerification(h, int_ip, iport) <= 0)
goto clear_and_exit;
syslog(LOG_INFO, "%s: (inbound) from [%s]:%hu to [%s]:%hu with proto %ld during %d sec",
action, rem_host?rem_host:"any",
rport, int_ip, iport,
proto, ltime);
/* In cases where the RemoteHost, RemotePort, InternalPort,
* InternalClient and Protocol are the same than an existing pinhole,
* but LeaseTime is different, the device MUST extend the existing
* pinhole's lease time and return the UniqueID of the existing pinhole. */
r = upnp_add_inboundpinhole(rem_host, rport, int_ip, iport, proto, "IGD2 pinhole", ltime, &uid);
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body),
resp, action,
ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
uid, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -1: /* not permitted */
SoapError(h, 701, "PinholeSpaceExhausted");
break;
default:
SoapError(h, 501, "ActionFailed");
break;
}
/* 606 Action not authorized
* 701 PinholeSpaceExhausted
* 702 FirewallDisabled
* 703 InboundPinholeNotAllowed
* 705 ProtocolNotSupported
* 706 InternalPortWildcardingNotAllowed
* 707 ProtocolWildcardingNotAllowed
* 708 WildCardNotPermittedInSrcIP */
clear_and_exit:
ClearNameValueList(&data);
}
static void
UpdatePinhole(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:UpdatePinholeResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\">"
"</u:UpdatePinholeResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str, * leaseTime;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
int ltime;
int uid;
int n;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
leaseTime = GetValueFromNameValueList(&data, "NewLeaseTime");
uid = uid_str ? atoi(uid_str) : -1;
ltime = leaseTime ? atoi(leaseTime) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535 || ltime <= 0 || ltime > 86400)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not updating an pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
NULL, /* proto */
NULL, 0, /* desc, desclen */
NULL, NULL);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return;
}
else if(n == -2)
{
SoapError(h, 704, "NoSuchEntry");
return;
}
else
{
SoapError(h, 501, "ActionFailed");
return;
}
syslog(LOG_INFO, "%s: (inbound) updating lease duration to %d for pinhole with ID: %d",
action, ltime, uid);
n = upnp_update_inboundpinhole(uid, ltime);
if(n == -1)
SoapError(h, 704, "NoSuchEntry");
else if(n < 0)
SoapError(h, 501, "ActionFailed");
else {
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
}
static void
GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
if (!int_port || !rem_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
static void
DeletePinhole(struct upnphttp * h, const char * action, const char * ns)
{
int n;
#if 0
static const char resp[] =
"<u:DeletePinholeResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\">"
"</u:DeletePinholeResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str;
char iaddr[INET6_ADDRSTRLEN];
int proto;
unsigned short iport;
unsigned int leasetime;
int uid;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not deleting an pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
&proto,
NULL, 0, /* desc, desclen */
&leasetime, NULL);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return;
}
else if(n == -2)
{
SoapError(h, 704, "NoSuchEntry");
return;
}
else
{
SoapError(h, 501, "ActionFailed");
return;
}
n = upnp_delete_inboundpinhole(uid);
if(n < 0)
{
syslog(LOG_INFO, "%s: (inbound) failed to remove pinhole with ID: %d",
action, uid);
SoapError(h, 501, "ActionFailed");
return;
}
syslog(LOG_INFO, "%s: (inbound) pinhole with ID %d successfully removed",
action, uid);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
CheckPinholeWorking(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<IsWorking>%d</IsWorking>"
"</u:%sResponse>";
char body[512];
int bodylen;
int r;
struct NameValueParserData data;
const char * uid_str;
int uid;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
unsigned int packets;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not checking a pinhole
* it doesn't have access to, because of its public access */
r = upnp_get_pinhole_info(uid,
NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
NULL, /* proto */
NULL, 0, /* desc, desclen */
NULL, &packets);
if (r >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return ;
if(packets == 0)
{
SoapError(h, 709, "NoPacketSent");
return;
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
1, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else if(r == -2)
SoapError(h, 704, "NoSuchEntry");
else
SoapError(h, 501, "ActionFailed");
}
static void
GetPinholePackets(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<PinholePackets>%u</PinholePackets>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str;
int n;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
unsigned int packets = 0;
int uid;
int proto;
unsigned int leasetime;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not getting infos of a pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
&proto,
NULL, 0, /* desc, desclen */
&leasetime, &packets);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport)<=0)
return ;
}
#if 0
else if(r == -4 || r == -1)
{
SoapError(h, 704, "NoSuchEntry");
}
#endif
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
packets, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
#ifdef ENABLE_DP_SERVICE
static void
SendSetupMessage(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutMessage>%s</OutMessage>"
"</u:%sResponse>";
char body[1024];
int bodylen;
struct NameValueParserData data;
const char * ProtocolType; /* string */
const char * InMessage; /* base64 */
const char * OutMessage = ""; /* base64 */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
ProtocolType = GetValueFromNameValueList(&data, "ProtocolType"); /* string */
InMessage = GetValueFromNameValueList(&data, "InMessage"); /* base64 */
if(ProtocolType == NULL || InMessage == NULL)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
/*if(strcmp(ProtocolType, "DeviceProtection:1") != 0)*/
if(strcmp(ProtocolType, "WPS") != 0)
{
ClearNameValueList(&data);
SoapError(h, 600, "Argument Value Invalid"); /* 703 ? */
return;
}
/* TODO : put here code for WPS */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
OutMessage, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
ClearNameValueList(&data);
}
static void
GetSupportedProtocols(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<ProtocolList><![CDATA[%s]]></ProtocolList>"
"</u:%sResponse>";
char body[1024];
int bodylen;
const char * ProtocolList =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<SupportedProtocols xmlns=\"urn:schemas-upnp-org:gw:DeviceProtection\""
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
" xsi:schemaLocation=\"urn:schemas-upnp-org:gw:DeviceProtection"
" http://www.upnp.org/schemas/gw/DeviceProtection-v1.xsd\">"
"<Introduction><Name>WPS</Name></Introduction>"
"<Login><Name>PKCS5</Name></Login>"
"</SupportedProtocols>";
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
ProtocolList, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetAssignedRoles(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<RoleList>%s</RoleList>"
"</u:%sResponse>";
char body[1024];
int bodylen;
const char * RoleList = "Public"; /* list of roles separated by spaces */
#ifdef ENABLE_HTTPS
if(h->ssl != NULL) {
/* we should get the Roles of the session (based on client certificate) */
X509 * peercert;
peercert = SSL_get_peer_certificate(h->ssl);
if(peercert != NULL) {
RoleList = "Admin Basic";
X509_free(peercert);
}
}
#endif
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
RoleList, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
/* Windows XP as client send the following requests :
* GetConnectionTypeInfo
* GetNATRSIPStatus
* ? GetTotalBytesSent - WANCommonInterfaceConfig
* ? GetTotalBytesReceived - idem
* ? GetTotalPacketsSent - idem
* ? GetTotalPacketsReceived - idem
* GetCommonLinkProperties - idem
* GetStatusInfo - WANIPConnection
* GetExternalIPAddress
* QueryStateVariable / ConnectionStatus!
*/
static const struct
{
const char * methodName;
void (*methodImpl)(struct upnphttp *, const char *, const char *);
}
soapMethods[] =
{
/* WANCommonInterfaceConfig */
{ "QueryStateVariable", QueryStateVariable},
{ "GetTotalBytesSent", GetTotalBytesSent},
{ "GetTotalBytesReceived", GetTotalBytesReceived},
{ "GetTotalPacketsSent", GetTotalPacketsSent},
{ "GetTotalPacketsReceived", GetTotalPacketsReceived},
{ "GetCommonLinkProperties", GetCommonLinkProperties},
{ "GetStatusInfo", GetStatusInfo},
/* WANIPConnection */
{ "GetConnectionTypeInfo", GetConnectionTypeInfo },
{ "GetNATRSIPStatus", GetNATRSIPStatus},
{ "GetExternalIPAddress", GetExternalIPAddress},
{ "AddPortMapping", AddPortMapping},
{ "DeletePortMapping", DeletePortMapping},
{ "GetGenericPortMappingEntry", GetGenericPortMappingEntry},
{ "GetSpecificPortMappingEntry", GetSpecificPortMappingEntry},
/* Required in WANIPConnection:2 */
{ "SetConnectionType", SetConnectionType},
{ "RequestConnection", RequestConnection},
{ "ForceTermination", ForceTermination},
{ "AddAnyPortMapping", AddAnyPortMapping},
{ "DeletePortMappingRange", DeletePortMappingRange},
{ "GetListOfPortMappings", GetListOfPortMappings},
#ifdef ENABLE_L3F_SERVICE
/* Layer3Forwarding */
{ "SetDefaultConnectionService", SetDefaultConnectionService},
{ "GetDefaultConnectionService", GetDefaultConnectionService},
#endif
#ifdef ENABLE_6FC_SERVICE
/* WANIPv6FirewallControl */
{ "GetFirewallStatus", GetFirewallStatus}, /* Required */
{ "AddPinhole", AddPinhole}, /* Required */
{ "UpdatePinhole", UpdatePinhole}, /* Required */
{ "GetOutboundPinholeTimeout", GetOutboundPinholeTimeout}, /* Optional */
{ "DeletePinhole", DeletePinhole}, /* Required */
{ "CheckPinholeWorking", CheckPinholeWorking}, /* Optional */
{ "GetPinholePackets", GetPinholePackets}, /* Required */
#endif
#ifdef ENABLE_DP_SERVICE
/* DeviceProtection */
{ "SendSetupMessage", SendSetupMessage}, /* Required */
{ "GetSupportedProtocols", GetSupportedProtocols}, /* Required */
{ "GetAssignedRoles", GetAssignedRoles}, /* Required */
#endif
{ 0, 0 }
};
void
ExecuteSoapAction(struct upnphttp * h, const char * action, int n)
{
char * p;
char * p2;
int i, len, methodlen;
char namespace[256];
/* SoapAction example :
* urn:schemas-upnp-org:service:WANIPConnection:1#GetStatusInfo */
p = strchr(action, '#');
if(p && (p - action) < n) {
for(i = 0; i < ((int)sizeof(namespace) - 1) && (action + i) < p; i++)
namespace[i] = action[i];
namespace[i] = '\0';
p++;
p2 = strchr(p, '"');
if(p2 && (p2 - action) <= n)
methodlen = p2 - p;
else
methodlen = n - (p - action);
/*syslog(LOG_DEBUG, "SoapMethod: %.*s %d %d %p %p %d",
methodlen, p, methodlen, n, action, p, (int)(p - action));*/
for(i = 0; soapMethods[i].methodName; i++) {
len = strlen(soapMethods[i].methodName);
if((len == methodlen) && memcmp(p, soapMethods[i].methodName, len) == 0) {
#ifdef DEBUG
syslog(LOG_DEBUG, "Remote Call of SoapMethod '%s' %s",
soapMethods[i].methodName, namespace);
#endif /* DEBUG */
soapMethods[i].methodImpl(h, soapMethods[i].methodName, namespace);
return;
}
}
syslog(LOG_NOTICE, "SoapMethod: Unknown: %.*s %s", methodlen, p, namespace);
} else {
syslog(LOG_NOTICE, "cannot parse SoapAction");
}
SoapError(h, 401, "Invalid Action");
}
/* Standard Errors:
*
* errorCode errorDescription Description
* -------- ---------------- -----------
* 401 Invalid Action No action by that name at this service.
* 402 Invalid Args Could be any of the following: not enough in args,
* too many in args, no in arg by that name,
* one or more in args are of the wrong data type.
* 403 Out of Sync Out of synchronization.
* 501 Action Failed May be returned in current state of service
* prevents invoking that action.
* 600-699 TBD Common action errors. Defined by UPnP Forum
* Technical Committee.
* 700-799 TBD Action-specific errors for standard actions.
* Defined by UPnP Forum working committee.
* 800-899 TBD Action-specific errors for non-standard actions.
* Defined by UPnP vendor.
*/
void
SoapError(struct upnphttp * h, int errCode, const char * errDesc)
{
static const char resp[] =
"<s:Envelope "
"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body>"
"<s:Fault>"
"<faultcode>s:Client</faultcode>"
"<faultstring>UPnPError</faultstring>"
"<detail>"
"<UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">"
"<errorCode>%d</errorCode>"
"<errorDescription>%s</errorDescription>"
"</UPnPError>"
"</detail>"
"</s:Fault>"
"</s:Body>"
"</s:Envelope>";
char body[2048];
int bodylen;
syslog(LOG_INFO, "Returning UPnPError %d: %s", errCode, errDesc);
bodylen = snprintf(body, sizeof(body), resp, errCode, errDesc);
BuildResp2_upnphttp(h, 500, "Internal Server Error", body, bodylen);
SendRespAndClose_upnphttp(h);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_862_0 |
crossvul-cpp_data_bad_75_0 | /*
* Hisilicon clock driver
*
* Copyright (c) 2013-2017 Hisilicon Limited.
* Copyright (c) 2017 Linaro Limited.
*
* Author: Kai Zhao <zhaokai1@hisilicon.com>
* Tao Wang <kevin.wangtao@hisilicon.com>
* Leo Yan <leo.yan@linaro.org>
*
* 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.
*
*/
#include <linux/clk-provider.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/mailbox_client.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <dt-bindings/clock/hi3660-clock.h>
#define HI3660_STUB_CLOCK_DATA (0x70)
#define MHZ (1000 * 1000)
#define DEFINE_CLK_STUB(_id, _cmd, _name) \
{ \
.id = (_id), \
.cmd = (_cmd), \
.hw.init = &(struct clk_init_data) { \
.name = #_name, \
.ops = &hi3660_stub_clk_ops, \
.num_parents = 0, \
.flags = CLK_GET_RATE_NOCACHE, \
}, \
},
#define to_stub_clk(_hw) container_of(_hw, struct hi3660_stub_clk, hw)
struct hi3660_stub_clk_chan {
struct mbox_client cl;
struct mbox_chan *mbox;
};
struct hi3660_stub_clk {
unsigned int id;
struct clk_hw hw;
unsigned int cmd;
unsigned int msg[8];
unsigned int rate;
};
static void __iomem *freq_reg;
static struct hi3660_stub_clk_chan stub_clk_chan;
static unsigned long hi3660_stub_clk_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
struct hi3660_stub_clk *stub_clk = to_stub_clk(hw);
/*
* LPM3 writes back the CPU frequency in shared SRAM so read
* back the frequency.
*/
stub_clk->rate = readl(freq_reg + (stub_clk->id << 2)) * MHZ;
return stub_clk->rate;
}
static long hi3660_stub_clk_round_rate(struct clk_hw *hw, unsigned long rate,
unsigned long *prate)
{
/*
* LPM3 handles rate rounding so just return whatever
* rate is requested.
*/
return rate;
}
static int hi3660_stub_clk_set_rate(struct clk_hw *hw, unsigned long rate,
unsigned long parent_rate)
{
struct hi3660_stub_clk *stub_clk = to_stub_clk(hw);
stub_clk->msg[0] = stub_clk->cmd;
stub_clk->msg[1] = rate / MHZ;
dev_dbg(stub_clk_chan.cl.dev, "set rate msg[0]=0x%x msg[1]=0x%x\n",
stub_clk->msg[0], stub_clk->msg[1]);
mbox_send_message(stub_clk_chan.mbox, stub_clk->msg);
mbox_client_txdone(stub_clk_chan.mbox, 0);
stub_clk->rate = rate;
return 0;
}
static const struct clk_ops hi3660_stub_clk_ops = {
.recalc_rate = hi3660_stub_clk_recalc_rate,
.round_rate = hi3660_stub_clk_round_rate,
.set_rate = hi3660_stub_clk_set_rate,
};
static struct hi3660_stub_clk hi3660_stub_clks[HI3660_CLK_STUB_NUM] = {
DEFINE_CLK_STUB(HI3660_CLK_STUB_CLUSTER0, 0x0001030A, "cpu-cluster.0")
DEFINE_CLK_STUB(HI3660_CLK_STUB_CLUSTER1, 0x0002030A, "cpu-cluster.1")
DEFINE_CLK_STUB(HI3660_CLK_STUB_GPU, 0x0003030A, "clk-g3d")
DEFINE_CLK_STUB(HI3660_CLK_STUB_DDR, 0x00040309, "clk-ddrc")
};
static struct clk_hw *hi3660_stub_clk_hw_get(struct of_phandle_args *clkspec,
void *data)
{
unsigned int idx = clkspec->args[0];
if (idx >= HI3660_CLK_STUB_NUM) {
pr_err("%s: invalid index %u\n", __func__, idx);
return ERR_PTR(-EINVAL);
}
return &hi3660_stub_clks[idx].hw;
}
static int hi3660_stub_clk_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct resource *res;
unsigned int i;
int ret;
/* Use mailbox client without blocking */
stub_clk_chan.cl.dev = dev;
stub_clk_chan.cl.tx_done = NULL;
stub_clk_chan.cl.tx_block = false;
stub_clk_chan.cl.knows_txdone = false;
/* Allocate mailbox channel */
stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);
if (IS_ERR(stub_clk_chan.mbox))
return PTR_ERR(stub_clk_chan.mbox);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
freq_reg = devm_ioremap(dev, res->start, resource_size(res));
if (!freq_reg)
return -ENOMEM;
freq_reg += HI3660_STUB_CLOCK_DATA;
for (i = 0; i < HI3660_CLK_STUB_NUM; i++) {
ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);
if (ret)
return ret;
}
return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,
hi3660_stub_clks);
}
static const struct of_device_id hi3660_stub_clk_of_match[] = {
{ .compatible = "hisilicon,hi3660-stub-clk", },
{}
};
static struct platform_driver hi3660_stub_clk_driver = {
.probe = hi3660_stub_clk_probe,
.driver = {
.name = "hi3660-stub-clk",
.of_match_table = hi3660_stub_clk_of_match,
},
};
static int __init hi3660_stub_clk_init(void)
{
return platform_driver_register(&hi3660_stub_clk_driver);
}
subsys_initcall(hi3660_stub_clk_init);
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_75_0 |
crossvul-cpp_data_bad_5345_0 | /******************************************************************************
* emulate.c
*
* Generic x86 (32-bit and 64-bit) instruction decoder and emulator.
*
* Copyright (c) 2005 Keir Fraser
*
* Linux coding style, mod r/m decoder, segment base fixes, real-mode
* privileged instructions:
*
* Copyright (C) 2006 Qumranet
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* 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.
*
* From: xen-unstable 10676:af9809f51f81a3c43f276f00c81a52ef558afda4
*/
#include <linux/kvm_host.h>
#include "kvm_cache_regs.h"
#include <asm/kvm_emulate.h>
#include <linux/stringify.h>
#include <asm/debugreg.h>
#include "x86.h"
#include "tss.h"
/*
* Operand types
*/
#define OpNone 0ull
#define OpImplicit 1ull /* No generic decode */
#define OpReg 2ull /* Register */
#define OpMem 3ull /* Memory */
#define OpAcc 4ull /* Accumulator: AL/AX/EAX/RAX */
#define OpDI 5ull /* ES:DI/EDI/RDI */
#define OpMem64 6ull /* Memory, 64-bit */
#define OpImmUByte 7ull /* Zero-extended 8-bit immediate */
#define OpDX 8ull /* DX register */
#define OpCL 9ull /* CL register (for shifts) */
#define OpImmByte 10ull /* 8-bit sign extended immediate */
#define OpOne 11ull /* Implied 1 */
#define OpImm 12ull /* Sign extended up to 32-bit immediate */
#define OpMem16 13ull /* Memory operand (16-bit). */
#define OpMem32 14ull /* Memory operand (32-bit). */
#define OpImmU 15ull /* Immediate operand, zero extended */
#define OpSI 16ull /* SI/ESI/RSI */
#define OpImmFAddr 17ull /* Immediate far address */
#define OpMemFAddr 18ull /* Far address in memory */
#define OpImmU16 19ull /* Immediate operand, 16 bits, zero extended */
#define OpES 20ull /* ES */
#define OpCS 21ull /* CS */
#define OpSS 22ull /* SS */
#define OpDS 23ull /* DS */
#define OpFS 24ull /* FS */
#define OpGS 25ull /* GS */
#define OpMem8 26ull /* 8-bit zero extended memory operand */
#define OpImm64 27ull /* Sign extended 16/32/64-bit immediate */
#define OpXLat 28ull /* memory at BX/EBX/RBX + zero-extended AL */
#define OpAccLo 29ull /* Low part of extended acc (AX/AX/EAX/RAX) */
#define OpAccHi 30ull /* High part of extended acc (-/DX/EDX/RDX) */
#define OpBits 5 /* Width of operand field */
#define OpMask ((1ull << OpBits) - 1)
/*
* Opcode effective-address decode tables.
* Note that we only emulate instructions that have at least one memory
* operand (excluding implicit stack references). We assume that stack
* references and instruction fetches will never occur in special memory
* areas that require emulation. So, for example, 'mov <imm>,<reg>' need
* not be handled.
*/
/* Operand sizes: 8-bit operands or specified/overridden size. */
#define ByteOp (1<<0) /* 8-bit operands. */
/* Destination operand type. */
#define DstShift 1
#define ImplicitOps (OpImplicit << DstShift)
#define DstReg (OpReg << DstShift)
#define DstMem (OpMem << DstShift)
#define DstAcc (OpAcc << DstShift)
#define DstDI (OpDI << DstShift)
#define DstMem64 (OpMem64 << DstShift)
#define DstMem16 (OpMem16 << DstShift)
#define DstImmUByte (OpImmUByte << DstShift)
#define DstDX (OpDX << DstShift)
#define DstAccLo (OpAccLo << DstShift)
#define DstMask (OpMask << DstShift)
/* Source operand type. */
#define SrcShift 6
#define SrcNone (OpNone << SrcShift)
#define SrcReg (OpReg << SrcShift)
#define SrcMem (OpMem << SrcShift)
#define SrcMem16 (OpMem16 << SrcShift)
#define SrcMem32 (OpMem32 << SrcShift)
#define SrcImm (OpImm << SrcShift)
#define SrcImmByte (OpImmByte << SrcShift)
#define SrcOne (OpOne << SrcShift)
#define SrcImmUByte (OpImmUByte << SrcShift)
#define SrcImmU (OpImmU << SrcShift)
#define SrcSI (OpSI << SrcShift)
#define SrcXLat (OpXLat << SrcShift)
#define SrcImmFAddr (OpImmFAddr << SrcShift)
#define SrcMemFAddr (OpMemFAddr << SrcShift)
#define SrcAcc (OpAcc << SrcShift)
#define SrcImmU16 (OpImmU16 << SrcShift)
#define SrcImm64 (OpImm64 << SrcShift)
#define SrcDX (OpDX << SrcShift)
#define SrcMem8 (OpMem8 << SrcShift)
#define SrcAccHi (OpAccHi << SrcShift)
#define SrcMask (OpMask << SrcShift)
#define BitOp (1<<11)
#define MemAbs (1<<12) /* Memory operand is absolute displacement */
#define String (1<<13) /* String instruction (rep capable) */
#define Stack (1<<14) /* Stack instruction (push/pop) */
#define GroupMask (7<<15) /* Opcode uses one of the group mechanisms */
#define Group (1<<15) /* Bits 3:5 of modrm byte extend opcode */
#define GroupDual (2<<15) /* Alternate decoding of mod == 3 */
#define Prefix (3<<15) /* Instruction varies with 66/f2/f3 prefix */
#define RMExt (4<<15) /* Opcode extension in ModRM r/m if mod == 3 */
#define Escape (5<<15) /* Escape to coprocessor instruction */
#define InstrDual (6<<15) /* Alternate instruction decoding of mod == 3 */
#define ModeDual (7<<15) /* Different instruction for 32/64 bit */
#define Sse (1<<18) /* SSE Vector instruction */
/* Generic ModRM decode. */
#define ModRM (1<<19)
/* Destination is only written; never read. */
#define Mov (1<<20)
/* Misc flags */
#define Prot (1<<21) /* instruction generates #UD if not in prot-mode */
#define EmulateOnUD (1<<22) /* Emulate if unsupported by the host */
#define NoAccess (1<<23) /* Don't access memory (lea/invlpg/verr etc) */
#define Op3264 (1<<24) /* Operand is 64b in long mode, 32b otherwise */
#define Undefined (1<<25) /* No Such Instruction */
#define Lock (1<<26) /* lock prefix is allowed for the instruction */
#define Priv (1<<27) /* instruction generates #GP if current CPL != 0 */
#define No64 (1<<28)
#define PageTable (1 << 29) /* instruction used to write page table */
#define NotImpl (1 << 30) /* instruction is not implemented */
/* Source 2 operand type */
#define Src2Shift (31)
#define Src2None (OpNone << Src2Shift)
#define Src2Mem (OpMem << Src2Shift)
#define Src2CL (OpCL << Src2Shift)
#define Src2ImmByte (OpImmByte << Src2Shift)
#define Src2One (OpOne << Src2Shift)
#define Src2Imm (OpImm << Src2Shift)
#define Src2ES (OpES << Src2Shift)
#define Src2CS (OpCS << Src2Shift)
#define Src2SS (OpSS << Src2Shift)
#define Src2DS (OpDS << Src2Shift)
#define Src2FS (OpFS << Src2Shift)
#define Src2GS (OpGS << Src2Shift)
#define Src2Mask (OpMask << Src2Shift)
#define Mmx ((u64)1 << 40) /* MMX Vector instruction */
#define Aligned ((u64)1 << 41) /* Explicitly aligned (e.g. MOVDQA) */
#define Unaligned ((u64)1 << 42) /* Explicitly unaligned (e.g. MOVDQU) */
#define Avx ((u64)1 << 43) /* Advanced Vector Extensions */
#define Fastop ((u64)1 << 44) /* Use opcode::u.fastop */
#define NoWrite ((u64)1 << 45) /* No writeback */
#define SrcWrite ((u64)1 << 46) /* Write back src operand */
#define NoMod ((u64)1 << 47) /* Mod field is ignored */
#define Intercept ((u64)1 << 48) /* Has valid intercept field */
#define CheckPerm ((u64)1 << 49) /* Has valid check_perm field */
#define PrivUD ((u64)1 << 51) /* #UD instead of #GP on CPL > 0 */
#define NearBranch ((u64)1 << 52) /* Near branches */
#define No16 ((u64)1 << 53) /* No 16 bit operand */
#define IncSP ((u64)1 << 54) /* SP is incremented before ModRM calc */
#define DstXacc (DstAccLo | SrcAccHi | SrcWrite)
#define X2(x...) x, x
#define X3(x...) X2(x), x
#define X4(x...) X2(x), X2(x)
#define X5(x...) X4(x), x
#define X6(x...) X4(x), X2(x)
#define X7(x...) X4(x), X3(x)
#define X8(x...) X4(x), X4(x)
#define X16(x...) X8(x), X8(x)
#define NR_FASTOP (ilog2(sizeof(ulong)) + 1)
#define FASTOP_SIZE 8
/*
* fastop functions have a special calling convention:
*
* dst: rax (in/out)
* src: rdx (in/out)
* src2: rcx (in)
* flags: rflags (in/out)
* ex: rsi (in:fastop pointer, out:zero if exception)
*
* Moreover, they are all exactly FASTOP_SIZE bytes long, so functions for
* different operand sizes can be reached by calculation, rather than a jump
* table (which would be bigger than the code).
*
* fastop functions are declared as taking a never-defined fastop parameter,
* so they can't be called from C directly.
*/
struct fastop;
struct opcode {
u64 flags : 56;
u64 intercept : 8;
union {
int (*execute)(struct x86_emulate_ctxt *ctxt);
const struct opcode *group;
const struct group_dual *gdual;
const struct gprefix *gprefix;
const struct escape *esc;
const struct instr_dual *idual;
const struct mode_dual *mdual;
void (*fastop)(struct fastop *fake);
} u;
int (*check_perm)(struct x86_emulate_ctxt *ctxt);
};
struct group_dual {
struct opcode mod012[8];
struct opcode mod3[8];
};
struct gprefix {
struct opcode pfx_no;
struct opcode pfx_66;
struct opcode pfx_f2;
struct opcode pfx_f3;
};
struct escape {
struct opcode op[8];
struct opcode high[64];
};
struct instr_dual {
struct opcode mod012;
struct opcode mod3;
};
struct mode_dual {
struct opcode mode32;
struct opcode mode64;
};
#define EFLG_RESERVED_ZEROS_MASK 0xffc0802a
enum x86_transfer_type {
X86_TRANSFER_NONE,
X86_TRANSFER_CALL_JMP,
X86_TRANSFER_RET,
X86_TRANSFER_TASK_SWITCH,
};
static ulong reg_read(struct x86_emulate_ctxt *ctxt, unsigned nr)
{
if (!(ctxt->regs_valid & (1 << nr))) {
ctxt->regs_valid |= 1 << nr;
ctxt->_regs[nr] = ctxt->ops->read_gpr(ctxt, nr);
}
return ctxt->_regs[nr];
}
static ulong *reg_write(struct x86_emulate_ctxt *ctxt, unsigned nr)
{
ctxt->regs_valid |= 1 << nr;
ctxt->regs_dirty |= 1 << nr;
return &ctxt->_regs[nr];
}
static ulong *reg_rmw(struct x86_emulate_ctxt *ctxt, unsigned nr)
{
reg_read(ctxt, nr);
return reg_write(ctxt, nr);
}
static void writeback_registers(struct x86_emulate_ctxt *ctxt)
{
unsigned reg;
for_each_set_bit(reg, (ulong *)&ctxt->regs_dirty, 16)
ctxt->ops->write_gpr(ctxt, reg, ctxt->_regs[reg]);
}
static void invalidate_registers(struct x86_emulate_ctxt *ctxt)
{
ctxt->regs_dirty = 0;
ctxt->regs_valid = 0;
}
/*
* These EFLAGS bits are restored from saved value during emulation, and
* any changes are written back to the saved value after emulation.
*/
#define EFLAGS_MASK (X86_EFLAGS_OF|X86_EFLAGS_SF|X86_EFLAGS_ZF|X86_EFLAGS_AF|\
X86_EFLAGS_PF|X86_EFLAGS_CF)
#ifdef CONFIG_X86_64
#define ON64(x) x
#else
#define ON64(x)
#endif
static int fastop(struct x86_emulate_ctxt *ctxt, void (*fop)(struct fastop *));
#define FOP_FUNC(name) \
".align " __stringify(FASTOP_SIZE) " \n\t" \
".type " name ", @function \n\t" \
name ":\n\t"
#define FOP_RET "ret \n\t"
#define FOP_START(op) \
extern void em_##op(struct fastop *fake); \
asm(".pushsection .text, \"ax\" \n\t" \
".global em_" #op " \n\t" \
FOP_FUNC("em_" #op)
#define FOP_END \
".popsection")
#define FOPNOP() \
FOP_FUNC(__stringify(__UNIQUE_ID(nop))) \
FOP_RET
#define FOP1E(op, dst) \
FOP_FUNC(#op "_" #dst) \
"10: " #op " %" #dst " \n\t" FOP_RET
#define FOP1EEX(op, dst) \
FOP1E(op, dst) _ASM_EXTABLE(10b, kvm_fastop_exception)
#define FASTOP1(op) \
FOP_START(op) \
FOP1E(op##b, al) \
FOP1E(op##w, ax) \
FOP1E(op##l, eax) \
ON64(FOP1E(op##q, rax)) \
FOP_END
/* 1-operand, using src2 (for MUL/DIV r/m) */
#define FASTOP1SRC2(op, name) \
FOP_START(name) \
FOP1E(op, cl) \
FOP1E(op, cx) \
FOP1E(op, ecx) \
ON64(FOP1E(op, rcx)) \
FOP_END
/* 1-operand, using src2 (for MUL/DIV r/m), with exceptions */
#define FASTOP1SRC2EX(op, name) \
FOP_START(name) \
FOP1EEX(op, cl) \
FOP1EEX(op, cx) \
FOP1EEX(op, ecx) \
ON64(FOP1EEX(op, rcx)) \
FOP_END
#define FOP2E(op, dst, src) \
FOP_FUNC(#op "_" #dst "_" #src) \
#op " %" #src ", %" #dst " \n\t" FOP_RET
#define FASTOP2(op) \
FOP_START(op) \
FOP2E(op##b, al, dl) \
FOP2E(op##w, ax, dx) \
FOP2E(op##l, eax, edx) \
ON64(FOP2E(op##q, rax, rdx)) \
FOP_END
/* 2 operand, word only */
#define FASTOP2W(op) \
FOP_START(op) \
FOPNOP() \
FOP2E(op##w, ax, dx) \
FOP2E(op##l, eax, edx) \
ON64(FOP2E(op##q, rax, rdx)) \
FOP_END
/* 2 operand, src is CL */
#define FASTOP2CL(op) \
FOP_START(op) \
FOP2E(op##b, al, cl) \
FOP2E(op##w, ax, cl) \
FOP2E(op##l, eax, cl) \
ON64(FOP2E(op##q, rax, cl)) \
FOP_END
/* 2 operand, src and dest are reversed */
#define FASTOP2R(op, name) \
FOP_START(name) \
FOP2E(op##b, dl, al) \
FOP2E(op##w, dx, ax) \
FOP2E(op##l, edx, eax) \
ON64(FOP2E(op##q, rdx, rax)) \
FOP_END
#define FOP3E(op, dst, src, src2) \
FOP_FUNC(#op "_" #dst "_" #src "_" #src2) \
#op " %" #src2 ", %" #src ", %" #dst " \n\t" FOP_RET
/* 3-operand, word-only, src2=cl */
#define FASTOP3WCL(op) \
FOP_START(op) \
FOPNOP() \
FOP3E(op##w, ax, dx, cl) \
FOP3E(op##l, eax, edx, cl) \
ON64(FOP3E(op##q, rax, rdx, cl)) \
FOP_END
/* Special case for SETcc - 1 instruction per cc */
#define FOP_SETCC(op) \
".align 4 \n\t" \
".type " #op ", @function \n\t" \
#op ": \n\t" \
#op " %al \n\t" \
FOP_RET
asm(".global kvm_fastop_exception \n"
"kvm_fastop_exception: xor %esi, %esi; ret");
FOP_START(setcc)
FOP_SETCC(seto)
FOP_SETCC(setno)
FOP_SETCC(setc)
FOP_SETCC(setnc)
FOP_SETCC(setz)
FOP_SETCC(setnz)
FOP_SETCC(setbe)
FOP_SETCC(setnbe)
FOP_SETCC(sets)
FOP_SETCC(setns)
FOP_SETCC(setp)
FOP_SETCC(setnp)
FOP_SETCC(setl)
FOP_SETCC(setnl)
FOP_SETCC(setle)
FOP_SETCC(setnle)
FOP_END;
FOP_START(salc) "pushf; sbb %al, %al; popf \n\t" FOP_RET
FOP_END;
static int emulator_check_intercept(struct x86_emulate_ctxt *ctxt,
enum x86_intercept intercept,
enum x86_intercept_stage stage)
{
struct x86_instruction_info info = {
.intercept = intercept,
.rep_prefix = ctxt->rep_prefix,
.modrm_mod = ctxt->modrm_mod,
.modrm_reg = ctxt->modrm_reg,
.modrm_rm = ctxt->modrm_rm,
.src_val = ctxt->src.val64,
.dst_val = ctxt->dst.val64,
.src_bytes = ctxt->src.bytes,
.dst_bytes = ctxt->dst.bytes,
.ad_bytes = ctxt->ad_bytes,
.next_rip = ctxt->eip,
};
return ctxt->ops->intercept(ctxt, &info, stage);
}
static void assign_masked(ulong *dest, ulong src, ulong mask)
{
*dest = (*dest & ~mask) | (src & mask);
}
static void assign_register(unsigned long *reg, u64 val, int bytes)
{
/* The 4-byte case *is* correct: in 64-bit mode we zero-extend. */
switch (bytes) {
case 1:
*(u8 *)reg = (u8)val;
break;
case 2:
*(u16 *)reg = (u16)val;
break;
case 4:
*reg = (u32)val;
break; /* 64b: zero-extend */
case 8:
*reg = val;
break;
}
}
static inline unsigned long ad_mask(struct x86_emulate_ctxt *ctxt)
{
return (1UL << (ctxt->ad_bytes << 3)) - 1;
}
static ulong stack_mask(struct x86_emulate_ctxt *ctxt)
{
u16 sel;
struct desc_struct ss;
if (ctxt->mode == X86EMUL_MODE_PROT64)
return ~0UL;
ctxt->ops->get_segment(ctxt, &sel, &ss, NULL, VCPU_SREG_SS);
return ~0U >> ((ss.d ^ 1) * 16); /* d=0: 0xffff; d=1: 0xffffffff */
}
static int stack_size(struct x86_emulate_ctxt *ctxt)
{
return (__fls(stack_mask(ctxt)) + 1) >> 3;
}
/* Access/update address held in a register, based on addressing mode. */
static inline unsigned long
address_mask(struct x86_emulate_ctxt *ctxt, unsigned long reg)
{
if (ctxt->ad_bytes == sizeof(unsigned long))
return reg;
else
return reg & ad_mask(ctxt);
}
static inline unsigned long
register_address(struct x86_emulate_ctxt *ctxt, int reg)
{
return address_mask(ctxt, reg_read(ctxt, reg));
}
static void masked_increment(ulong *reg, ulong mask, int inc)
{
assign_masked(reg, *reg + inc, mask);
}
static inline void
register_address_increment(struct x86_emulate_ctxt *ctxt, int reg, int inc)
{
ulong *preg = reg_rmw(ctxt, reg);
assign_register(preg, *preg + inc, ctxt->ad_bytes);
}
static void rsp_increment(struct x86_emulate_ctxt *ctxt, int inc)
{
masked_increment(reg_rmw(ctxt, VCPU_REGS_RSP), stack_mask(ctxt), inc);
}
static u32 desc_limit_scaled(struct desc_struct *desc)
{
u32 limit = get_desc_limit(desc);
return desc->g ? (limit << 12) | 0xfff : limit;
}
static unsigned long seg_base(struct x86_emulate_ctxt *ctxt, int seg)
{
if (ctxt->mode == X86EMUL_MODE_PROT64 && seg < VCPU_SREG_FS)
return 0;
return ctxt->ops->get_cached_segment_base(ctxt, seg);
}
static int emulate_exception(struct x86_emulate_ctxt *ctxt, int vec,
u32 error, bool valid)
{
WARN_ON(vec > 0x1f);
ctxt->exception.vector = vec;
ctxt->exception.error_code = error;
ctxt->exception.error_code_valid = valid;
return X86EMUL_PROPAGATE_FAULT;
}
static int emulate_db(struct x86_emulate_ctxt *ctxt)
{
return emulate_exception(ctxt, DB_VECTOR, 0, false);
}
static int emulate_gp(struct x86_emulate_ctxt *ctxt, int err)
{
return emulate_exception(ctxt, GP_VECTOR, err, true);
}
static int emulate_ss(struct x86_emulate_ctxt *ctxt, int err)
{
return emulate_exception(ctxt, SS_VECTOR, err, true);
}
static int emulate_ud(struct x86_emulate_ctxt *ctxt)
{
return emulate_exception(ctxt, UD_VECTOR, 0, false);
}
static int emulate_ts(struct x86_emulate_ctxt *ctxt, int err)
{
return emulate_exception(ctxt, TS_VECTOR, err, true);
}
static int emulate_de(struct x86_emulate_ctxt *ctxt)
{
return emulate_exception(ctxt, DE_VECTOR, 0, false);
}
static int emulate_nm(struct x86_emulate_ctxt *ctxt)
{
return emulate_exception(ctxt, NM_VECTOR, 0, false);
}
static u16 get_segment_selector(struct x86_emulate_ctxt *ctxt, unsigned seg)
{
u16 selector;
struct desc_struct desc;
ctxt->ops->get_segment(ctxt, &selector, &desc, NULL, seg);
return selector;
}
static void set_segment_selector(struct x86_emulate_ctxt *ctxt, u16 selector,
unsigned seg)
{
u16 dummy;
u32 base3;
struct desc_struct desc;
ctxt->ops->get_segment(ctxt, &dummy, &desc, &base3, seg);
ctxt->ops->set_segment(ctxt, selector, &desc, base3, seg);
}
/*
* x86 defines three classes of vector instructions: explicitly
* aligned, explicitly unaligned, and the rest, which change behaviour
* depending on whether they're AVX encoded or not.
*
* Also included is CMPXCHG16B which is not a vector instruction, yet it is
* subject to the same check.
*/
static bool insn_aligned(struct x86_emulate_ctxt *ctxt, unsigned size)
{
if (likely(size < 16))
return false;
if (ctxt->d & Aligned)
return true;
else if (ctxt->d & Unaligned)
return false;
else if (ctxt->d & Avx)
return false;
else
return true;
}
static __always_inline int __linearize(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
unsigned *max_size, unsigned size,
bool write, bool fetch,
enum x86emul_mode mode, ulong *linear)
{
struct desc_struct desc;
bool usable;
ulong la;
u32 lim;
u16 sel;
la = seg_base(ctxt, addr.seg) + addr.ea;
*max_size = 0;
switch (mode) {
case X86EMUL_MODE_PROT64:
*linear = la;
if (is_noncanonical_address(la))
goto bad;
*max_size = min_t(u64, ~0u, (1ull << 48) - la);
if (size > *max_size)
goto bad;
break;
default:
*linear = la = (u32)la;
usable = ctxt->ops->get_segment(ctxt, &sel, &desc, NULL,
addr.seg);
if (!usable)
goto bad;
/* code segment in protected mode or read-only data segment */
if ((((ctxt->mode != X86EMUL_MODE_REAL) && (desc.type & 8))
|| !(desc.type & 2)) && write)
goto bad;
/* unreadable code segment */
if (!fetch && (desc.type & 8) && !(desc.type & 2))
goto bad;
lim = desc_limit_scaled(&desc);
if (!(desc.type & 8) && (desc.type & 4)) {
/* expand-down segment */
if (addr.ea <= lim)
goto bad;
lim = desc.d ? 0xffffffff : 0xffff;
}
if (addr.ea > lim)
goto bad;
if (lim == 0xffffffff)
*max_size = ~0u;
else {
*max_size = (u64)lim + 1 - addr.ea;
if (size > *max_size)
goto bad;
}
break;
}
if (insn_aligned(ctxt, size) && ((la & (size - 1)) != 0))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
bad:
if (addr.seg == VCPU_SREG_SS)
return emulate_ss(ctxt, 0);
else
return emulate_gp(ctxt, 0);
}
static int linearize(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
unsigned size, bool write,
ulong *linear)
{
unsigned max_size;
return __linearize(ctxt, addr, &max_size, size, write, false,
ctxt->mode, linear);
}
static inline int assign_eip(struct x86_emulate_ctxt *ctxt, ulong dst,
enum x86emul_mode mode)
{
ulong linear;
int rc;
unsigned max_size;
struct segmented_address addr = { .seg = VCPU_SREG_CS,
.ea = dst };
if (ctxt->op_bytes != sizeof(unsigned long))
addr.ea = dst & ((1UL << (ctxt->op_bytes << 3)) - 1);
rc = __linearize(ctxt, addr, &max_size, 1, false, true, mode, &linear);
if (rc == X86EMUL_CONTINUE)
ctxt->_eip = addr.ea;
return rc;
}
static inline int assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst)
{
return assign_eip(ctxt, dst, ctxt->mode);
}
static int assign_eip_far(struct x86_emulate_ctxt *ctxt, ulong dst,
const struct desc_struct *cs_desc)
{
enum x86emul_mode mode = ctxt->mode;
int rc;
#ifdef CONFIG_X86_64
if (ctxt->mode >= X86EMUL_MODE_PROT16) {
if (cs_desc->l) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
mode = X86EMUL_MODE_PROT64;
} else
mode = X86EMUL_MODE_PROT32; /* temporary value */
}
#endif
if (mode == X86EMUL_MODE_PROT16 || mode == X86EMUL_MODE_PROT32)
mode = cs_desc->d ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
rc = assign_eip(ctxt, dst, mode);
if (rc == X86EMUL_CONTINUE)
ctxt->mode = mode;
return rc;
}
static inline int jmp_rel(struct x86_emulate_ctxt *ctxt, int rel)
{
return assign_eip_near(ctxt, ctxt->_eip + rel);
}
static int segmented_read_std(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
void *data,
unsigned size)
{
int rc;
ulong linear;
rc = linearize(ctxt, addr, size, false, &linear);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->read_std(ctxt, linear, data, size, &ctxt->exception);
}
/*
* Prefetch the remaining bytes of the instruction without crossing page
* boundary if they are not in fetch_cache yet.
*/
static int __do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt, int op_size)
{
int rc;
unsigned size, max_size;
unsigned long linear;
int cur_size = ctxt->fetch.end - ctxt->fetch.data;
struct segmented_address addr = { .seg = VCPU_SREG_CS,
.ea = ctxt->eip + cur_size };
/*
* We do not know exactly how many bytes will be needed, and
* __linearize is expensive, so fetch as much as possible. We
* just have to avoid going beyond the 15 byte limit, the end
* of the segment, or the end of the page.
*
* __linearize is called with size 0 so that it does not do any
* boundary check itself. Instead, we use max_size to check
* against op_size.
*/
rc = __linearize(ctxt, addr, &max_size, 0, false, true, ctxt->mode,
&linear);
if (unlikely(rc != X86EMUL_CONTINUE))
return rc;
size = min_t(unsigned, 15UL ^ cur_size, max_size);
size = min_t(unsigned, size, PAGE_SIZE - offset_in_page(linear));
/*
* One instruction can only straddle two pages,
* and one has been loaded at the beginning of
* x86_decode_insn. So, if not enough bytes
* still, we must have hit the 15-byte boundary.
*/
if (unlikely(size < op_size))
return emulate_gp(ctxt, 0);
rc = ctxt->ops->fetch(ctxt, linear, ctxt->fetch.end,
size, &ctxt->exception);
if (unlikely(rc != X86EMUL_CONTINUE))
return rc;
ctxt->fetch.end += size;
return X86EMUL_CONTINUE;
}
static __always_inline int do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt,
unsigned size)
{
unsigned done_size = ctxt->fetch.end - ctxt->fetch.ptr;
if (unlikely(done_size < size))
return __do_insn_fetch_bytes(ctxt, size - done_size);
else
return X86EMUL_CONTINUE;
}
/* Fetch next part of the instruction being emulated. */
#define insn_fetch(_type, _ctxt) \
({ _type _x; \
\
rc = do_insn_fetch_bytes(_ctxt, sizeof(_type)); \
if (rc != X86EMUL_CONTINUE) \
goto done; \
ctxt->_eip += sizeof(_type); \
_x = *(_type __aligned(1) *) ctxt->fetch.ptr; \
ctxt->fetch.ptr += sizeof(_type); \
_x; \
})
#define insn_fetch_arr(_arr, _size, _ctxt) \
({ \
rc = do_insn_fetch_bytes(_ctxt, _size); \
if (rc != X86EMUL_CONTINUE) \
goto done; \
ctxt->_eip += (_size); \
memcpy(_arr, ctxt->fetch.ptr, _size); \
ctxt->fetch.ptr += (_size); \
})
/*
* Given the 'reg' portion of a ModRM byte, and a register block, return a
* pointer into the block that addresses the relevant register.
* @highbyte_regs specifies whether to decode AH,CH,DH,BH.
*/
static void *decode_register(struct x86_emulate_ctxt *ctxt, u8 modrm_reg,
int byteop)
{
void *p;
int highbyte_regs = (ctxt->rex_prefix == 0) && byteop;
if (highbyte_regs && modrm_reg >= 4 && modrm_reg < 8)
p = (unsigned char *)reg_rmw(ctxt, modrm_reg & 3) + 1;
else
p = reg_rmw(ctxt, modrm_reg);
return p;
}
static int read_descriptor(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
u16 *size, unsigned long *address, int op_bytes)
{
int rc;
if (op_bytes == 2)
op_bytes = 3;
*address = 0;
rc = segmented_read_std(ctxt, addr, size, 2);
if (rc != X86EMUL_CONTINUE)
return rc;
addr.ea += 2;
rc = segmented_read_std(ctxt, addr, address, op_bytes);
return rc;
}
FASTOP2(add);
FASTOP2(or);
FASTOP2(adc);
FASTOP2(sbb);
FASTOP2(and);
FASTOP2(sub);
FASTOP2(xor);
FASTOP2(cmp);
FASTOP2(test);
FASTOP1SRC2(mul, mul_ex);
FASTOP1SRC2(imul, imul_ex);
FASTOP1SRC2EX(div, div_ex);
FASTOP1SRC2EX(idiv, idiv_ex);
FASTOP3WCL(shld);
FASTOP3WCL(shrd);
FASTOP2W(imul);
FASTOP1(not);
FASTOP1(neg);
FASTOP1(inc);
FASTOP1(dec);
FASTOP2CL(rol);
FASTOP2CL(ror);
FASTOP2CL(rcl);
FASTOP2CL(rcr);
FASTOP2CL(shl);
FASTOP2CL(shr);
FASTOP2CL(sar);
FASTOP2W(bsf);
FASTOP2W(bsr);
FASTOP2W(bt);
FASTOP2W(bts);
FASTOP2W(btr);
FASTOP2W(btc);
FASTOP2(xadd);
FASTOP2R(cmp, cmp_r);
static int em_bsf_c(struct x86_emulate_ctxt *ctxt)
{
/* If src is zero, do not writeback, but update flags */
if (ctxt->src.val == 0)
ctxt->dst.type = OP_NONE;
return fastop(ctxt, em_bsf);
}
static int em_bsr_c(struct x86_emulate_ctxt *ctxt)
{
/* If src is zero, do not writeback, but update flags */
if (ctxt->src.val == 0)
ctxt->dst.type = OP_NONE;
return fastop(ctxt, em_bsr);
}
static __always_inline u8 test_cc(unsigned int condition, unsigned long flags)
{
u8 rc;
void (*fop)(void) = (void *)em_setcc + 4 * (condition & 0xf);
flags = (flags & EFLAGS_MASK) | X86_EFLAGS_IF;
asm("push %[flags]; popf; call *%[fastop]"
: "=a"(rc) : [fastop]"r"(fop), [flags]"r"(flags));
return rc;
}
static void fetch_register_operand(struct operand *op)
{
switch (op->bytes) {
case 1:
op->val = *(u8 *)op->addr.reg;
break;
case 2:
op->val = *(u16 *)op->addr.reg;
break;
case 4:
op->val = *(u32 *)op->addr.reg;
break;
case 8:
op->val = *(u64 *)op->addr.reg;
break;
}
}
static void read_sse_reg(struct x86_emulate_ctxt *ctxt, sse128_t *data, int reg)
{
ctxt->ops->get_fpu(ctxt);
switch (reg) {
case 0: asm("movdqa %%xmm0, %0" : "=m"(*data)); break;
case 1: asm("movdqa %%xmm1, %0" : "=m"(*data)); break;
case 2: asm("movdqa %%xmm2, %0" : "=m"(*data)); break;
case 3: asm("movdqa %%xmm3, %0" : "=m"(*data)); break;
case 4: asm("movdqa %%xmm4, %0" : "=m"(*data)); break;
case 5: asm("movdqa %%xmm5, %0" : "=m"(*data)); break;
case 6: asm("movdqa %%xmm6, %0" : "=m"(*data)); break;
case 7: asm("movdqa %%xmm7, %0" : "=m"(*data)); break;
#ifdef CONFIG_X86_64
case 8: asm("movdqa %%xmm8, %0" : "=m"(*data)); break;
case 9: asm("movdqa %%xmm9, %0" : "=m"(*data)); break;
case 10: asm("movdqa %%xmm10, %0" : "=m"(*data)); break;
case 11: asm("movdqa %%xmm11, %0" : "=m"(*data)); break;
case 12: asm("movdqa %%xmm12, %0" : "=m"(*data)); break;
case 13: asm("movdqa %%xmm13, %0" : "=m"(*data)); break;
case 14: asm("movdqa %%xmm14, %0" : "=m"(*data)); break;
case 15: asm("movdqa %%xmm15, %0" : "=m"(*data)); break;
#endif
default: BUG();
}
ctxt->ops->put_fpu(ctxt);
}
static void write_sse_reg(struct x86_emulate_ctxt *ctxt, sse128_t *data,
int reg)
{
ctxt->ops->get_fpu(ctxt);
switch (reg) {
case 0: asm("movdqa %0, %%xmm0" : : "m"(*data)); break;
case 1: asm("movdqa %0, %%xmm1" : : "m"(*data)); break;
case 2: asm("movdqa %0, %%xmm2" : : "m"(*data)); break;
case 3: asm("movdqa %0, %%xmm3" : : "m"(*data)); break;
case 4: asm("movdqa %0, %%xmm4" : : "m"(*data)); break;
case 5: asm("movdqa %0, %%xmm5" : : "m"(*data)); break;
case 6: asm("movdqa %0, %%xmm6" : : "m"(*data)); break;
case 7: asm("movdqa %0, %%xmm7" : : "m"(*data)); break;
#ifdef CONFIG_X86_64
case 8: asm("movdqa %0, %%xmm8" : : "m"(*data)); break;
case 9: asm("movdqa %0, %%xmm9" : : "m"(*data)); break;
case 10: asm("movdqa %0, %%xmm10" : : "m"(*data)); break;
case 11: asm("movdqa %0, %%xmm11" : : "m"(*data)); break;
case 12: asm("movdqa %0, %%xmm12" : : "m"(*data)); break;
case 13: asm("movdqa %0, %%xmm13" : : "m"(*data)); break;
case 14: asm("movdqa %0, %%xmm14" : : "m"(*data)); break;
case 15: asm("movdqa %0, %%xmm15" : : "m"(*data)); break;
#endif
default: BUG();
}
ctxt->ops->put_fpu(ctxt);
}
static void read_mmx_reg(struct x86_emulate_ctxt *ctxt, u64 *data, int reg)
{
ctxt->ops->get_fpu(ctxt);
switch (reg) {
case 0: asm("movq %%mm0, %0" : "=m"(*data)); break;
case 1: asm("movq %%mm1, %0" : "=m"(*data)); break;
case 2: asm("movq %%mm2, %0" : "=m"(*data)); break;
case 3: asm("movq %%mm3, %0" : "=m"(*data)); break;
case 4: asm("movq %%mm4, %0" : "=m"(*data)); break;
case 5: asm("movq %%mm5, %0" : "=m"(*data)); break;
case 6: asm("movq %%mm6, %0" : "=m"(*data)); break;
case 7: asm("movq %%mm7, %0" : "=m"(*data)); break;
default: BUG();
}
ctxt->ops->put_fpu(ctxt);
}
static void write_mmx_reg(struct x86_emulate_ctxt *ctxt, u64 *data, int reg)
{
ctxt->ops->get_fpu(ctxt);
switch (reg) {
case 0: asm("movq %0, %%mm0" : : "m"(*data)); break;
case 1: asm("movq %0, %%mm1" : : "m"(*data)); break;
case 2: asm("movq %0, %%mm2" : : "m"(*data)); break;
case 3: asm("movq %0, %%mm3" : : "m"(*data)); break;
case 4: asm("movq %0, %%mm4" : : "m"(*data)); break;
case 5: asm("movq %0, %%mm5" : : "m"(*data)); break;
case 6: asm("movq %0, %%mm6" : : "m"(*data)); break;
case 7: asm("movq %0, %%mm7" : : "m"(*data)); break;
default: BUG();
}
ctxt->ops->put_fpu(ctxt);
}
static int em_fninit(struct x86_emulate_ctxt *ctxt)
{
if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
return emulate_nm(ctxt);
ctxt->ops->get_fpu(ctxt);
asm volatile("fninit");
ctxt->ops->put_fpu(ctxt);
return X86EMUL_CONTINUE;
}
static int em_fnstcw(struct x86_emulate_ctxt *ctxt)
{
u16 fcw;
if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
return emulate_nm(ctxt);
ctxt->ops->get_fpu(ctxt);
asm volatile("fnstcw %0": "+m"(fcw));
ctxt->ops->put_fpu(ctxt);
ctxt->dst.val = fcw;
return X86EMUL_CONTINUE;
}
static int em_fnstsw(struct x86_emulate_ctxt *ctxt)
{
u16 fsw;
if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
return emulate_nm(ctxt);
ctxt->ops->get_fpu(ctxt);
asm volatile("fnstsw %0": "+m"(fsw));
ctxt->ops->put_fpu(ctxt);
ctxt->dst.val = fsw;
return X86EMUL_CONTINUE;
}
static void decode_register_operand(struct x86_emulate_ctxt *ctxt,
struct operand *op)
{
unsigned reg = ctxt->modrm_reg;
if (!(ctxt->d & ModRM))
reg = (ctxt->b & 7) | ((ctxt->rex_prefix & 1) << 3);
if (ctxt->d & Sse) {
op->type = OP_XMM;
op->bytes = 16;
op->addr.xmm = reg;
read_sse_reg(ctxt, &op->vec_val, reg);
return;
}
if (ctxt->d & Mmx) {
reg &= 7;
op->type = OP_MM;
op->bytes = 8;
op->addr.mm = reg;
return;
}
op->type = OP_REG;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.reg = decode_register(ctxt, reg, ctxt->d & ByteOp);
fetch_register_operand(op);
op->orig_val = op->val;
}
static void adjust_modrm_seg(struct x86_emulate_ctxt *ctxt, int base_reg)
{
if (base_reg == VCPU_REGS_RSP || base_reg == VCPU_REGS_RBP)
ctxt->modrm_seg = VCPU_SREG_SS;
}
static int decode_modrm(struct x86_emulate_ctxt *ctxt,
struct operand *op)
{
u8 sib;
int index_reg, base_reg, scale;
int rc = X86EMUL_CONTINUE;
ulong modrm_ea = 0;
ctxt->modrm_reg = ((ctxt->rex_prefix << 1) & 8); /* REX.R */
index_reg = (ctxt->rex_prefix << 2) & 8; /* REX.X */
base_reg = (ctxt->rex_prefix << 3) & 8; /* REX.B */
ctxt->modrm_mod = (ctxt->modrm & 0xc0) >> 6;
ctxt->modrm_reg |= (ctxt->modrm & 0x38) >> 3;
ctxt->modrm_rm = base_reg | (ctxt->modrm & 0x07);
ctxt->modrm_seg = VCPU_SREG_DS;
if (ctxt->modrm_mod == 3 || (ctxt->d & NoMod)) {
op->type = OP_REG;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.reg = decode_register(ctxt, ctxt->modrm_rm,
ctxt->d & ByteOp);
if (ctxt->d & Sse) {
op->type = OP_XMM;
op->bytes = 16;
op->addr.xmm = ctxt->modrm_rm;
read_sse_reg(ctxt, &op->vec_val, ctxt->modrm_rm);
return rc;
}
if (ctxt->d & Mmx) {
op->type = OP_MM;
op->bytes = 8;
op->addr.mm = ctxt->modrm_rm & 7;
return rc;
}
fetch_register_operand(op);
return rc;
}
op->type = OP_MEM;
if (ctxt->ad_bytes == 2) {
unsigned bx = reg_read(ctxt, VCPU_REGS_RBX);
unsigned bp = reg_read(ctxt, VCPU_REGS_RBP);
unsigned si = reg_read(ctxt, VCPU_REGS_RSI);
unsigned di = reg_read(ctxt, VCPU_REGS_RDI);
/* 16-bit ModR/M decode. */
switch (ctxt->modrm_mod) {
case 0:
if (ctxt->modrm_rm == 6)
modrm_ea += insn_fetch(u16, ctxt);
break;
case 1:
modrm_ea += insn_fetch(s8, ctxt);
break;
case 2:
modrm_ea += insn_fetch(u16, ctxt);
break;
}
switch (ctxt->modrm_rm) {
case 0:
modrm_ea += bx + si;
break;
case 1:
modrm_ea += bx + di;
break;
case 2:
modrm_ea += bp + si;
break;
case 3:
modrm_ea += bp + di;
break;
case 4:
modrm_ea += si;
break;
case 5:
modrm_ea += di;
break;
case 6:
if (ctxt->modrm_mod != 0)
modrm_ea += bp;
break;
case 7:
modrm_ea += bx;
break;
}
if (ctxt->modrm_rm == 2 || ctxt->modrm_rm == 3 ||
(ctxt->modrm_rm == 6 && ctxt->modrm_mod != 0))
ctxt->modrm_seg = VCPU_SREG_SS;
modrm_ea = (u16)modrm_ea;
} else {
/* 32/64-bit ModR/M decode. */
if ((ctxt->modrm_rm & 7) == 4) {
sib = insn_fetch(u8, ctxt);
index_reg |= (sib >> 3) & 7;
base_reg |= sib & 7;
scale = sib >> 6;
if ((base_reg & 7) == 5 && ctxt->modrm_mod == 0)
modrm_ea += insn_fetch(s32, ctxt);
else {
modrm_ea += reg_read(ctxt, base_reg);
adjust_modrm_seg(ctxt, base_reg);
/* Increment ESP on POP [ESP] */
if ((ctxt->d & IncSP) &&
base_reg == VCPU_REGS_RSP)
modrm_ea += ctxt->op_bytes;
}
if (index_reg != 4)
modrm_ea += reg_read(ctxt, index_reg) << scale;
} else if ((ctxt->modrm_rm & 7) == 5 && ctxt->modrm_mod == 0) {
modrm_ea += insn_fetch(s32, ctxt);
if (ctxt->mode == X86EMUL_MODE_PROT64)
ctxt->rip_relative = 1;
} else {
base_reg = ctxt->modrm_rm;
modrm_ea += reg_read(ctxt, base_reg);
adjust_modrm_seg(ctxt, base_reg);
}
switch (ctxt->modrm_mod) {
case 1:
modrm_ea += insn_fetch(s8, ctxt);
break;
case 2:
modrm_ea += insn_fetch(s32, ctxt);
break;
}
}
op->addr.mem.ea = modrm_ea;
if (ctxt->ad_bytes != 8)
ctxt->memop.addr.mem.ea = (u32)ctxt->memop.addr.mem.ea;
done:
return rc;
}
static int decode_abs(struct x86_emulate_ctxt *ctxt,
struct operand *op)
{
int rc = X86EMUL_CONTINUE;
op->type = OP_MEM;
switch (ctxt->ad_bytes) {
case 2:
op->addr.mem.ea = insn_fetch(u16, ctxt);
break;
case 4:
op->addr.mem.ea = insn_fetch(u32, ctxt);
break;
case 8:
op->addr.mem.ea = insn_fetch(u64, ctxt);
break;
}
done:
return rc;
}
static void fetch_bit_operand(struct x86_emulate_ctxt *ctxt)
{
long sv = 0, mask;
if (ctxt->dst.type == OP_MEM && ctxt->src.type == OP_REG) {
mask = ~((long)ctxt->dst.bytes * 8 - 1);
if (ctxt->src.bytes == 2)
sv = (s16)ctxt->src.val & (s16)mask;
else if (ctxt->src.bytes == 4)
sv = (s32)ctxt->src.val & (s32)mask;
else
sv = (s64)ctxt->src.val & (s64)mask;
ctxt->dst.addr.mem.ea = address_mask(ctxt,
ctxt->dst.addr.mem.ea + (sv >> 3));
}
/* only subword offset */
ctxt->src.val &= (ctxt->dst.bytes << 3) - 1;
}
static int read_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr, void *dest, unsigned size)
{
int rc;
struct read_cache *mc = &ctxt->mem_read;
if (mc->pos < mc->end)
goto read_cached;
WARN_ON((mc->end + size) >= sizeof(mc->data));
rc = ctxt->ops->read_emulated(ctxt, addr, mc->data + mc->end, size,
&ctxt->exception);
if (rc != X86EMUL_CONTINUE)
return rc;
mc->end += size;
read_cached:
memcpy(dest, mc->data + mc->pos, size);
mc->pos += size;
return X86EMUL_CONTINUE;
}
static int segmented_read(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
void *data,
unsigned size)
{
int rc;
ulong linear;
rc = linearize(ctxt, addr, size, false, &linear);
if (rc != X86EMUL_CONTINUE)
return rc;
return read_emulated(ctxt, linear, data, size);
}
static int segmented_write(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
const void *data,
unsigned size)
{
int rc;
ulong linear;
rc = linearize(ctxt, addr, size, true, &linear);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->write_emulated(ctxt, linear, data, size,
&ctxt->exception);
}
static int segmented_cmpxchg(struct x86_emulate_ctxt *ctxt,
struct segmented_address addr,
const void *orig_data, const void *data,
unsigned size)
{
int rc;
ulong linear;
rc = linearize(ctxt, addr, size, true, &linear);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->cmpxchg_emulated(ctxt, linear, orig_data, data,
size, &ctxt->exception);
}
static int pio_in_emulated(struct x86_emulate_ctxt *ctxt,
unsigned int size, unsigned short port,
void *dest)
{
struct read_cache *rc = &ctxt->io_read;
if (rc->pos == rc->end) { /* refill pio read ahead */
unsigned int in_page, n;
unsigned int count = ctxt->rep_prefix ?
address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) : 1;
in_page = (ctxt->eflags & X86_EFLAGS_DF) ?
offset_in_page(reg_read(ctxt, VCPU_REGS_RDI)) :
PAGE_SIZE - offset_in_page(reg_read(ctxt, VCPU_REGS_RDI));
n = min3(in_page, (unsigned int)sizeof(rc->data) / size, count);
if (n == 0)
n = 1;
rc->pos = rc->end = 0;
if (!ctxt->ops->pio_in_emulated(ctxt, size, port, rc->data, n))
return 0;
rc->end = n * size;
}
if (ctxt->rep_prefix && (ctxt->d & String) &&
!(ctxt->eflags & X86_EFLAGS_DF)) {
ctxt->dst.data = rc->data + rc->pos;
ctxt->dst.type = OP_MEM_STR;
ctxt->dst.count = (rc->end - rc->pos) / size;
rc->pos = rc->end;
} else {
memcpy(dest, rc->data + rc->pos, size);
rc->pos += size;
}
return 1;
}
static int read_interrupt_descriptor(struct x86_emulate_ctxt *ctxt,
u16 index, struct desc_struct *desc)
{
struct desc_ptr dt;
ulong addr;
ctxt->ops->get_idt(ctxt, &dt);
if (dt.size < index * 8 + 7)
return emulate_gp(ctxt, index << 3 | 0x2);
addr = dt.address + index * 8;
return ctxt->ops->read_std(ctxt, addr, desc, sizeof *desc,
&ctxt->exception);
}
static void get_descriptor_table_ptr(struct x86_emulate_ctxt *ctxt,
u16 selector, struct desc_ptr *dt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
u32 base3 = 0;
if (selector & 1 << 2) {
struct desc_struct desc;
u16 sel;
memset (dt, 0, sizeof *dt);
if (!ops->get_segment(ctxt, &sel, &desc, &base3,
VCPU_SREG_LDTR))
return;
dt->size = desc_limit_scaled(&desc); /* what if limit > 65535? */
dt->address = get_desc_base(&desc) | ((u64)base3 << 32);
} else
ops->get_gdt(ctxt, dt);
}
static int get_descriptor_ptr(struct x86_emulate_ctxt *ctxt,
u16 selector, ulong *desc_addr_p)
{
struct desc_ptr dt;
u16 index = selector >> 3;
ulong addr;
get_descriptor_table_ptr(ctxt, selector, &dt);
if (dt.size < index * 8 + 7)
return emulate_gp(ctxt, selector & 0xfffc);
addr = dt.address + index * 8;
#ifdef CONFIG_X86_64
if (addr >> 32 != 0) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (!(efer & EFER_LMA))
addr &= (u32)-1;
}
#endif
*desc_addr_p = addr;
return X86EMUL_CONTINUE;
}
/* allowed just for 8 bytes segments */
static int read_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, struct desc_struct *desc,
ulong *desc_addr_p)
{
int rc;
rc = get_descriptor_ptr(ctxt, selector, desc_addr_p);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->read_std(ctxt, *desc_addr_p, desc, sizeof(*desc),
&ctxt->exception);
}
/* allowed just for 8 bytes segments */
static int write_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, struct desc_struct *desc)
{
int rc;
ulong addr;
rc = get_descriptor_ptr(ctxt, selector, &addr);
if (rc != X86EMUL_CONTINUE)
return rc;
return ctxt->ops->write_std(ctxt, addr, desc, sizeof *desc,
&ctxt->exception);
}
/* Does not support long mode */
static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg, u8 cpl,
enum x86_transfer_type transfer,
struct desc_struct *desc)
{
struct desc_struct seg_desc, old_desc;
u8 dpl, rpl;
unsigned err_vec = GP_VECTOR;
u32 err_code = 0;
bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
ulong desc_addr;
int ret;
u16 dummy;
u32 base3 = 0;
memset(&seg_desc, 0, sizeof seg_desc);
if (ctxt->mode == X86EMUL_MODE_REAL) {
/* set real mode segment descriptor (keep limit etc. for
* unreal mode) */
ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);
set_desc_base(&seg_desc, selector << 4);
goto load;
} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {
/* VM86 needs a clean new segment descriptor */
set_desc_base(&seg_desc, selector << 4);
set_desc_limit(&seg_desc, 0xffff);
seg_desc.type = 3;
seg_desc.p = 1;
seg_desc.s = 1;
seg_desc.dpl = 3;
goto load;
}
rpl = selector & 3;
/* NULL selector is not valid for TR, CS and SS (except for long mode) */
if ((seg == VCPU_SREG_CS
|| (seg == VCPU_SREG_SS
&& (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl))
|| seg == VCPU_SREG_TR)
&& null_selector)
goto exception;
/* TR should be in GDT only */
if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
goto exception;
if (null_selector) /* for NULL selector skip all following checks */
goto load;
ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
err_code = selector & 0xfffc;
err_vec = (transfer == X86_TRANSFER_TASK_SWITCH) ? TS_VECTOR :
GP_VECTOR;
/* can't load system descriptor into segment selector */
if (seg <= VCPU_SREG_GS && !seg_desc.s) {
if (transfer == X86_TRANSFER_CALL_JMP)
return X86EMUL_UNHANDLEABLE;
goto exception;
}
if (!seg_desc.p) {
err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
goto exception;
}
dpl = seg_desc.dpl;
switch (seg) {
case VCPU_SREG_SS:
/*
* segment is not a writable data segment or segment
* selector's RPL != CPL or segment selector's RPL != CPL
*/
if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
goto exception;
break;
case VCPU_SREG_CS:
if (!(seg_desc.type & 8))
goto exception;
if (seg_desc.type & 4) {
/* conforming */
if (dpl > cpl)
goto exception;
} else {
/* nonconforming */
if (rpl > cpl || dpl != cpl)
goto exception;
}
/* in long-mode d/b must be clear if l is set */
if (seg_desc.d && seg_desc.l) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
goto exception;
}
/* CS(RPL) <- CPL */
selector = (selector & 0xfffc) | cpl;
break;
case VCPU_SREG_TR:
if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
goto exception;
old_desc = seg_desc;
seg_desc.type |= 2; /* busy */
ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,
sizeof(seg_desc), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
break;
case VCPU_SREG_LDTR:
if (seg_desc.s || seg_desc.type != 2)
goto exception;
break;
default: /* DS, ES, FS, or GS */
/*
* segment is not a data or readable code segment or
* ((segment is a data or nonconforming code segment)
* and (both RPL and CPL > DPL))
*/
if ((seg_desc.type & 0xa) == 0x8 ||
(((seg_desc.type & 0xc) != 0xc) &&
(rpl > dpl && cpl > dpl)))
goto exception;
break;
}
if (seg_desc.s) {
/* mark segment as accessed */
if (!(seg_desc.type & 1)) {
seg_desc.type |= 1;
ret = write_segment_descriptor(ctxt, selector,
&seg_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
}
} else if (ctxt->mode == X86EMUL_MODE_PROT64) {
ret = ctxt->ops->read_std(ctxt, desc_addr+8, &base3,
sizeof(base3), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
if (is_noncanonical_address(get_desc_base(&seg_desc) |
((u64)base3 << 32)))
return emulate_gp(ctxt, 0);
}
load:
ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);
if (desc)
*desc = seg_desc;
return X86EMUL_CONTINUE;
exception:
return emulate_exception(ctxt, err_vec, err_code, true);
}
static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg)
{
u8 cpl = ctxt->ops->cpl(ctxt);
return __load_segment_descriptor(ctxt, selector, seg, cpl,
X86_TRANSFER_NONE, NULL);
}
static void write_register_operand(struct operand *op)
{
return assign_register(op->addr.reg, op->val, op->bytes);
}
static int writeback(struct x86_emulate_ctxt *ctxt, struct operand *op)
{
switch (op->type) {
case OP_REG:
write_register_operand(op);
break;
case OP_MEM:
if (ctxt->lock_prefix)
return segmented_cmpxchg(ctxt,
op->addr.mem,
&op->orig_val,
&op->val,
op->bytes);
else
return segmented_write(ctxt,
op->addr.mem,
&op->val,
op->bytes);
break;
case OP_MEM_STR:
return segmented_write(ctxt,
op->addr.mem,
op->data,
op->bytes * op->count);
break;
case OP_XMM:
write_sse_reg(ctxt, &op->vec_val, op->addr.xmm);
break;
case OP_MM:
write_mmx_reg(ctxt, &op->mm_val, op->addr.mm);
break;
case OP_NONE:
/* no writeback */
break;
default:
break;
}
return X86EMUL_CONTINUE;
}
static int push(struct x86_emulate_ctxt *ctxt, void *data, int bytes)
{
struct segmented_address addr;
rsp_increment(ctxt, -bytes);
addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt);
addr.seg = VCPU_SREG_SS;
return segmented_write(ctxt, addr, data, bytes);
}
static int em_push(struct x86_emulate_ctxt *ctxt)
{
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return push(ctxt, &ctxt->src.val, ctxt->op_bytes);
}
static int emulate_pop(struct x86_emulate_ctxt *ctxt,
void *dest, int len)
{
int rc;
struct segmented_address addr;
addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt);
addr.seg = VCPU_SREG_SS;
rc = segmented_read(ctxt, addr, dest, len);
if (rc != X86EMUL_CONTINUE)
return rc;
rsp_increment(ctxt, len);
return rc;
}
static int em_pop(struct x86_emulate_ctxt *ctxt)
{
return emulate_pop(ctxt, &ctxt->dst.val, ctxt->op_bytes);
}
static int emulate_popf(struct x86_emulate_ctxt *ctxt,
void *dest, int len)
{
int rc;
unsigned long val, change_mask;
int iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> X86_EFLAGS_IOPL_BIT;
int cpl = ctxt->ops->cpl(ctxt);
rc = emulate_pop(ctxt, &val, len);
if (rc != X86EMUL_CONTINUE)
return rc;
change_mask = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF |
X86_EFLAGS_TF | X86_EFLAGS_DF | X86_EFLAGS_NT |
X86_EFLAGS_AC | X86_EFLAGS_ID;
switch(ctxt->mode) {
case X86EMUL_MODE_PROT64:
case X86EMUL_MODE_PROT32:
case X86EMUL_MODE_PROT16:
if (cpl == 0)
change_mask |= X86_EFLAGS_IOPL;
if (cpl <= iopl)
change_mask |= X86_EFLAGS_IF;
break;
case X86EMUL_MODE_VM86:
if (iopl < 3)
return emulate_gp(ctxt, 0);
change_mask |= X86_EFLAGS_IF;
break;
default: /* real mode */
change_mask |= (X86_EFLAGS_IOPL | X86_EFLAGS_IF);
break;
}
*(unsigned long *)dest =
(ctxt->eflags & ~change_mask) | (val & change_mask);
return rc;
}
static int em_popf(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.type = OP_REG;
ctxt->dst.addr.reg = &ctxt->eflags;
ctxt->dst.bytes = ctxt->op_bytes;
return emulate_popf(ctxt, &ctxt->dst.val, ctxt->op_bytes);
}
static int em_enter(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned frame_size = ctxt->src.val;
unsigned nesting_level = ctxt->src2.val & 31;
ulong rbp;
if (nesting_level)
return X86EMUL_UNHANDLEABLE;
rbp = reg_read(ctxt, VCPU_REGS_RBP);
rc = push(ctxt, &rbp, stack_size(ctxt));
if (rc != X86EMUL_CONTINUE)
return rc;
assign_masked(reg_rmw(ctxt, VCPU_REGS_RBP), reg_read(ctxt, VCPU_REGS_RSP),
stack_mask(ctxt));
assign_masked(reg_rmw(ctxt, VCPU_REGS_RSP),
reg_read(ctxt, VCPU_REGS_RSP) - frame_size,
stack_mask(ctxt));
return X86EMUL_CONTINUE;
}
static int em_leave(struct x86_emulate_ctxt *ctxt)
{
assign_masked(reg_rmw(ctxt, VCPU_REGS_RSP), reg_read(ctxt, VCPU_REGS_RBP),
stack_mask(ctxt));
return emulate_pop(ctxt, reg_rmw(ctxt, VCPU_REGS_RBP), ctxt->op_bytes);
}
static int em_push_sreg(struct x86_emulate_ctxt *ctxt)
{
int seg = ctxt->src2.val;
ctxt->src.val = get_segment_selector(ctxt, seg);
if (ctxt->op_bytes == 4) {
rsp_increment(ctxt, -2);
ctxt->op_bytes = 2;
}
return em_push(ctxt);
}
static int em_pop_sreg(struct x86_emulate_ctxt *ctxt)
{
int seg = ctxt->src2.val;
unsigned long selector;
int rc;
rc = emulate_pop(ctxt, &selector, 2);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->modrm_reg == VCPU_SREG_SS)
ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS;
if (ctxt->op_bytes > 2)
rsp_increment(ctxt, ctxt->op_bytes - 2);
rc = load_segment_descriptor(ctxt, (u16)selector, seg);
return rc;
}
static int em_pusha(struct x86_emulate_ctxt *ctxt)
{
unsigned long old_esp = reg_read(ctxt, VCPU_REGS_RSP);
int rc = X86EMUL_CONTINUE;
int reg = VCPU_REGS_RAX;
while (reg <= VCPU_REGS_RDI) {
(reg == VCPU_REGS_RSP) ?
(ctxt->src.val = old_esp) : (ctxt->src.val = reg_read(ctxt, reg));
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
++reg;
}
return rc;
}
static int em_pushf(struct x86_emulate_ctxt *ctxt)
{
ctxt->src.val = (unsigned long)ctxt->eflags & ~X86_EFLAGS_VM;
return em_push(ctxt);
}
static int em_popa(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
int reg = VCPU_REGS_RDI;
u32 val;
while (reg >= VCPU_REGS_RAX) {
if (reg == VCPU_REGS_RSP) {
rsp_increment(ctxt, ctxt->op_bytes);
--reg;
}
rc = emulate_pop(ctxt, &val, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
break;
assign_register(reg_rmw(ctxt, reg), val, ctxt->op_bytes);
--reg;
}
return rc;
}
static int __emulate_int_real(struct x86_emulate_ctxt *ctxt, int irq)
{
const struct x86_emulate_ops *ops = ctxt->ops;
int rc;
struct desc_ptr dt;
gva_t cs_addr;
gva_t eip_addr;
u16 cs, eip;
/* TODO: Add limit checks */
ctxt->src.val = ctxt->eflags;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->eflags &= ~(X86_EFLAGS_IF | X86_EFLAGS_TF | X86_EFLAGS_AC);
ctxt->src.val = get_segment_selector(ctxt, VCPU_SREG_CS);
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->src.val = ctxt->_eip;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ops->get_idt(ctxt, &dt);
eip_addr = dt.address + (irq << 2);
cs_addr = dt.address + (irq << 2) + 2;
rc = ops->read_std(ctxt, cs_addr, &cs, 2, &ctxt->exception);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = ops->read_std(ctxt, eip_addr, &eip, 2, &ctxt->exception);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = load_segment_descriptor(ctxt, cs, VCPU_SREG_CS);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->_eip = eip;
return rc;
}
int emulate_int_real(struct x86_emulate_ctxt *ctxt, int irq)
{
int rc;
invalidate_registers(ctxt);
rc = __emulate_int_real(ctxt, irq);
if (rc == X86EMUL_CONTINUE)
writeback_registers(ctxt);
return rc;
}
static int emulate_int(struct x86_emulate_ctxt *ctxt, int irq)
{
switch(ctxt->mode) {
case X86EMUL_MODE_REAL:
return __emulate_int_real(ctxt, irq);
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
case X86EMUL_MODE_PROT32:
case X86EMUL_MODE_PROT64:
default:
/* Protected mode interrupts unimplemented yet */
return X86EMUL_UNHANDLEABLE;
}
}
static int emulate_iret_real(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
unsigned long temp_eip = 0;
unsigned long temp_eflags = 0;
unsigned long cs = 0;
unsigned long mask = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_TF |
X86_EFLAGS_IF | X86_EFLAGS_DF | X86_EFLAGS_OF |
X86_EFLAGS_IOPL | X86_EFLAGS_NT | X86_EFLAGS_RF |
X86_EFLAGS_AC | X86_EFLAGS_ID |
X86_EFLAGS_FIXED;
unsigned long vm86_mask = X86_EFLAGS_VM | X86_EFLAGS_VIF |
X86_EFLAGS_VIP;
/* TODO: Add stack limit check */
rc = emulate_pop(ctxt, &temp_eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
if (temp_eip & ~0xffff)
return emulate_gp(ctxt, 0);
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &temp_eflags, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->_eip = temp_eip;
if (ctxt->op_bytes == 4)
ctxt->eflags = ((temp_eflags & mask) | (ctxt->eflags & vm86_mask));
else if (ctxt->op_bytes == 2) {
ctxt->eflags &= ~0xffff;
ctxt->eflags |= temp_eflags;
}
ctxt->eflags &= ~EFLG_RESERVED_ZEROS_MASK; /* Clear reserved zeros */
ctxt->eflags |= X86_EFLAGS_FIXED;
ctxt->ops->set_nmi_mask(ctxt, false);
return rc;
}
static int em_iret(struct x86_emulate_ctxt *ctxt)
{
switch(ctxt->mode) {
case X86EMUL_MODE_REAL:
return emulate_iret_real(ctxt);
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
case X86EMUL_MODE_PROT32:
case X86EMUL_MODE_PROT64:
default:
/* iret from protected mode unimplemented yet */
return X86EMUL_UNHANDLEABLE;
}
}
static int em_jmp_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned short sel, old_sel;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
u8 cpl = ctxt->ops->cpl(ctxt);
/* Assignment of RIP may only fail in 64-bit mode */
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_sel, &old_desc, NULL,
VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,
X86_TRANSFER_CALL_JMP,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, ctxt->src.val, &new_desc);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);
/* assigning eip failed; restore the old cs */
ops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS);
return rc;
}
return rc;
}
static int em_jmp_abs(struct x86_emulate_ctxt *ctxt)
{
return assign_eip_near(ctxt, ctxt->src.val);
}
static int em_call_near_abs(struct x86_emulate_ctxt *ctxt)
{
int rc;
long int old_eip;
old_eip = ctxt->_eip;
rc = assign_eip_near(ctxt, ctxt->src.val);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->src.val = old_eip;
rc = em_push(ctxt);
return rc;
}
static int em_cmpxchg8b(struct x86_emulate_ctxt *ctxt)
{
u64 old = ctxt->dst.orig_val64;
if (ctxt->dst.bytes == 16)
return X86EMUL_UNHANDLEABLE;
if (((u32) (old >> 0) != (u32) reg_read(ctxt, VCPU_REGS_RAX)) ||
((u32) (old >> 32) != (u32) reg_read(ctxt, VCPU_REGS_RDX))) {
*reg_write(ctxt, VCPU_REGS_RAX) = (u32) (old >> 0);
*reg_write(ctxt, VCPU_REGS_RDX) = (u32) (old >> 32);
ctxt->eflags &= ~X86_EFLAGS_ZF;
} else {
ctxt->dst.val64 = ((u64)reg_read(ctxt, VCPU_REGS_RCX) << 32) |
(u32) reg_read(ctxt, VCPU_REGS_RBX);
ctxt->eflags |= X86_EFLAGS_ZF;
}
return X86EMUL_CONTINUE;
}
static int em_ret(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip;
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
return assign_eip_near(ctxt, eip);
}
static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip, cs;
u16 old_cs;
int cpl = ctxt->ops->cpl(ctxt);
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_cs, &old_desc, NULL,
VCPU_SREG_CS);
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, cpl,
X86_TRANSFER_RET,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, eip, &new_desc);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
}
return rc;
}
static int em_ret_far_imm(struct x86_emulate_ctxt *ctxt)
{
int rc;
rc = em_ret_far(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
rsp_increment(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
static int em_cmpxchg(struct x86_emulate_ctxt *ctxt)
{
/* Save real source value, then compare EAX against destination. */
ctxt->dst.orig_val = ctxt->dst.val;
ctxt->dst.val = reg_read(ctxt, VCPU_REGS_RAX);
ctxt->src.orig_val = ctxt->src.val;
ctxt->src.val = ctxt->dst.orig_val;
fastop(ctxt, em_cmp);
if (ctxt->eflags & X86_EFLAGS_ZF) {
/* Success: write back to memory; no update of EAX */
ctxt->src.type = OP_NONE;
ctxt->dst.val = ctxt->src.orig_val;
} else {
/* Failure: write the value we saw to EAX. */
ctxt->src.type = OP_REG;
ctxt->src.addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
ctxt->src.val = ctxt->dst.orig_val;
/* Create write-cycle to dest by writing the same value */
ctxt->dst.val = ctxt->dst.orig_val;
}
return X86EMUL_CONTINUE;
}
static int em_lseg(struct x86_emulate_ctxt *ctxt)
{
int seg = ctxt->src2.val;
unsigned short sel;
int rc;
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = load_segment_descriptor(ctxt, sel, seg);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->dst.val = ctxt->src.val;
return rc;
}
static int emulator_has_longmode(struct x86_emulate_ctxt *ctxt)
{
u32 eax, ebx, ecx, edx;
eax = 0x80000001;
ecx = 0;
ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
return edx & bit(X86_FEATURE_LM);
}
#define GET_SMSTATE(type, smbase, offset) \
({ \
type __val; \
int r = ctxt->ops->read_phys(ctxt, smbase + offset, &__val, \
sizeof(__val)); \
if (r != X86EMUL_CONTINUE) \
return X86EMUL_UNHANDLEABLE; \
__val; \
})
static void rsm_set_desc_flags(struct desc_struct *desc, u32 flags)
{
desc->g = (flags >> 23) & 1;
desc->d = (flags >> 22) & 1;
desc->l = (flags >> 21) & 1;
desc->avl = (flags >> 20) & 1;
desc->p = (flags >> 15) & 1;
desc->dpl = (flags >> 13) & 3;
desc->s = (flags >> 12) & 1;
desc->type = (flags >> 8) & 15;
}
static int rsm_load_seg_32(struct x86_emulate_ctxt *ctxt, u64 smbase, int n)
{
struct desc_struct desc;
int offset;
u16 selector;
selector = GET_SMSTATE(u32, smbase, 0x7fa8 + n * 4);
if (n < 3)
offset = 0x7f84 + n * 12;
else
offset = 0x7f2c + (n - 3) * 12;
set_desc_base(&desc, GET_SMSTATE(u32, smbase, offset + 8));
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, offset + 4));
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, offset));
ctxt->ops->set_segment(ctxt, selector, &desc, 0, n);
return X86EMUL_CONTINUE;
}
static int rsm_load_seg_64(struct x86_emulate_ctxt *ctxt, u64 smbase, int n)
{
struct desc_struct desc;
int offset;
u16 selector;
u32 base3;
offset = 0x7e00 + n * 16;
selector = GET_SMSTATE(u16, smbase, offset);
rsm_set_desc_flags(&desc, GET_SMSTATE(u16, smbase, offset + 2) << 8);
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, offset + 4));
set_desc_base(&desc, GET_SMSTATE(u32, smbase, offset + 8));
base3 = GET_SMSTATE(u32, smbase, offset + 12);
ctxt->ops->set_segment(ctxt, selector, &desc, base3, n);
return X86EMUL_CONTINUE;
}
static int rsm_enter_protected_mode(struct x86_emulate_ctxt *ctxt,
u64 cr0, u64 cr4)
{
int bad;
/*
* First enable PAE, long mode needs it before CR0.PG = 1 is set.
* Then enable protected mode. However, PCID cannot be enabled
* if EFER.LMA=0, so set it separately.
*/
bad = ctxt->ops->set_cr(ctxt, 4, cr4 & ~X86_CR4_PCIDE);
if (bad)
return X86EMUL_UNHANDLEABLE;
bad = ctxt->ops->set_cr(ctxt, 0, cr0);
if (bad)
return X86EMUL_UNHANDLEABLE;
if (cr4 & X86_CR4_PCIDE) {
bad = ctxt->ops->set_cr(ctxt, 4, cr4);
if (bad)
return X86EMUL_UNHANDLEABLE;
}
return X86EMUL_CONTINUE;
}
static int rsm_load_state_32(struct x86_emulate_ctxt *ctxt, u64 smbase)
{
struct desc_struct desc;
struct desc_ptr dt;
u16 selector;
u32 val, cr0, cr4;
int i;
cr0 = GET_SMSTATE(u32, smbase, 0x7ffc);
ctxt->ops->set_cr(ctxt, 3, GET_SMSTATE(u32, smbase, 0x7ff8));
ctxt->eflags = GET_SMSTATE(u32, smbase, 0x7ff4) | X86_EFLAGS_FIXED;
ctxt->_eip = GET_SMSTATE(u32, smbase, 0x7ff0);
for (i = 0; i < 8; i++)
*reg_write(ctxt, i) = GET_SMSTATE(u32, smbase, 0x7fd0 + i * 4);
val = GET_SMSTATE(u32, smbase, 0x7fcc);
ctxt->ops->set_dr(ctxt, 6, (val & DR6_VOLATILE) | DR6_FIXED_1);
val = GET_SMSTATE(u32, smbase, 0x7fc8);
ctxt->ops->set_dr(ctxt, 7, (val & DR7_VOLATILE) | DR7_FIXED_1);
selector = GET_SMSTATE(u32, smbase, 0x7fc4);
set_desc_base(&desc, GET_SMSTATE(u32, smbase, 0x7f64));
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, 0x7f60));
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, 0x7f5c));
ctxt->ops->set_segment(ctxt, selector, &desc, 0, VCPU_SREG_TR);
selector = GET_SMSTATE(u32, smbase, 0x7fc0);
set_desc_base(&desc, GET_SMSTATE(u32, smbase, 0x7f80));
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, 0x7f7c));
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, 0x7f78));
ctxt->ops->set_segment(ctxt, selector, &desc, 0, VCPU_SREG_LDTR);
dt.address = GET_SMSTATE(u32, smbase, 0x7f74);
dt.size = GET_SMSTATE(u32, smbase, 0x7f70);
ctxt->ops->set_gdt(ctxt, &dt);
dt.address = GET_SMSTATE(u32, smbase, 0x7f58);
dt.size = GET_SMSTATE(u32, smbase, 0x7f54);
ctxt->ops->set_idt(ctxt, &dt);
for (i = 0; i < 6; i++) {
int r = rsm_load_seg_32(ctxt, smbase, i);
if (r != X86EMUL_CONTINUE)
return r;
}
cr4 = GET_SMSTATE(u32, smbase, 0x7f14);
ctxt->ops->set_smbase(ctxt, GET_SMSTATE(u32, smbase, 0x7ef8));
return rsm_enter_protected_mode(ctxt, cr0, cr4);
}
static int rsm_load_state_64(struct x86_emulate_ctxt *ctxt, u64 smbase)
{
struct desc_struct desc;
struct desc_ptr dt;
u64 val, cr0, cr4;
u32 base3;
u16 selector;
int i, r;
for (i = 0; i < 16; i++)
*reg_write(ctxt, i) = GET_SMSTATE(u64, smbase, 0x7ff8 - i * 8);
ctxt->_eip = GET_SMSTATE(u64, smbase, 0x7f78);
ctxt->eflags = GET_SMSTATE(u32, smbase, 0x7f70) | X86_EFLAGS_FIXED;
val = GET_SMSTATE(u32, smbase, 0x7f68);
ctxt->ops->set_dr(ctxt, 6, (val & DR6_VOLATILE) | DR6_FIXED_1);
val = GET_SMSTATE(u32, smbase, 0x7f60);
ctxt->ops->set_dr(ctxt, 7, (val & DR7_VOLATILE) | DR7_FIXED_1);
cr0 = GET_SMSTATE(u64, smbase, 0x7f58);
ctxt->ops->set_cr(ctxt, 3, GET_SMSTATE(u64, smbase, 0x7f50));
cr4 = GET_SMSTATE(u64, smbase, 0x7f48);
ctxt->ops->set_smbase(ctxt, GET_SMSTATE(u32, smbase, 0x7f00));
val = GET_SMSTATE(u64, smbase, 0x7ed0);
ctxt->ops->set_msr(ctxt, MSR_EFER, val & ~EFER_LMA);
selector = GET_SMSTATE(u32, smbase, 0x7e90);
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, 0x7e92) << 8);
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, 0x7e94));
set_desc_base(&desc, GET_SMSTATE(u32, smbase, 0x7e98));
base3 = GET_SMSTATE(u32, smbase, 0x7e9c);
ctxt->ops->set_segment(ctxt, selector, &desc, base3, VCPU_SREG_TR);
dt.size = GET_SMSTATE(u32, smbase, 0x7e84);
dt.address = GET_SMSTATE(u64, smbase, 0x7e88);
ctxt->ops->set_idt(ctxt, &dt);
selector = GET_SMSTATE(u32, smbase, 0x7e70);
rsm_set_desc_flags(&desc, GET_SMSTATE(u32, smbase, 0x7e72) << 8);
set_desc_limit(&desc, GET_SMSTATE(u32, smbase, 0x7e74));
set_desc_base(&desc, GET_SMSTATE(u32, smbase, 0x7e78));
base3 = GET_SMSTATE(u32, smbase, 0x7e7c);
ctxt->ops->set_segment(ctxt, selector, &desc, base3, VCPU_SREG_LDTR);
dt.size = GET_SMSTATE(u32, smbase, 0x7e64);
dt.address = GET_SMSTATE(u64, smbase, 0x7e68);
ctxt->ops->set_gdt(ctxt, &dt);
r = rsm_enter_protected_mode(ctxt, cr0, cr4);
if (r != X86EMUL_CONTINUE)
return r;
for (i = 0; i < 6; i++) {
r = rsm_load_seg_64(ctxt, smbase, i);
if (r != X86EMUL_CONTINUE)
return r;
}
return X86EMUL_CONTINUE;
}
static int em_rsm(struct x86_emulate_ctxt *ctxt)
{
unsigned long cr0, cr4, efer;
u64 smbase;
int ret;
if ((ctxt->emul_flags & X86EMUL_SMM_MASK) == 0)
return emulate_ud(ctxt);
/*
* Get back to real mode, to prepare a safe state in which to load
* CR0/CR3/CR4/EFER. It's all a bit more complicated if the vCPU
* supports long mode.
*/
cr4 = ctxt->ops->get_cr(ctxt, 4);
if (emulator_has_longmode(ctxt)) {
struct desc_struct cs_desc;
/* Zero CR4.PCIDE before CR0.PG. */
if (cr4 & X86_CR4_PCIDE) {
ctxt->ops->set_cr(ctxt, 4, cr4 & ~X86_CR4_PCIDE);
cr4 &= ~X86_CR4_PCIDE;
}
/* A 32-bit code segment is required to clear EFER.LMA. */
memset(&cs_desc, 0, sizeof(cs_desc));
cs_desc.type = 0xb;
cs_desc.s = cs_desc.g = cs_desc.p = 1;
ctxt->ops->set_segment(ctxt, 0, &cs_desc, 0, VCPU_SREG_CS);
}
/* For the 64-bit case, this will clear EFER.LMA. */
cr0 = ctxt->ops->get_cr(ctxt, 0);
if (cr0 & X86_CR0_PE)
ctxt->ops->set_cr(ctxt, 0, cr0 & ~(X86_CR0_PG | X86_CR0_PE));
/* Now clear CR4.PAE (which must be done before clearing EFER.LME). */
if (cr4 & X86_CR4_PAE)
ctxt->ops->set_cr(ctxt, 4, cr4 & ~X86_CR4_PAE);
/* And finally go back to 32-bit mode. */
efer = 0;
ctxt->ops->set_msr(ctxt, MSR_EFER, efer);
smbase = ctxt->ops->get_smbase(ctxt);
if (emulator_has_longmode(ctxt))
ret = rsm_load_state_64(ctxt, smbase + 0x8000);
else
ret = rsm_load_state_32(ctxt, smbase + 0x8000);
if (ret != X86EMUL_CONTINUE) {
/* FIXME: should triple fault */
return X86EMUL_UNHANDLEABLE;
}
if ((ctxt->emul_flags & X86EMUL_SMM_INSIDE_NMI_MASK) == 0)
ctxt->ops->set_nmi_mask(ctxt, false);
ctxt->emul_flags &= ~X86EMUL_SMM_INSIDE_NMI_MASK;
ctxt->emul_flags &= ~X86EMUL_SMM_MASK;
return X86EMUL_CONTINUE;
}
static void
setup_syscalls_segments(struct x86_emulate_ctxt *ctxt,
struct desc_struct *cs, struct desc_struct *ss)
{
cs->l = 0; /* will be adjusted later */
set_desc_base(cs, 0); /* flat segment */
cs->g = 1; /* 4kb granularity */
set_desc_limit(cs, 0xfffff); /* 4GB limit */
cs->type = 0x0b; /* Read, Execute, Accessed */
cs->s = 1;
cs->dpl = 0; /* will be adjusted later */
cs->p = 1;
cs->d = 1;
cs->avl = 0;
set_desc_base(ss, 0); /* flat segment */
set_desc_limit(ss, 0xfffff); /* 4GB limit */
ss->g = 1; /* 4kb granularity */
ss->s = 1;
ss->type = 0x03; /* Read/Write, Accessed */
ss->d = 1; /* 32bit stack segment */
ss->dpl = 0;
ss->p = 1;
ss->l = 0;
ss->avl = 0;
}
static bool vendor_intel(struct x86_emulate_ctxt *ctxt)
{
u32 eax, ebx, ecx, edx;
eax = ecx = 0;
ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
return ebx == X86EMUL_CPUID_VENDOR_GenuineIntel_ebx
&& ecx == X86EMUL_CPUID_VENDOR_GenuineIntel_ecx
&& edx == X86EMUL_CPUID_VENDOR_GenuineIntel_edx;
}
static bool em_syscall_is_enabled(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
u32 eax, ebx, ecx, edx;
/*
* syscall should always be enabled in longmode - so only become
* vendor specific (cpuid) if other modes are active...
*/
if (ctxt->mode == X86EMUL_MODE_PROT64)
return true;
eax = 0x00000000;
ecx = 0x00000000;
ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
/*
* Intel ("GenuineIntel")
* remark: Intel CPUs only support "syscall" in 64bit
* longmode. Also an 64bit guest with a
* 32bit compat-app running will #UD !! While this
* behaviour can be fixed (by emulating) into AMD
* response - CPUs of AMD can't behave like Intel.
*/
if (ebx == X86EMUL_CPUID_VENDOR_GenuineIntel_ebx &&
ecx == X86EMUL_CPUID_VENDOR_GenuineIntel_ecx &&
edx == X86EMUL_CPUID_VENDOR_GenuineIntel_edx)
return false;
/* AMD ("AuthenticAMD") */
if (ebx == X86EMUL_CPUID_VENDOR_AuthenticAMD_ebx &&
ecx == X86EMUL_CPUID_VENDOR_AuthenticAMD_ecx &&
edx == X86EMUL_CPUID_VENDOR_AuthenticAMD_edx)
return true;
/* AMD ("AMDisbetter!") */
if (ebx == X86EMUL_CPUID_VENDOR_AMDisbetterI_ebx &&
ecx == X86EMUL_CPUID_VENDOR_AMDisbetterI_ecx &&
edx == X86EMUL_CPUID_VENDOR_AMDisbetterI_edx)
return true;
/* default: (not Intel, not AMD), apply Intel's stricter rules... */
return false;
}
static int em_syscall(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data;
u16 cs_sel, ss_sel;
u64 efer = 0;
/* syscall is not available in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86)
return emulate_ud(ctxt);
if (!(em_syscall_is_enabled(ctxt)))
return emulate_ud(ctxt);
ops->get_msr(ctxt, MSR_EFER, &efer);
setup_syscalls_segments(ctxt, &cs, &ss);
if (!(efer & EFER_SCE))
return emulate_ud(ctxt);
ops->get_msr(ctxt, MSR_STAR, &msr_data);
msr_data >>= 32;
cs_sel = (u16)(msr_data & 0xfffc);
ss_sel = (u16)(msr_data + 8);
if (efer & EFER_LMA) {
cs.d = 0;
cs.l = 1;
}
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
*reg_write(ctxt, VCPU_REGS_RCX) = ctxt->_eip;
if (efer & EFER_LMA) {
#ifdef CONFIG_X86_64
*reg_write(ctxt, VCPU_REGS_R11) = ctxt->eflags;
ops->get_msr(ctxt,
ctxt->mode == X86EMUL_MODE_PROT64 ?
MSR_LSTAR : MSR_CSTAR, &msr_data);
ctxt->_eip = msr_data;
ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data);
ctxt->eflags &= ~msr_data;
ctxt->eflags |= X86_EFLAGS_FIXED;
#endif
} else {
/* legacy mode */
ops->get_msr(ctxt, MSR_STAR, &msr_data);
ctxt->_eip = (u32)msr_data;
ctxt->eflags &= ~(X86_EFLAGS_VM | X86_EFLAGS_IF);
}
return X86EMUL_CONTINUE;
}
static int em_sysenter(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data;
u16 cs_sel, ss_sel;
u64 efer = 0;
ops->get_msr(ctxt, MSR_EFER, &efer);
/* inject #GP if in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL)
return emulate_gp(ctxt, 0);
/*
* Not recognized on AMD in compat mode (but is recognized in legacy
* mode).
*/
if ((ctxt->mode != X86EMUL_MODE_PROT64) && (efer & EFER_LMA)
&& !vendor_intel(ctxt))
return emulate_ud(ctxt);
/* sysenter/sysexit have not been tested in 64bit mode. */
if (ctxt->mode == X86EMUL_MODE_PROT64)
return X86EMUL_UNHANDLEABLE;
setup_syscalls_segments(ctxt, &cs, &ss);
ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
if ((msr_data & 0xfffc) == 0x0)
return emulate_gp(ctxt, 0);
ctxt->eflags &= ~(X86_EFLAGS_VM | X86_EFLAGS_IF);
cs_sel = (u16)msr_data & ~SEGMENT_RPL_MASK;
ss_sel = cs_sel + 8;
if (efer & EFER_LMA) {
cs.d = 0;
cs.l = 1;
}
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data);
ctxt->_eip = (efer & EFER_LMA) ? msr_data : (u32)msr_data;
ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data);
*reg_write(ctxt, VCPU_REGS_RSP) = (efer & EFER_LMA) ? msr_data :
(u32)msr_data;
return X86EMUL_CONTINUE;
}
static int em_sysexit(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data, rcx, rdx;
int usermode;
u16 cs_sel = 0, ss_sel = 0;
/* inject #GP if in real mode or Virtual 8086 mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86)
return emulate_gp(ctxt, 0);
setup_syscalls_segments(ctxt, &cs, &ss);
if ((ctxt->rex_prefix & 0x8) != 0x0)
usermode = X86EMUL_MODE_PROT64;
else
usermode = X86EMUL_MODE_PROT32;
rcx = reg_read(ctxt, VCPU_REGS_RCX);
rdx = reg_read(ctxt, VCPU_REGS_RDX);
cs.dpl = 3;
ss.dpl = 3;
ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
switch (usermode) {
case X86EMUL_MODE_PROT32:
cs_sel = (u16)(msr_data + 16);
if ((msr_data & 0xfffc) == 0x0)
return emulate_gp(ctxt, 0);
ss_sel = (u16)(msr_data + 24);
rcx = (u32)rcx;
rdx = (u32)rdx;
break;
case X86EMUL_MODE_PROT64:
cs_sel = (u16)(msr_data + 32);
if (msr_data == 0x0)
return emulate_gp(ctxt, 0);
ss_sel = cs_sel + 8;
cs.d = 0;
cs.l = 1;
if (is_noncanonical_address(rcx) ||
is_noncanonical_address(rdx))
return emulate_gp(ctxt, 0);
break;
}
cs_sel |= SEGMENT_RPL_MASK;
ss_sel |= SEGMENT_RPL_MASK;
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ctxt->_eip = rdx;
*reg_write(ctxt, VCPU_REGS_RSP) = rcx;
return X86EMUL_CONTINUE;
}
static bool emulator_bad_iopl(struct x86_emulate_ctxt *ctxt)
{
int iopl;
if (ctxt->mode == X86EMUL_MODE_REAL)
return false;
if (ctxt->mode == X86EMUL_MODE_VM86)
return true;
iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> X86_EFLAGS_IOPL_BIT;
return ctxt->ops->cpl(ctxt) > iopl;
}
static bool emulator_io_port_access_allowed(struct x86_emulate_ctxt *ctxt,
u16 port, u16 len)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct tr_seg;
u32 base3;
int r;
u16 tr, io_bitmap_ptr, perm, bit_idx = port & 0x7;
unsigned mask = (1 << len) - 1;
unsigned long base;
ops->get_segment(ctxt, &tr, &tr_seg, &base3, VCPU_SREG_TR);
if (!tr_seg.p)
return false;
if (desc_limit_scaled(&tr_seg) < 103)
return false;
base = get_desc_base(&tr_seg);
#ifdef CONFIG_X86_64
base |= ((u64)base3) << 32;
#endif
r = ops->read_std(ctxt, base + 102, &io_bitmap_ptr, 2, NULL);
if (r != X86EMUL_CONTINUE)
return false;
if (io_bitmap_ptr + port/8 > desc_limit_scaled(&tr_seg))
return false;
r = ops->read_std(ctxt, base + io_bitmap_ptr + port/8, &perm, 2, NULL);
if (r != X86EMUL_CONTINUE)
return false;
if ((perm >> bit_idx) & mask)
return false;
return true;
}
static bool emulator_io_permited(struct x86_emulate_ctxt *ctxt,
u16 port, u16 len)
{
if (ctxt->perm_ok)
return true;
if (emulator_bad_iopl(ctxt))
if (!emulator_io_port_access_allowed(ctxt, port, len))
return false;
ctxt->perm_ok = true;
return true;
}
static void string_registers_quirk(struct x86_emulate_ctxt *ctxt)
{
/*
* Intel CPUs mask the counter and pointers in quite strange
* manner when ECX is zero due to REP-string optimizations.
*/
#ifdef CONFIG_X86_64
if (ctxt->ad_bytes != 4 || !vendor_intel(ctxt))
return;
*reg_write(ctxt, VCPU_REGS_RCX) = 0;
switch (ctxt->b) {
case 0xa4: /* movsb */
case 0xa5: /* movsd/w */
*reg_rmw(ctxt, VCPU_REGS_RSI) &= (u32)-1;
/* fall through */
case 0xaa: /* stosb */
case 0xab: /* stosd/w */
*reg_rmw(ctxt, VCPU_REGS_RDI) &= (u32)-1;
}
#endif
}
static void save_state_to_tss16(struct x86_emulate_ctxt *ctxt,
struct tss_segment_16 *tss)
{
tss->ip = ctxt->_eip;
tss->flag = ctxt->eflags;
tss->ax = reg_read(ctxt, VCPU_REGS_RAX);
tss->cx = reg_read(ctxt, VCPU_REGS_RCX);
tss->dx = reg_read(ctxt, VCPU_REGS_RDX);
tss->bx = reg_read(ctxt, VCPU_REGS_RBX);
tss->sp = reg_read(ctxt, VCPU_REGS_RSP);
tss->bp = reg_read(ctxt, VCPU_REGS_RBP);
tss->si = reg_read(ctxt, VCPU_REGS_RSI);
tss->di = reg_read(ctxt, VCPU_REGS_RDI);
tss->es = get_segment_selector(ctxt, VCPU_SREG_ES);
tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS);
tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS);
tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS);
tss->ldt = get_segment_selector(ctxt, VCPU_SREG_LDTR);
}
static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt,
struct tss_segment_16 *tss)
{
int ret;
u8 cpl;
ctxt->_eip = tss->ip;
ctxt->eflags = tss->flag | 2;
*reg_write(ctxt, VCPU_REGS_RAX) = tss->ax;
*reg_write(ctxt, VCPU_REGS_RCX) = tss->cx;
*reg_write(ctxt, VCPU_REGS_RDX) = tss->dx;
*reg_write(ctxt, VCPU_REGS_RBX) = tss->bx;
*reg_write(ctxt, VCPU_REGS_RSP) = tss->sp;
*reg_write(ctxt, VCPU_REGS_RBP) = tss->bp;
*reg_write(ctxt, VCPU_REGS_RSI) = tss->si;
*reg_write(ctxt, VCPU_REGS_RDI) = tss->di;
/*
* SDM says that segment selectors are loaded before segment
* descriptors
*/
set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR);
set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
cpl = tss->cs & 3;
/*
* Now load segment descriptors. If fault happens at this stage
* it is handled in a context of new task
*/
ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
return X86EMUL_CONTINUE;
}
static int task_switch_16(struct x86_emulate_ctxt *ctxt,
u16 tss_selector, u16 old_tss_sel,
ulong old_tss_base, struct desc_struct *new_desc)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct tss_segment_16 tss_seg;
int ret;
u32 new_tss_base = get_desc_base(new_desc);
ret = ops->read_std(ctxt, old_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
save_state_to_tss16(ctxt, &tss_seg);
ret = ops->write_std(ctxt, old_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = ops->read_std(ctxt, new_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
if (old_tss_sel != 0xffff) {
tss_seg.prev_task_link = old_tss_sel;
ret = ops->write_std(ctxt, new_tss_base,
&tss_seg.prev_task_link,
sizeof tss_seg.prev_task_link,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
}
return load_state_from_tss16(ctxt, &tss_seg);
}
static void save_state_to_tss32(struct x86_emulate_ctxt *ctxt,
struct tss_segment_32 *tss)
{
/* CR3 and ldt selector are not saved intentionally */
tss->eip = ctxt->_eip;
tss->eflags = ctxt->eflags;
tss->eax = reg_read(ctxt, VCPU_REGS_RAX);
tss->ecx = reg_read(ctxt, VCPU_REGS_RCX);
tss->edx = reg_read(ctxt, VCPU_REGS_RDX);
tss->ebx = reg_read(ctxt, VCPU_REGS_RBX);
tss->esp = reg_read(ctxt, VCPU_REGS_RSP);
tss->ebp = reg_read(ctxt, VCPU_REGS_RBP);
tss->esi = reg_read(ctxt, VCPU_REGS_RSI);
tss->edi = reg_read(ctxt, VCPU_REGS_RDI);
tss->es = get_segment_selector(ctxt, VCPU_SREG_ES);
tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS);
tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS);
tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS);
tss->fs = get_segment_selector(ctxt, VCPU_SREG_FS);
tss->gs = get_segment_selector(ctxt, VCPU_SREG_GS);
}
static int load_state_from_tss32(struct x86_emulate_ctxt *ctxt,
struct tss_segment_32 *tss)
{
int ret;
u8 cpl;
if (ctxt->ops->set_cr(ctxt, 3, tss->cr3))
return emulate_gp(ctxt, 0);
ctxt->_eip = tss->eip;
ctxt->eflags = tss->eflags | 2;
/* General purpose registers */
*reg_write(ctxt, VCPU_REGS_RAX) = tss->eax;
*reg_write(ctxt, VCPU_REGS_RCX) = tss->ecx;
*reg_write(ctxt, VCPU_REGS_RDX) = tss->edx;
*reg_write(ctxt, VCPU_REGS_RBX) = tss->ebx;
*reg_write(ctxt, VCPU_REGS_RSP) = tss->esp;
*reg_write(ctxt, VCPU_REGS_RBP) = tss->ebp;
*reg_write(ctxt, VCPU_REGS_RSI) = tss->esi;
*reg_write(ctxt, VCPU_REGS_RDI) = tss->edi;
/*
* SDM says that segment selectors are loaded before segment
* descriptors. This is important because CPL checks will
* use CS.RPL.
*/
set_segment_selector(ctxt, tss->ldt_selector, VCPU_SREG_LDTR);
set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
set_segment_selector(ctxt, tss->fs, VCPU_SREG_FS);
set_segment_selector(ctxt, tss->gs, VCPU_SREG_GS);
/*
* If we're switching between Protected Mode and VM86, we need to make
* sure to update the mode before loading the segment descriptors so
* that the selectors are interpreted correctly.
*/
if (ctxt->eflags & X86_EFLAGS_VM) {
ctxt->mode = X86EMUL_MODE_VM86;
cpl = 3;
} else {
ctxt->mode = X86EMUL_MODE_PROT32;
cpl = tss->cs & 3;
}
/*
* Now load segment descriptors. If fault happenes at this stage
* it is handled in a context of new task
*/
ret = __load_segment_descriptor(ctxt, tss->ldt_selector, VCPU_SREG_LDTR,
cpl, X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->fs, VCPU_SREG_FS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->gs, VCPU_SREG_GS, cpl,
X86_TRANSFER_TASK_SWITCH, NULL);
return ret;
}
static int task_switch_32(struct x86_emulate_ctxt *ctxt,
u16 tss_selector, u16 old_tss_sel,
ulong old_tss_base, struct desc_struct *new_desc)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct tss_segment_32 tss_seg;
int ret;
u32 new_tss_base = get_desc_base(new_desc);
u32 eip_offset = offsetof(struct tss_segment_32, eip);
u32 ldt_sel_offset = offsetof(struct tss_segment_32, ldt_selector);
ret = ops->read_std(ctxt, old_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
save_state_to_tss32(ctxt, &tss_seg);
/* Only GP registers and segment selectors are saved */
ret = ops->write_std(ctxt, old_tss_base + eip_offset, &tss_seg.eip,
ldt_sel_offset - eip_offset, &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = ops->read_std(ctxt, new_tss_base, &tss_seg, sizeof tss_seg,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
if (old_tss_sel != 0xffff) {
tss_seg.prev_task_link = old_tss_sel;
ret = ops->write_std(ctxt, new_tss_base,
&tss_seg.prev_task_link,
sizeof tss_seg.prev_task_link,
&ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
}
return load_state_from_tss32(ctxt, &tss_seg);
}
static int emulator_do_task_switch(struct x86_emulate_ctxt *ctxt,
u16 tss_selector, int idt_index, int reason,
bool has_error_code, u32 error_code)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct curr_tss_desc, next_tss_desc;
int ret;
u16 old_tss_sel = get_segment_selector(ctxt, VCPU_SREG_TR);
ulong old_tss_base =
ops->get_cached_segment_base(ctxt, VCPU_SREG_TR);
u32 desc_limit;
ulong desc_addr, dr7;
/* FIXME: old_tss_base == ~0 ? */
ret = read_segment_descriptor(ctxt, tss_selector, &next_tss_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = read_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
/* FIXME: check that next_tss_desc is tss */
/*
* Check privileges. The three cases are task switch caused by...
*
* 1. jmp/call/int to task gate: Check against DPL of the task gate
* 2. Exception/IRQ/iret: No check is performed
* 3. jmp/call to TSS/task-gate: No check is performed since the
* hardware checks it before exiting.
*/
if (reason == TASK_SWITCH_GATE) {
if (idt_index != -1) {
/* Software interrupts */
struct desc_struct task_gate_desc;
int dpl;
ret = read_interrupt_descriptor(ctxt, idt_index,
&task_gate_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
dpl = task_gate_desc.dpl;
if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl)
return emulate_gp(ctxt, (idt_index << 3) | 0x2);
}
}
desc_limit = desc_limit_scaled(&next_tss_desc);
if (!next_tss_desc.p ||
((desc_limit < 0x67 && (next_tss_desc.type & 8)) ||
desc_limit < 0x2b)) {
return emulate_ts(ctxt, tss_selector & 0xfffc);
}
if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
curr_tss_desc.type &= ~(1 << 1); /* clear busy flag */
write_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc);
}
if (reason == TASK_SWITCH_IRET)
ctxt->eflags = ctxt->eflags & ~X86_EFLAGS_NT;
/* set back link to prev task only if NT bit is set in eflags
note that old_tss_sel is not used after this point */
if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE)
old_tss_sel = 0xffff;
if (next_tss_desc.type & 8)
ret = task_switch_32(ctxt, tss_selector, old_tss_sel,
old_tss_base, &next_tss_desc);
else
ret = task_switch_16(ctxt, tss_selector, old_tss_sel,
old_tss_base, &next_tss_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE)
ctxt->eflags = ctxt->eflags | X86_EFLAGS_NT;
if (reason != TASK_SWITCH_IRET) {
next_tss_desc.type |= (1 << 1); /* set busy flag */
write_segment_descriptor(ctxt, tss_selector, &next_tss_desc);
}
ops->set_cr(ctxt, 0, ops->get_cr(ctxt, 0) | X86_CR0_TS);
ops->set_segment(ctxt, tss_selector, &next_tss_desc, 0, VCPU_SREG_TR);
if (has_error_code) {
ctxt->op_bytes = ctxt->ad_bytes = (next_tss_desc.type & 8) ? 4 : 2;
ctxt->lock_prefix = 0;
ctxt->src.val = (unsigned long) error_code;
ret = em_push(ctxt);
}
ops->get_dr(ctxt, 7, &dr7);
ops->set_dr(ctxt, 7, dr7 & ~(DR_LOCAL_ENABLE_MASK | DR_LOCAL_SLOWDOWN));
return ret;
}
int emulator_task_switch(struct x86_emulate_ctxt *ctxt,
u16 tss_selector, int idt_index, int reason,
bool has_error_code, u32 error_code)
{
int rc;
invalidate_registers(ctxt);
ctxt->_eip = ctxt->eip;
ctxt->dst.type = OP_NONE;
rc = emulator_do_task_switch(ctxt, tss_selector, idt_index, reason,
has_error_code, error_code);
if (rc == X86EMUL_CONTINUE) {
ctxt->eip = ctxt->_eip;
writeback_registers(ctxt);
}
return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK;
}
static void string_addr_inc(struct x86_emulate_ctxt *ctxt, int reg,
struct operand *op)
{
int df = (ctxt->eflags & X86_EFLAGS_DF) ? -op->count : op->count;
register_address_increment(ctxt, reg, df * op->bytes);
op->addr.mem.ea = register_address(ctxt, reg);
}
static int em_das(struct x86_emulate_ctxt *ctxt)
{
u8 al, old_al;
bool af, cf, old_cf;
cf = ctxt->eflags & X86_EFLAGS_CF;
al = ctxt->dst.val;
old_al = al;
old_cf = cf;
cf = false;
af = ctxt->eflags & X86_EFLAGS_AF;
if ((al & 0x0f) > 9 || af) {
al -= 6;
cf = old_cf | (al >= 250);
af = true;
} else {
af = false;
}
if (old_al > 0x99 || old_cf) {
al -= 0x60;
cf = true;
}
ctxt->dst.val = al;
/* Set PF, ZF, SF */
ctxt->src.type = OP_IMM;
ctxt->src.val = 0;
ctxt->src.bytes = 1;
fastop(ctxt, em_or);
ctxt->eflags &= ~(X86_EFLAGS_AF | X86_EFLAGS_CF);
if (cf)
ctxt->eflags |= X86_EFLAGS_CF;
if (af)
ctxt->eflags |= X86_EFLAGS_AF;
return X86EMUL_CONTINUE;
}
static int em_aam(struct x86_emulate_ctxt *ctxt)
{
u8 al, ah;
if (ctxt->src.val == 0)
return emulate_de(ctxt);
al = ctxt->dst.val & 0xff;
ah = al / ctxt->src.val;
al %= ctxt->src.val;
ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al | (ah << 8);
/* Set PF, ZF, SF */
ctxt->src.type = OP_IMM;
ctxt->src.val = 0;
ctxt->src.bytes = 1;
fastop(ctxt, em_or);
return X86EMUL_CONTINUE;
}
static int em_aad(struct x86_emulate_ctxt *ctxt)
{
u8 al = ctxt->dst.val & 0xff;
u8 ah = (ctxt->dst.val >> 8) & 0xff;
al = (al + (ah * ctxt->src.val)) & 0xff;
ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al;
/* Set PF, ZF, SF */
ctxt->src.type = OP_IMM;
ctxt->src.val = 0;
ctxt->src.bytes = 1;
fastop(ctxt, em_or);
return X86EMUL_CONTINUE;
}
static int em_call(struct x86_emulate_ctxt *ctxt)
{
int rc;
long rel = ctxt->src.val;
ctxt->src.val = (unsigned long)ctxt->_eip;
rc = jmp_rel(ctxt, rel);
if (rc != X86EMUL_CONTINUE)
return rc;
return em_push(ctxt);
}
static int em_call_far(struct x86_emulate_ctxt *ctxt)
{
u16 sel, old_cs;
ulong old_eip;
int rc;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
int cpl = ctxt->ops->cpl(ctxt);
enum x86emul_mode prev_mode = ctxt->mode;
old_eip = ctxt->_eip;
ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,
X86_TRANSFER_CALL_JMP, &new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, ctxt->src.val, &new_desc);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_cs;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_eip;
rc = em_push(ctxt);
/* If we failed, we tainted the memory, but the very least we should
restore cs */
if (rc != X86EMUL_CONTINUE) {
pr_warn_once("faulting far call emulation tainted memory\n");
goto fail;
}
return rc;
fail:
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
ctxt->mode = prev_mode;
return rc;
}
static int em_ret_near_imm(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip;
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_near(ctxt, eip);
if (rc != X86EMUL_CONTINUE)
return rc;
rsp_increment(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
static int em_xchg(struct x86_emulate_ctxt *ctxt)
{
/* Write back the register source. */
ctxt->src.val = ctxt->dst.val;
write_register_operand(&ctxt->src);
/* Write back the memory destination with implicit LOCK prefix. */
ctxt->dst.val = ctxt->src.orig_val;
ctxt->lock_prefix = 1;
return X86EMUL_CONTINUE;
}
static int em_imul_3op(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.val = ctxt->src2.val;
return fastop(ctxt, em_imul);
}
static int em_cwd(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.type = OP_REG;
ctxt->dst.bytes = ctxt->src.bytes;
ctxt->dst.addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
ctxt->dst.val = ~((ctxt->src.val >> (ctxt->src.bytes * 8 - 1)) - 1);
return X86EMUL_CONTINUE;
}
static int em_rdtsc(struct x86_emulate_ctxt *ctxt)
{
u64 tsc = 0;
ctxt->ops->get_msr(ctxt, MSR_IA32_TSC, &tsc);
*reg_write(ctxt, VCPU_REGS_RAX) = (u32)tsc;
*reg_write(ctxt, VCPU_REGS_RDX) = tsc >> 32;
return X86EMUL_CONTINUE;
}
static int em_rdpmc(struct x86_emulate_ctxt *ctxt)
{
u64 pmc;
if (ctxt->ops->read_pmc(ctxt, reg_read(ctxt, VCPU_REGS_RCX), &pmc))
return emulate_gp(ctxt, 0);
*reg_write(ctxt, VCPU_REGS_RAX) = (u32)pmc;
*reg_write(ctxt, VCPU_REGS_RDX) = pmc >> 32;
return X86EMUL_CONTINUE;
}
static int em_mov(struct x86_emulate_ctxt *ctxt)
{
memcpy(ctxt->dst.valptr, ctxt->src.valptr, sizeof(ctxt->src.valptr));
return X86EMUL_CONTINUE;
}
#define FFL(x) bit(X86_FEATURE_##x)
static int em_movbe(struct x86_emulate_ctxt *ctxt)
{
u32 ebx, ecx, edx, eax = 1;
u16 tmp;
/*
* Check MOVBE is set in the guest-visible CPUID leaf.
*/
ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
if (!(ecx & FFL(MOVBE)))
return emulate_ud(ctxt);
switch (ctxt->op_bytes) {
case 2:
/*
* From MOVBE definition: "...When the operand size is 16 bits,
* the upper word of the destination register remains unchanged
* ..."
*
* Both casting ->valptr and ->val to u16 breaks strict aliasing
* rules so we have to do the operation almost per hand.
*/
tmp = (u16)ctxt->src.val;
ctxt->dst.val &= ~0xffffUL;
ctxt->dst.val |= (unsigned long)swab16(tmp);
break;
case 4:
ctxt->dst.val = swab32((u32)ctxt->src.val);
break;
case 8:
ctxt->dst.val = swab64(ctxt->src.val);
break;
default:
BUG();
}
return X86EMUL_CONTINUE;
}
static int em_cr_write(struct x86_emulate_ctxt *ctxt)
{
if (ctxt->ops->set_cr(ctxt, ctxt->modrm_reg, ctxt->src.val))
return emulate_gp(ctxt, 0);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_dr_write(struct x86_emulate_ctxt *ctxt)
{
unsigned long val;
if (ctxt->mode == X86EMUL_MODE_PROT64)
val = ctxt->src.val & ~0ULL;
else
val = ctxt->src.val & ~0U;
/* #UD condition is already handled. */
if (ctxt->ops->set_dr(ctxt, ctxt->modrm_reg, val) < 0)
return emulate_gp(ctxt, 0);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_wrmsr(struct x86_emulate_ctxt *ctxt)
{
u64 msr_data;
msr_data = (u32)reg_read(ctxt, VCPU_REGS_RAX)
| ((u64)reg_read(ctxt, VCPU_REGS_RDX) << 32);
if (ctxt->ops->set_msr(ctxt, reg_read(ctxt, VCPU_REGS_RCX), msr_data))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
}
static int em_rdmsr(struct x86_emulate_ctxt *ctxt)
{
u64 msr_data;
if (ctxt->ops->get_msr(ctxt, reg_read(ctxt, VCPU_REGS_RCX), &msr_data))
return emulate_gp(ctxt, 0);
*reg_write(ctxt, VCPU_REGS_RAX) = (u32)msr_data;
*reg_write(ctxt, VCPU_REGS_RDX) = msr_data >> 32;
return X86EMUL_CONTINUE;
}
static int em_mov_rm_sreg(struct x86_emulate_ctxt *ctxt)
{
if (ctxt->modrm_reg > VCPU_SREG_GS)
return emulate_ud(ctxt);
ctxt->dst.val = get_segment_selector(ctxt, ctxt->modrm_reg);
if (ctxt->dst.bytes == 4 && ctxt->dst.type == OP_MEM)
ctxt->dst.bytes = 2;
return X86EMUL_CONTINUE;
}
static int em_mov_sreg_rm(struct x86_emulate_ctxt *ctxt)
{
u16 sel = ctxt->src.val;
if (ctxt->modrm_reg == VCPU_SREG_CS || ctxt->modrm_reg > VCPU_SREG_GS)
return emulate_ud(ctxt);
if (ctxt->modrm_reg == VCPU_SREG_SS)
ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return load_segment_descriptor(ctxt, sel, ctxt->modrm_reg);
}
static int em_lldt(struct x86_emulate_ctxt *ctxt)
{
u16 sel = ctxt->src.val;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return load_segment_descriptor(ctxt, sel, VCPU_SREG_LDTR);
}
static int em_ltr(struct x86_emulate_ctxt *ctxt)
{
u16 sel = ctxt->src.val;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return load_segment_descriptor(ctxt, sel, VCPU_SREG_TR);
}
static int em_invlpg(struct x86_emulate_ctxt *ctxt)
{
int rc;
ulong linear;
rc = linearize(ctxt, ctxt->src.addr.mem, 1, false, &linear);
if (rc == X86EMUL_CONTINUE)
ctxt->ops->invlpg(ctxt, linear);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_clts(struct x86_emulate_ctxt *ctxt)
{
ulong cr0;
cr0 = ctxt->ops->get_cr(ctxt, 0);
cr0 &= ~X86_CR0_TS;
ctxt->ops->set_cr(ctxt, 0, cr0);
return X86EMUL_CONTINUE;
}
static int em_hypercall(struct x86_emulate_ctxt *ctxt)
{
int rc = ctxt->ops->fix_hypercall(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Let the processor re-execute the fixed hypercall */
ctxt->_eip = ctxt->eip;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int emulate_store_desc_ptr(struct x86_emulate_ctxt *ctxt,
void (*get)(struct x86_emulate_ctxt *ctxt,
struct desc_ptr *ptr))
{
struct desc_ptr desc_ptr;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ctxt->op_bytes = 8;
get(ctxt, &desc_ptr);
if (ctxt->op_bytes == 2) {
ctxt->op_bytes = 4;
desc_ptr.address &= 0x00ffffff;
}
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return segmented_write(ctxt, ctxt->dst.addr.mem,
&desc_ptr, 2 + ctxt->op_bytes);
}
static int em_sgdt(struct x86_emulate_ctxt *ctxt)
{
return emulate_store_desc_ptr(ctxt, ctxt->ops->get_gdt);
}
static int em_sidt(struct x86_emulate_ctxt *ctxt)
{
return emulate_store_desc_ptr(ctxt, ctxt->ops->get_idt);
}
static int em_lgdt_lidt(struct x86_emulate_ctxt *ctxt, bool lgdt)
{
struct desc_ptr desc_ptr;
int rc;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ctxt->op_bytes = 8;
rc = read_descriptor(ctxt, ctxt->src.addr.mem,
&desc_ptr.size, &desc_ptr.address,
ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->mode == X86EMUL_MODE_PROT64 &&
is_noncanonical_address(desc_ptr.address))
return emulate_gp(ctxt, 0);
if (lgdt)
ctxt->ops->set_gdt(ctxt, &desc_ptr);
else
ctxt->ops->set_idt(ctxt, &desc_ptr);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_lgdt(struct x86_emulate_ctxt *ctxt)
{
return em_lgdt_lidt(ctxt, true);
}
static int em_lidt(struct x86_emulate_ctxt *ctxt)
{
return em_lgdt_lidt(ctxt, false);
}
static int em_smsw(struct x86_emulate_ctxt *ctxt)
{
if (ctxt->dst.type == OP_MEM)
ctxt->dst.bytes = 2;
ctxt->dst.val = ctxt->ops->get_cr(ctxt, 0);
return X86EMUL_CONTINUE;
}
static int em_lmsw(struct x86_emulate_ctxt *ctxt)
{
ctxt->ops->set_cr(ctxt, 0, (ctxt->ops->get_cr(ctxt, 0) & ~0x0eul)
| (ctxt->src.val & 0x0f));
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_loop(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
register_address_increment(ctxt, VCPU_REGS_RCX, -1);
if ((address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) != 0) &&
(ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags)))
rc = jmp_rel(ctxt, ctxt->src.val);
return rc;
}
static int em_jcxz(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)
rc = jmp_rel(ctxt, ctxt->src.val);
return rc;
}
static int em_in(struct x86_emulate_ctxt *ctxt)
{
if (!pio_in_emulated(ctxt, ctxt->dst.bytes, ctxt->src.val,
&ctxt->dst.val))
return X86EMUL_IO_NEEDED;
return X86EMUL_CONTINUE;
}
static int em_out(struct x86_emulate_ctxt *ctxt)
{
ctxt->ops->pio_out_emulated(ctxt, ctxt->src.bytes, ctxt->dst.val,
&ctxt->src.val, 1);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
static int em_cli(struct x86_emulate_ctxt *ctxt)
{
if (emulator_bad_iopl(ctxt))
return emulate_gp(ctxt, 0);
ctxt->eflags &= ~X86_EFLAGS_IF;
return X86EMUL_CONTINUE;
}
static int em_sti(struct x86_emulate_ctxt *ctxt)
{
if (emulator_bad_iopl(ctxt))
return emulate_gp(ctxt, 0);
ctxt->interruptibility = KVM_X86_SHADOW_INT_STI;
ctxt->eflags |= X86_EFLAGS_IF;
return X86EMUL_CONTINUE;
}
static int em_cpuid(struct x86_emulate_ctxt *ctxt)
{
u32 eax, ebx, ecx, edx;
eax = reg_read(ctxt, VCPU_REGS_RAX);
ecx = reg_read(ctxt, VCPU_REGS_RCX);
ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx);
*reg_write(ctxt, VCPU_REGS_RAX) = eax;
*reg_write(ctxt, VCPU_REGS_RBX) = ebx;
*reg_write(ctxt, VCPU_REGS_RCX) = ecx;
*reg_write(ctxt, VCPU_REGS_RDX) = edx;
return X86EMUL_CONTINUE;
}
static int em_sahf(struct x86_emulate_ctxt *ctxt)
{
u32 flags;
flags = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
X86_EFLAGS_SF;
flags &= *reg_rmw(ctxt, VCPU_REGS_RAX) >> 8;
ctxt->eflags &= ~0xffUL;
ctxt->eflags |= flags | X86_EFLAGS_FIXED;
return X86EMUL_CONTINUE;
}
static int em_lahf(struct x86_emulate_ctxt *ctxt)
{
*reg_rmw(ctxt, VCPU_REGS_RAX) &= ~0xff00UL;
*reg_rmw(ctxt, VCPU_REGS_RAX) |= (ctxt->eflags & 0xff) << 8;
return X86EMUL_CONTINUE;
}
static int em_bswap(struct x86_emulate_ctxt *ctxt)
{
switch (ctxt->op_bytes) {
#ifdef CONFIG_X86_64
case 8:
asm("bswap %0" : "+r"(ctxt->dst.val));
break;
#endif
default:
asm("bswap %0" : "+r"(*(u32 *)&ctxt->dst.val));
break;
}
return X86EMUL_CONTINUE;
}
static int em_clflush(struct x86_emulate_ctxt *ctxt)
{
/* emulating clflush regardless of cpuid */
return X86EMUL_CONTINUE;
}
static int em_movsxd(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.val = (s32) ctxt->src.val;
return X86EMUL_CONTINUE;
}
static bool valid_cr(int nr)
{
switch (nr) {
case 0:
case 2 ... 4:
case 8:
return true;
default:
return false;
}
}
static int check_cr_read(struct x86_emulate_ctxt *ctxt)
{
if (!valid_cr(ctxt->modrm_reg))
return emulate_ud(ctxt);
return X86EMUL_CONTINUE;
}
static int check_cr_write(struct x86_emulate_ctxt *ctxt)
{
u64 new_val = ctxt->src.val64;
int cr = ctxt->modrm_reg;
u64 efer = 0;
static u64 cr_reserved_bits[] = {
0xffffffff00000000ULL,
0, 0, 0, /* CR3 checked later */
CR4_RESERVED_BITS,
0, 0, 0,
CR8_RESERVED_BITS,
};
if (!valid_cr(cr))
return emulate_ud(ctxt);
if (new_val & cr_reserved_bits[cr])
return emulate_gp(ctxt, 0);
switch (cr) {
case 0: {
u64 cr4;
if (((new_val & X86_CR0_PG) && !(new_val & X86_CR0_PE)) ||
((new_val & X86_CR0_NW) && !(new_val & X86_CR0_CD)))
return emulate_gp(ctxt, 0);
cr4 = ctxt->ops->get_cr(ctxt, 4);
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if ((new_val & X86_CR0_PG) && (efer & EFER_LME) &&
!(cr4 & X86_CR4_PAE))
return emulate_gp(ctxt, 0);
break;
}
case 3: {
u64 rsvd = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
rsvd = CR3_L_MODE_RESERVED_BITS & ~CR3_PCID_INVD;
if (new_val & rsvd)
return emulate_gp(ctxt, 0);
break;
}
case 4: {
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if ((efer & EFER_LMA) && !(new_val & X86_CR4_PAE))
return emulate_gp(ctxt, 0);
break;
}
}
return X86EMUL_CONTINUE;
}
static int check_dr7_gd(struct x86_emulate_ctxt *ctxt)
{
unsigned long dr7;
ctxt->ops->get_dr(ctxt, 7, &dr7);
/* Check if DR7.Global_Enable is set */
return dr7 & (1 << 13);
}
static int check_dr_read(struct x86_emulate_ctxt *ctxt)
{
int dr = ctxt->modrm_reg;
u64 cr4;
if (dr > 7)
return emulate_ud(ctxt);
cr4 = ctxt->ops->get_cr(ctxt, 4);
if ((cr4 & X86_CR4_DE) && (dr == 4 || dr == 5))
return emulate_ud(ctxt);
if (check_dr7_gd(ctxt)) {
ulong dr6;
ctxt->ops->get_dr(ctxt, 6, &dr6);
dr6 &= ~15;
dr6 |= DR6_BD | DR6_RTM;
ctxt->ops->set_dr(ctxt, 6, dr6);
return emulate_db(ctxt);
}
return X86EMUL_CONTINUE;
}
static int check_dr_write(struct x86_emulate_ctxt *ctxt)
{
u64 new_val = ctxt->src.val64;
int dr = ctxt->modrm_reg;
if ((dr == 6 || dr == 7) && (new_val & 0xffffffff00000000ULL))
return emulate_gp(ctxt, 0);
return check_dr_read(ctxt);
}
static int check_svme(struct x86_emulate_ctxt *ctxt)
{
u64 efer;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (!(efer & EFER_SVME))
return emulate_ud(ctxt);
return X86EMUL_CONTINUE;
}
static int check_svme_pa(struct x86_emulate_ctxt *ctxt)
{
u64 rax = reg_read(ctxt, VCPU_REGS_RAX);
/* Valid physical address? */
if (rax & 0xffff000000000000ULL)
return emulate_gp(ctxt, 0);
return check_svme(ctxt);
}
static int check_rdtsc(struct x86_emulate_ctxt *ctxt)
{
u64 cr4 = ctxt->ops->get_cr(ctxt, 4);
if (cr4 & X86_CR4_TSD && ctxt->ops->cpl(ctxt))
return emulate_ud(ctxt);
return X86EMUL_CONTINUE;
}
static int check_rdpmc(struct x86_emulate_ctxt *ctxt)
{
u64 cr4 = ctxt->ops->get_cr(ctxt, 4);
u64 rcx = reg_read(ctxt, VCPU_REGS_RCX);
if ((!(cr4 & X86_CR4_PCE) && ctxt->ops->cpl(ctxt)) ||
ctxt->ops->check_pmc(ctxt, rcx))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
}
static int check_perm_in(struct x86_emulate_ctxt *ctxt)
{
ctxt->dst.bytes = min(ctxt->dst.bytes, 4u);
if (!emulator_io_permited(ctxt, ctxt->src.val, ctxt->dst.bytes))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
}
static int check_perm_out(struct x86_emulate_ctxt *ctxt)
{
ctxt->src.bytes = min(ctxt->src.bytes, 4u);
if (!emulator_io_permited(ctxt, ctxt->dst.val, ctxt->src.bytes))
return emulate_gp(ctxt, 0);
return X86EMUL_CONTINUE;
}
#define D(_y) { .flags = (_y) }
#define DI(_y, _i) { .flags = (_y)|Intercept, .intercept = x86_intercept_##_i }
#define DIP(_y, _i, _p) { .flags = (_y)|Intercept|CheckPerm, \
.intercept = x86_intercept_##_i, .check_perm = (_p) }
#define N D(NotImpl)
#define EXT(_f, _e) { .flags = ((_f) | RMExt), .u.group = (_e) }
#define G(_f, _g) { .flags = ((_f) | Group | ModRM), .u.group = (_g) }
#define GD(_f, _g) { .flags = ((_f) | GroupDual | ModRM), .u.gdual = (_g) }
#define ID(_f, _i) { .flags = ((_f) | InstrDual | ModRM), .u.idual = (_i) }
#define MD(_f, _m) { .flags = ((_f) | ModeDual), .u.mdual = (_m) }
#define E(_f, _e) { .flags = ((_f) | Escape | ModRM), .u.esc = (_e) }
#define I(_f, _e) { .flags = (_f), .u.execute = (_e) }
#define F(_f, _e) { .flags = (_f) | Fastop, .u.fastop = (_e) }
#define II(_f, _e, _i) \
{ .flags = (_f)|Intercept, .u.execute = (_e), .intercept = x86_intercept_##_i }
#define IIP(_f, _e, _i, _p) \
{ .flags = (_f)|Intercept|CheckPerm, .u.execute = (_e), \
.intercept = x86_intercept_##_i, .check_perm = (_p) }
#define GP(_f, _g) { .flags = ((_f) | Prefix), .u.gprefix = (_g) }
#define D2bv(_f) D((_f) | ByteOp), D(_f)
#define D2bvIP(_f, _i, _p) DIP((_f) | ByteOp, _i, _p), DIP(_f, _i, _p)
#define I2bv(_f, _e) I((_f) | ByteOp, _e), I(_f, _e)
#define F2bv(_f, _e) F((_f) | ByteOp, _e), F(_f, _e)
#define I2bvIP(_f, _e, _i, _p) \
IIP((_f) | ByteOp, _e, _i, _p), IIP(_f, _e, _i, _p)
#define F6ALU(_f, _e) F2bv((_f) | DstMem | SrcReg | ModRM, _e), \
F2bv(((_f) | DstReg | SrcMem | ModRM) & ~Lock, _e), \
F2bv(((_f) & ~Lock) | DstAcc | SrcImm, _e)
static const struct opcode group7_rm0[] = {
N,
I(SrcNone | Priv | EmulateOnUD, em_hypercall),
N, N, N, N, N, N,
};
static const struct opcode group7_rm1[] = {
DI(SrcNone | Priv, monitor),
DI(SrcNone | Priv, mwait),
N, N, N, N, N, N,
};
static const struct opcode group7_rm3[] = {
DIP(SrcNone | Prot | Priv, vmrun, check_svme_pa),
II(SrcNone | Prot | EmulateOnUD, em_hypercall, vmmcall),
DIP(SrcNone | Prot | Priv, vmload, check_svme_pa),
DIP(SrcNone | Prot | Priv, vmsave, check_svme_pa),
DIP(SrcNone | Prot | Priv, stgi, check_svme),
DIP(SrcNone | Prot | Priv, clgi, check_svme),
DIP(SrcNone | Prot | Priv, skinit, check_svme),
DIP(SrcNone | Prot | Priv, invlpga, check_svme),
};
static const struct opcode group7_rm7[] = {
N,
DIP(SrcNone, rdtscp, check_rdtsc),
N, N, N, N, N, N,
};
static const struct opcode group1[] = {
F(Lock, em_add),
F(Lock | PageTable, em_or),
F(Lock, em_adc),
F(Lock, em_sbb),
F(Lock | PageTable, em_and),
F(Lock, em_sub),
F(Lock, em_xor),
F(NoWrite, em_cmp),
};
static const struct opcode group1A[] = {
I(DstMem | SrcNone | Mov | Stack | IncSP, em_pop), N, N, N, N, N, N, N,
};
static const struct opcode group2[] = {
F(DstMem | ModRM, em_rol),
F(DstMem | ModRM, em_ror),
F(DstMem | ModRM, em_rcl),
F(DstMem | ModRM, em_rcr),
F(DstMem | ModRM, em_shl),
F(DstMem | ModRM, em_shr),
F(DstMem | ModRM, em_shl),
F(DstMem | ModRM, em_sar),
};
static const struct opcode group3[] = {
F(DstMem | SrcImm | NoWrite, em_test),
F(DstMem | SrcImm | NoWrite, em_test),
F(DstMem | SrcNone | Lock, em_not),
F(DstMem | SrcNone | Lock, em_neg),
F(DstXacc | Src2Mem, em_mul_ex),
F(DstXacc | Src2Mem, em_imul_ex),
F(DstXacc | Src2Mem, em_div_ex),
F(DstXacc | Src2Mem, em_idiv_ex),
};
static const struct opcode group4[] = {
F(ByteOp | DstMem | SrcNone | Lock, em_inc),
F(ByteOp | DstMem | SrcNone | Lock, em_dec),
N, N, N, N, N, N,
};
static const struct opcode group5[] = {
F(DstMem | SrcNone | Lock, em_inc),
F(DstMem | SrcNone | Lock, em_dec),
I(SrcMem | NearBranch, em_call_near_abs),
I(SrcMemFAddr | ImplicitOps, em_call_far),
I(SrcMem | NearBranch, em_jmp_abs),
I(SrcMemFAddr | ImplicitOps, em_jmp_far),
I(SrcMem | Stack, em_push), D(Undefined),
};
static const struct opcode group6[] = {
DI(Prot | DstMem, sldt),
DI(Prot | DstMem, str),
II(Prot | Priv | SrcMem16, em_lldt, lldt),
II(Prot | Priv | SrcMem16, em_ltr, ltr),
N, N, N, N,
};
static const struct group_dual group7 = { {
II(Mov | DstMem, em_sgdt, sgdt),
II(Mov | DstMem, em_sidt, sidt),
II(SrcMem | Priv, em_lgdt, lgdt),
II(SrcMem | Priv, em_lidt, lidt),
II(SrcNone | DstMem | Mov, em_smsw, smsw), N,
II(SrcMem16 | Mov | Priv, em_lmsw, lmsw),
II(SrcMem | ByteOp | Priv | NoAccess, em_invlpg, invlpg),
}, {
EXT(0, group7_rm0),
EXT(0, group7_rm1),
N, EXT(0, group7_rm3),
II(SrcNone | DstMem | Mov, em_smsw, smsw), N,
II(SrcMem16 | Mov | Priv, em_lmsw, lmsw),
EXT(0, group7_rm7),
} };
static const struct opcode group8[] = {
N, N, N, N,
F(DstMem | SrcImmByte | NoWrite, em_bt),
F(DstMem | SrcImmByte | Lock | PageTable, em_bts),
F(DstMem | SrcImmByte | Lock, em_btr),
F(DstMem | SrcImmByte | Lock | PageTable, em_btc),
};
static const struct group_dual group9 = { {
N, I(DstMem64 | Lock | PageTable, em_cmpxchg8b), N, N, N, N, N, N,
}, {
N, N, N, N, N, N, N, N,
} };
static const struct opcode group11[] = {
I(DstMem | SrcImm | Mov | PageTable, em_mov),
X7(D(Undefined)),
};
static const struct gprefix pfx_0f_ae_7 = {
I(SrcMem | ByteOp, em_clflush), N, N, N,
};
static const struct group_dual group15 = { {
N, N, N, N, N, N, N, GP(0, &pfx_0f_ae_7),
}, {
N, N, N, N, N, N, N, N,
} };
static const struct gprefix pfx_0f_6f_0f_7f = {
I(Mmx, em_mov), I(Sse | Aligned, em_mov), N, I(Sse | Unaligned, em_mov),
};
static const struct instr_dual instr_dual_0f_2b = {
I(0, em_mov), N
};
static const struct gprefix pfx_0f_2b = {
ID(0, &instr_dual_0f_2b), ID(0, &instr_dual_0f_2b), N, N,
};
static const struct gprefix pfx_0f_28_0f_29 = {
I(Aligned, em_mov), I(Aligned, em_mov), N, N,
};
static const struct gprefix pfx_0f_e7 = {
N, I(Sse, em_mov), N, N,
};
static const struct escape escape_d9 = { {
N, N, N, N, N, N, N, I(DstMem16 | Mov, em_fnstcw),
}, {
/* 0xC0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xC8 - 0xCF */
N, N, N, N, N, N, N, N,
/* 0xD0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xD8 - 0xDF */
N, N, N, N, N, N, N, N,
/* 0xE0 - 0xE7 */
N, N, N, N, N, N, N, N,
/* 0xE8 - 0xEF */
N, N, N, N, N, N, N, N,
/* 0xF0 - 0xF7 */
N, N, N, N, N, N, N, N,
/* 0xF8 - 0xFF */
N, N, N, N, N, N, N, N,
} };
static const struct escape escape_db = { {
N, N, N, N, N, N, N, N,
}, {
/* 0xC0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xC8 - 0xCF */
N, N, N, N, N, N, N, N,
/* 0xD0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xD8 - 0xDF */
N, N, N, N, N, N, N, N,
/* 0xE0 - 0xE7 */
N, N, N, I(ImplicitOps, em_fninit), N, N, N, N,
/* 0xE8 - 0xEF */
N, N, N, N, N, N, N, N,
/* 0xF0 - 0xF7 */
N, N, N, N, N, N, N, N,
/* 0xF8 - 0xFF */
N, N, N, N, N, N, N, N,
} };
static const struct escape escape_dd = { {
N, N, N, N, N, N, N, I(DstMem16 | Mov, em_fnstsw),
}, {
/* 0xC0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xC8 - 0xCF */
N, N, N, N, N, N, N, N,
/* 0xD0 - 0xC7 */
N, N, N, N, N, N, N, N,
/* 0xD8 - 0xDF */
N, N, N, N, N, N, N, N,
/* 0xE0 - 0xE7 */
N, N, N, N, N, N, N, N,
/* 0xE8 - 0xEF */
N, N, N, N, N, N, N, N,
/* 0xF0 - 0xF7 */
N, N, N, N, N, N, N, N,
/* 0xF8 - 0xFF */
N, N, N, N, N, N, N, N,
} };
static const struct instr_dual instr_dual_0f_c3 = {
I(DstMem | SrcReg | ModRM | No16 | Mov, em_mov), N
};
static const struct mode_dual mode_dual_63 = {
N, I(DstReg | SrcMem32 | ModRM | Mov, em_movsxd)
};
static const struct opcode opcode_table[256] = {
/* 0x00 - 0x07 */
F6ALU(Lock, em_add),
I(ImplicitOps | Stack | No64 | Src2ES, em_push_sreg),
I(ImplicitOps | Stack | No64 | Src2ES, em_pop_sreg),
/* 0x08 - 0x0F */
F6ALU(Lock | PageTable, em_or),
I(ImplicitOps | Stack | No64 | Src2CS, em_push_sreg),
N,
/* 0x10 - 0x17 */
F6ALU(Lock, em_adc),
I(ImplicitOps | Stack | No64 | Src2SS, em_push_sreg),
I(ImplicitOps | Stack | No64 | Src2SS, em_pop_sreg),
/* 0x18 - 0x1F */
F6ALU(Lock, em_sbb),
I(ImplicitOps | Stack | No64 | Src2DS, em_push_sreg),
I(ImplicitOps | Stack | No64 | Src2DS, em_pop_sreg),
/* 0x20 - 0x27 */
F6ALU(Lock | PageTable, em_and), N, N,
/* 0x28 - 0x2F */
F6ALU(Lock, em_sub), N, I(ByteOp | DstAcc | No64, em_das),
/* 0x30 - 0x37 */
F6ALU(Lock, em_xor), N, N,
/* 0x38 - 0x3F */
F6ALU(NoWrite, em_cmp), N, N,
/* 0x40 - 0x4F */
X8(F(DstReg, em_inc)), X8(F(DstReg, em_dec)),
/* 0x50 - 0x57 */
X8(I(SrcReg | Stack, em_push)),
/* 0x58 - 0x5F */
X8(I(DstReg | Stack, em_pop)),
/* 0x60 - 0x67 */
I(ImplicitOps | Stack | No64, em_pusha),
I(ImplicitOps | Stack | No64, em_popa),
N, MD(ModRM, &mode_dual_63),
N, N, N, N,
/* 0x68 - 0x6F */
I(SrcImm | Mov | Stack, em_push),
I(DstReg | SrcMem | ModRM | Src2Imm, em_imul_3op),
I(SrcImmByte | Mov | Stack, em_push),
I(DstReg | SrcMem | ModRM | Src2ImmByte, em_imul_3op),
I2bvIP(DstDI | SrcDX | Mov | String | Unaligned, em_in, ins, check_perm_in), /* insb, insw/insd */
I2bvIP(SrcSI | DstDX | String, em_out, outs, check_perm_out), /* outsb, outsw/outsd */
/* 0x70 - 0x7F */
X16(D(SrcImmByte | NearBranch)),
/* 0x80 - 0x87 */
G(ByteOp | DstMem | SrcImm, group1),
G(DstMem | SrcImm, group1),
G(ByteOp | DstMem | SrcImm | No64, group1),
G(DstMem | SrcImmByte, group1),
F2bv(DstMem | SrcReg | ModRM | NoWrite, em_test),
I2bv(DstMem | SrcReg | ModRM | Lock | PageTable, em_xchg),
/* 0x88 - 0x8F */
I2bv(DstMem | SrcReg | ModRM | Mov | PageTable, em_mov),
I2bv(DstReg | SrcMem | ModRM | Mov, em_mov),
I(DstMem | SrcNone | ModRM | Mov | PageTable, em_mov_rm_sreg),
D(ModRM | SrcMem | NoAccess | DstReg),
I(ImplicitOps | SrcMem16 | ModRM, em_mov_sreg_rm),
G(0, group1A),
/* 0x90 - 0x97 */
DI(SrcAcc | DstReg, pause), X7(D(SrcAcc | DstReg)),
/* 0x98 - 0x9F */
D(DstAcc | SrcNone), I(ImplicitOps | SrcAcc, em_cwd),
I(SrcImmFAddr | No64, em_call_far), N,
II(ImplicitOps | Stack, em_pushf, pushf),
II(ImplicitOps | Stack, em_popf, popf),
I(ImplicitOps, em_sahf), I(ImplicitOps, em_lahf),
/* 0xA0 - 0xA7 */
I2bv(DstAcc | SrcMem | Mov | MemAbs, em_mov),
I2bv(DstMem | SrcAcc | Mov | MemAbs | PageTable, em_mov),
I2bv(SrcSI | DstDI | Mov | String, em_mov),
F2bv(SrcSI | DstDI | String | NoWrite, em_cmp_r),
/* 0xA8 - 0xAF */
F2bv(DstAcc | SrcImm | NoWrite, em_test),
I2bv(SrcAcc | DstDI | Mov | String, em_mov),
I2bv(SrcSI | DstAcc | Mov | String, em_mov),
F2bv(SrcAcc | DstDI | String | NoWrite, em_cmp_r),
/* 0xB0 - 0xB7 */
X8(I(ByteOp | DstReg | SrcImm | Mov, em_mov)),
/* 0xB8 - 0xBF */
X8(I(DstReg | SrcImm64 | Mov, em_mov)),
/* 0xC0 - 0xC7 */
G(ByteOp | Src2ImmByte, group2), G(Src2ImmByte, group2),
I(ImplicitOps | NearBranch | SrcImmU16, em_ret_near_imm),
I(ImplicitOps | NearBranch, em_ret),
I(DstReg | SrcMemFAddr | ModRM | No64 | Src2ES, em_lseg),
I(DstReg | SrcMemFAddr | ModRM | No64 | Src2DS, em_lseg),
G(ByteOp, group11), G(0, group11),
/* 0xC8 - 0xCF */
I(Stack | SrcImmU16 | Src2ImmByte, em_enter), I(Stack, em_leave),
I(ImplicitOps | SrcImmU16, em_ret_far_imm),
I(ImplicitOps, em_ret_far),
D(ImplicitOps), DI(SrcImmByte, intn),
D(ImplicitOps | No64), II(ImplicitOps, em_iret, iret),
/* 0xD0 - 0xD7 */
G(Src2One | ByteOp, group2), G(Src2One, group2),
G(Src2CL | ByteOp, group2), G(Src2CL, group2),
I(DstAcc | SrcImmUByte | No64, em_aam),
I(DstAcc | SrcImmUByte | No64, em_aad),
F(DstAcc | ByteOp | No64, em_salc),
I(DstAcc | SrcXLat | ByteOp, em_mov),
/* 0xD8 - 0xDF */
N, E(0, &escape_d9), N, E(0, &escape_db), N, E(0, &escape_dd), N, N,
/* 0xE0 - 0xE7 */
X3(I(SrcImmByte | NearBranch, em_loop)),
I(SrcImmByte | NearBranch, em_jcxz),
I2bvIP(SrcImmUByte | DstAcc, em_in, in, check_perm_in),
I2bvIP(SrcAcc | DstImmUByte, em_out, out, check_perm_out),
/* 0xE8 - 0xEF */
I(SrcImm | NearBranch, em_call), D(SrcImm | ImplicitOps | NearBranch),
I(SrcImmFAddr | No64, em_jmp_far),
D(SrcImmByte | ImplicitOps | NearBranch),
I2bvIP(SrcDX | DstAcc, em_in, in, check_perm_in),
I2bvIP(SrcAcc | DstDX, em_out, out, check_perm_out),
/* 0xF0 - 0xF7 */
N, DI(ImplicitOps, icebp), N, N,
DI(ImplicitOps | Priv, hlt), D(ImplicitOps),
G(ByteOp, group3), G(0, group3),
/* 0xF8 - 0xFF */
D(ImplicitOps), D(ImplicitOps),
I(ImplicitOps, em_cli), I(ImplicitOps, em_sti),
D(ImplicitOps), D(ImplicitOps), G(0, group4), G(0, group5),
};
static const struct opcode twobyte_table[256] = {
/* 0x00 - 0x0F */
G(0, group6), GD(0, &group7), N, N,
N, I(ImplicitOps | EmulateOnUD, em_syscall),
II(ImplicitOps | Priv, em_clts, clts), N,
DI(ImplicitOps | Priv, invd), DI(ImplicitOps | Priv, wbinvd), N, N,
N, D(ImplicitOps | ModRM | SrcMem | NoAccess), N, N,
/* 0x10 - 0x1F */
N, N, N, N, N, N, N, N,
D(ImplicitOps | ModRM | SrcMem | NoAccess),
N, N, N, N, N, N, D(ImplicitOps | ModRM | SrcMem | NoAccess),
/* 0x20 - 0x2F */
DIP(ModRM | DstMem | Priv | Op3264 | NoMod, cr_read, check_cr_read),
DIP(ModRM | DstMem | Priv | Op3264 | NoMod, dr_read, check_dr_read),
IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_cr_write, cr_write,
check_cr_write),
IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_dr_write, dr_write,
check_dr_write),
N, N, N, N,
GP(ModRM | DstReg | SrcMem | Mov | Sse, &pfx_0f_28_0f_29),
GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_28_0f_29),
N, GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_2b),
N, N, N, N,
/* 0x30 - 0x3F */
II(ImplicitOps | Priv, em_wrmsr, wrmsr),
IIP(ImplicitOps, em_rdtsc, rdtsc, check_rdtsc),
II(ImplicitOps | Priv, em_rdmsr, rdmsr),
IIP(ImplicitOps, em_rdpmc, rdpmc, check_rdpmc),
I(ImplicitOps | EmulateOnUD, em_sysenter),
I(ImplicitOps | Priv | EmulateOnUD, em_sysexit),
N, N,
N, N, N, N, N, N, N, N,
/* 0x40 - 0x4F */
X16(D(DstReg | SrcMem | ModRM)),
/* 0x50 - 0x5F */
N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N,
/* 0x60 - 0x6F */
N, N, N, N,
N, N, N, N,
N, N, N, N,
N, N, N, GP(SrcMem | DstReg | ModRM | Mov, &pfx_0f_6f_0f_7f),
/* 0x70 - 0x7F */
N, N, N, N,
N, N, N, N,
N, N, N, N,
N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_6f_0f_7f),
/* 0x80 - 0x8F */
X16(D(SrcImm | NearBranch)),
/* 0x90 - 0x9F */
X16(D(ByteOp | DstMem | SrcNone | ModRM| Mov)),
/* 0xA0 - 0xA7 */
I(Stack | Src2FS, em_push_sreg), I(Stack | Src2FS, em_pop_sreg),
II(ImplicitOps, em_cpuid, cpuid),
F(DstMem | SrcReg | ModRM | BitOp | NoWrite, em_bt),
F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shld),
F(DstMem | SrcReg | Src2CL | ModRM, em_shld), N, N,
/* 0xA8 - 0xAF */
I(Stack | Src2GS, em_push_sreg), I(Stack | Src2GS, em_pop_sreg),
II(EmulateOnUD | ImplicitOps, em_rsm, rsm),
F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_bts),
F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shrd),
F(DstMem | SrcReg | Src2CL | ModRM, em_shrd),
GD(0, &group15), F(DstReg | SrcMem | ModRM, em_imul),
/* 0xB0 - 0xB7 */
I2bv(DstMem | SrcReg | ModRM | Lock | PageTable | SrcWrite, em_cmpxchg),
I(DstReg | SrcMemFAddr | ModRM | Src2SS, em_lseg),
F(DstMem | SrcReg | ModRM | BitOp | Lock, em_btr),
I(DstReg | SrcMemFAddr | ModRM | Src2FS, em_lseg),
I(DstReg | SrcMemFAddr | ModRM | Src2GS, em_lseg),
D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov),
/* 0xB8 - 0xBF */
N, N,
G(BitOp, group8),
F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_btc),
I(DstReg | SrcMem | ModRM, em_bsf_c),
I(DstReg | SrcMem | ModRM, em_bsr_c),
D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov),
/* 0xC0 - 0xC7 */
F2bv(DstMem | SrcReg | ModRM | SrcWrite | Lock, em_xadd),
N, ID(0, &instr_dual_0f_c3),
N, N, N, GD(0, &group9),
/* 0xC8 - 0xCF */
X8(I(DstReg, em_bswap)),
/* 0xD0 - 0xDF */
N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N,
/* 0xE0 - 0xEF */
N, N, N, N, N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_e7),
N, N, N, N, N, N, N, N,
/* 0xF0 - 0xFF */
N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N
};
static const struct instr_dual instr_dual_0f_38_f0 = {
I(DstReg | SrcMem | Mov, em_movbe), N
};
static const struct instr_dual instr_dual_0f_38_f1 = {
I(DstMem | SrcReg | Mov, em_movbe), N
};
static const struct gprefix three_byte_0f_38_f0 = {
ID(0, &instr_dual_0f_38_f0), N, N, N
};
static const struct gprefix three_byte_0f_38_f1 = {
ID(0, &instr_dual_0f_38_f1), N, N, N
};
/*
* Insns below are selected by the prefix which indexed by the third opcode
* byte.
*/
static const struct opcode opcode_map_0f_38[256] = {
/* 0x00 - 0x7f */
X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N),
/* 0x80 - 0xef */
X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N),
/* 0xf0 - 0xf1 */
GP(EmulateOnUD | ModRM, &three_byte_0f_38_f0),
GP(EmulateOnUD | ModRM, &three_byte_0f_38_f1),
/* 0xf2 - 0xff */
N, N, X4(N), X8(N)
};
#undef D
#undef N
#undef G
#undef GD
#undef I
#undef GP
#undef EXT
#undef MD
#undef ID
#undef D2bv
#undef D2bvIP
#undef I2bv
#undef I2bvIP
#undef I6ALU
static unsigned imm_size(struct x86_emulate_ctxt *ctxt)
{
unsigned size;
size = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
if (size == 8)
size = 4;
return size;
}
static int decode_imm(struct x86_emulate_ctxt *ctxt, struct operand *op,
unsigned size, bool sign_extension)
{
int rc = X86EMUL_CONTINUE;
op->type = OP_IMM;
op->bytes = size;
op->addr.mem.ea = ctxt->_eip;
/* NB. Immediates are sign-extended as necessary. */
switch (op->bytes) {
case 1:
op->val = insn_fetch(s8, ctxt);
break;
case 2:
op->val = insn_fetch(s16, ctxt);
break;
case 4:
op->val = insn_fetch(s32, ctxt);
break;
case 8:
op->val = insn_fetch(s64, ctxt);
break;
}
if (!sign_extension) {
switch (op->bytes) {
case 1:
op->val &= 0xff;
break;
case 2:
op->val &= 0xffff;
break;
case 4:
op->val &= 0xffffffff;
break;
}
}
done:
return rc;
}
static int decode_operand(struct x86_emulate_ctxt *ctxt, struct operand *op,
unsigned d)
{
int rc = X86EMUL_CONTINUE;
switch (d) {
case OpReg:
decode_register_operand(ctxt, op);
break;
case OpImmUByte:
rc = decode_imm(ctxt, op, 1, false);
break;
case OpMem:
ctxt->memop.bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
mem_common:
*op = ctxt->memop;
ctxt->memopp = op;
if (ctxt->d & BitOp)
fetch_bit_operand(ctxt);
op->orig_val = op->val;
break;
case OpMem64:
ctxt->memop.bytes = (ctxt->op_bytes == 8) ? 16 : 8;
goto mem_common;
case OpAcc:
op->type = OP_REG;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
fetch_register_operand(op);
op->orig_val = op->val;
break;
case OpAccLo:
op->type = OP_REG;
op->bytes = (ctxt->d & ByteOp) ? 2 : ctxt->op_bytes;
op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
fetch_register_operand(op);
op->orig_val = op->val;
break;
case OpAccHi:
if (ctxt->d & ByteOp) {
op->type = OP_NONE;
break;
}
op->type = OP_REG;
op->bytes = ctxt->op_bytes;
op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
fetch_register_operand(op);
op->orig_val = op->val;
break;
case OpDI:
op->type = OP_MEM;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.mem.ea =
register_address(ctxt, VCPU_REGS_RDI);
op->addr.mem.seg = VCPU_SREG_ES;
op->val = 0;
op->count = 1;
break;
case OpDX:
op->type = OP_REG;
op->bytes = 2;
op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
fetch_register_operand(op);
break;
case OpCL:
op->type = OP_IMM;
op->bytes = 1;
op->val = reg_read(ctxt, VCPU_REGS_RCX) & 0xff;
break;
case OpImmByte:
rc = decode_imm(ctxt, op, 1, true);
break;
case OpOne:
op->type = OP_IMM;
op->bytes = 1;
op->val = 1;
break;
case OpImm:
rc = decode_imm(ctxt, op, imm_size(ctxt), true);
break;
case OpImm64:
rc = decode_imm(ctxt, op, ctxt->op_bytes, true);
break;
case OpMem8:
ctxt->memop.bytes = 1;
if (ctxt->memop.type == OP_REG) {
ctxt->memop.addr.reg = decode_register(ctxt,
ctxt->modrm_rm, true);
fetch_register_operand(&ctxt->memop);
}
goto mem_common;
case OpMem16:
ctxt->memop.bytes = 2;
goto mem_common;
case OpMem32:
ctxt->memop.bytes = 4;
goto mem_common;
case OpImmU16:
rc = decode_imm(ctxt, op, 2, false);
break;
case OpImmU:
rc = decode_imm(ctxt, op, imm_size(ctxt), false);
break;
case OpSI:
op->type = OP_MEM;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.mem.ea =
register_address(ctxt, VCPU_REGS_RSI);
op->addr.mem.seg = ctxt->seg_override;
op->val = 0;
op->count = 1;
break;
case OpXLat:
op->type = OP_MEM;
op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
op->addr.mem.ea =
address_mask(ctxt,
reg_read(ctxt, VCPU_REGS_RBX) +
(reg_read(ctxt, VCPU_REGS_RAX) & 0xff));
op->addr.mem.seg = ctxt->seg_override;
op->val = 0;
break;
case OpImmFAddr:
op->type = OP_IMM;
op->addr.mem.ea = ctxt->_eip;
op->bytes = ctxt->op_bytes + 2;
insn_fetch_arr(op->valptr, op->bytes, ctxt);
break;
case OpMemFAddr:
ctxt->memop.bytes = ctxt->op_bytes + 2;
goto mem_common;
case OpES:
op->type = OP_IMM;
op->val = VCPU_SREG_ES;
break;
case OpCS:
op->type = OP_IMM;
op->val = VCPU_SREG_CS;
break;
case OpSS:
op->type = OP_IMM;
op->val = VCPU_SREG_SS;
break;
case OpDS:
op->type = OP_IMM;
op->val = VCPU_SREG_DS;
break;
case OpFS:
op->type = OP_IMM;
op->val = VCPU_SREG_FS;
break;
case OpGS:
op->type = OP_IMM;
op->val = VCPU_SREG_GS;
break;
case OpImplicit:
/* Special instructions do their own operand decoding. */
default:
op->type = OP_NONE; /* Disable writeback. */
break;
}
done:
return rc;
}
int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len)
{
int rc = X86EMUL_CONTINUE;
int mode = ctxt->mode;
int def_op_bytes, def_ad_bytes, goffset, simd_prefix;
bool op_prefix = false;
bool has_seg_override = false;
struct opcode opcode;
ctxt->memop.type = OP_NONE;
ctxt->memopp = NULL;
ctxt->_eip = ctxt->eip;
ctxt->fetch.ptr = ctxt->fetch.data;
ctxt->fetch.end = ctxt->fetch.data + insn_len;
ctxt->opcode_len = 1;
if (insn_len > 0)
memcpy(ctxt->fetch.data, insn, insn_len);
else {
rc = __do_insn_fetch_bytes(ctxt, 1);
if (rc != X86EMUL_CONTINUE)
return rc;
}
switch (mode) {
case X86EMUL_MODE_REAL:
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
def_op_bytes = def_ad_bytes = 2;
break;
case X86EMUL_MODE_PROT32:
def_op_bytes = def_ad_bytes = 4;
break;
#ifdef CONFIG_X86_64
case X86EMUL_MODE_PROT64:
def_op_bytes = 4;
def_ad_bytes = 8;
break;
#endif
default:
return EMULATION_FAILED;
}
ctxt->op_bytes = def_op_bytes;
ctxt->ad_bytes = def_ad_bytes;
/* Legacy prefixes. */
for (;;) {
switch (ctxt->b = insn_fetch(u8, ctxt)) {
case 0x66: /* operand-size override */
op_prefix = true;
/* switch between 2/4 bytes */
ctxt->op_bytes = def_op_bytes ^ 6;
break;
case 0x67: /* address-size override */
if (mode == X86EMUL_MODE_PROT64)
/* switch between 4/8 bytes */
ctxt->ad_bytes = def_ad_bytes ^ 12;
else
/* switch between 2/4 bytes */
ctxt->ad_bytes = def_ad_bytes ^ 6;
break;
case 0x26: /* ES override */
case 0x2e: /* CS override */
case 0x36: /* SS override */
case 0x3e: /* DS override */
has_seg_override = true;
ctxt->seg_override = (ctxt->b >> 3) & 3;
break;
case 0x64: /* FS override */
case 0x65: /* GS override */
has_seg_override = true;
ctxt->seg_override = ctxt->b & 7;
break;
case 0x40 ... 0x4f: /* REX */
if (mode != X86EMUL_MODE_PROT64)
goto done_prefixes;
ctxt->rex_prefix = ctxt->b;
continue;
case 0xf0: /* LOCK */
ctxt->lock_prefix = 1;
break;
case 0xf2: /* REPNE/REPNZ */
case 0xf3: /* REP/REPE/REPZ */
ctxt->rep_prefix = ctxt->b;
break;
default:
goto done_prefixes;
}
/* Any legacy prefix after a REX prefix nullifies its effect. */
ctxt->rex_prefix = 0;
}
done_prefixes:
/* REX prefix. */
if (ctxt->rex_prefix & 8)
ctxt->op_bytes = 8; /* REX.W */
/* Opcode byte(s). */
opcode = opcode_table[ctxt->b];
/* Two-byte opcode? */
if (ctxt->b == 0x0f) {
ctxt->opcode_len = 2;
ctxt->b = insn_fetch(u8, ctxt);
opcode = twobyte_table[ctxt->b];
/* 0F_38 opcode map */
if (ctxt->b == 0x38) {
ctxt->opcode_len = 3;
ctxt->b = insn_fetch(u8, ctxt);
opcode = opcode_map_0f_38[ctxt->b];
}
}
ctxt->d = opcode.flags;
if (ctxt->d & ModRM)
ctxt->modrm = insn_fetch(u8, ctxt);
/* vex-prefix instructions are not implemented */
if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) &&
(mode == X86EMUL_MODE_PROT64 || (ctxt->modrm & 0xc0) == 0xc0)) {
ctxt->d = NotImpl;
}
while (ctxt->d & GroupMask) {
switch (ctxt->d & GroupMask) {
case Group:
goffset = (ctxt->modrm >> 3) & 7;
opcode = opcode.u.group[goffset];
break;
case GroupDual:
goffset = (ctxt->modrm >> 3) & 7;
if ((ctxt->modrm >> 6) == 3)
opcode = opcode.u.gdual->mod3[goffset];
else
opcode = opcode.u.gdual->mod012[goffset];
break;
case RMExt:
goffset = ctxt->modrm & 7;
opcode = opcode.u.group[goffset];
break;
case Prefix:
if (ctxt->rep_prefix && op_prefix)
return EMULATION_FAILED;
simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix;
switch (simd_prefix) {
case 0x00: opcode = opcode.u.gprefix->pfx_no; break;
case 0x66: opcode = opcode.u.gprefix->pfx_66; break;
case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break;
case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break;
}
break;
case Escape:
if (ctxt->modrm > 0xbf)
opcode = opcode.u.esc->high[ctxt->modrm - 0xc0];
else
opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7];
break;
case InstrDual:
if ((ctxt->modrm >> 6) == 3)
opcode = opcode.u.idual->mod3;
else
opcode = opcode.u.idual->mod012;
break;
case ModeDual:
if (ctxt->mode == X86EMUL_MODE_PROT64)
opcode = opcode.u.mdual->mode64;
else
opcode = opcode.u.mdual->mode32;
break;
default:
return EMULATION_FAILED;
}
ctxt->d &= ~(u64)GroupMask;
ctxt->d |= opcode.flags;
}
/* Unrecognised? */
if (ctxt->d == 0)
return EMULATION_FAILED;
ctxt->execute = opcode.u.execute;
if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD)))
return EMULATION_FAILED;
if (unlikely(ctxt->d &
(NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm|NearBranch|
No16))) {
/*
* These are copied unconditionally here, and checked unconditionally
* in x86_emulate_insn.
*/
ctxt->check_perm = opcode.check_perm;
ctxt->intercept = opcode.intercept;
if (ctxt->d & NotImpl)
return EMULATION_FAILED;
if (mode == X86EMUL_MODE_PROT64) {
if (ctxt->op_bytes == 4 && (ctxt->d & Stack))
ctxt->op_bytes = 8;
else if (ctxt->d & NearBranch)
ctxt->op_bytes = 8;
}
if (ctxt->d & Op3264) {
if (mode == X86EMUL_MODE_PROT64)
ctxt->op_bytes = 8;
else
ctxt->op_bytes = 4;
}
if ((ctxt->d & No16) && ctxt->op_bytes == 2)
ctxt->op_bytes = 4;
if (ctxt->d & Sse)
ctxt->op_bytes = 16;
else if (ctxt->d & Mmx)
ctxt->op_bytes = 8;
}
/* ModRM and SIB bytes. */
if (ctxt->d & ModRM) {
rc = decode_modrm(ctxt, &ctxt->memop);
if (!has_seg_override) {
has_seg_override = true;
ctxt->seg_override = ctxt->modrm_seg;
}
} else if (ctxt->d & MemAbs)
rc = decode_abs(ctxt, &ctxt->memop);
if (rc != X86EMUL_CONTINUE)
goto done;
if (!has_seg_override)
ctxt->seg_override = VCPU_SREG_DS;
ctxt->memop.addr.mem.seg = ctxt->seg_override;
/*
* Decode and fetch the source operand: register, memory
* or immediate.
*/
rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask);
if (rc != X86EMUL_CONTINUE)
goto done;
/*
* Decode and fetch the second source operand: register, memory
* or immediate.
*/
rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask);
if (rc != X86EMUL_CONTINUE)
goto done;
/* Decode and fetch the destination operand: register or memory. */
rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask);
if (ctxt->rip_relative)
ctxt->memopp->addr.mem.ea = address_mask(ctxt,
ctxt->memopp->addr.mem.ea + ctxt->_eip);
done:
return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK;
}
bool x86_page_table_writing_insn(struct x86_emulate_ctxt *ctxt)
{
return ctxt->d & PageTable;
}
static bool string_insn_completed(struct x86_emulate_ctxt *ctxt)
{
/* The second termination condition only applies for REPE
* and REPNE. Test if the repeat string operation prefix is
* REPE/REPZ or REPNE/REPNZ and if it's the case it tests the
* corresponding termination condition according to:
* - if REPE/REPZ and ZF = 0 then done
* - if REPNE/REPNZ and ZF = 1 then done
*/
if (((ctxt->b == 0xa6) || (ctxt->b == 0xa7) ||
(ctxt->b == 0xae) || (ctxt->b == 0xaf))
&& (((ctxt->rep_prefix == REPE_PREFIX) &&
((ctxt->eflags & X86_EFLAGS_ZF) == 0))
|| ((ctxt->rep_prefix == REPNE_PREFIX) &&
((ctxt->eflags & X86_EFLAGS_ZF) == X86_EFLAGS_ZF))))
return true;
return false;
}
static int flush_pending_x87_faults(struct x86_emulate_ctxt *ctxt)
{
bool fault = false;
ctxt->ops->get_fpu(ctxt);
asm volatile("1: fwait \n\t"
"2: \n\t"
".pushsection .fixup,\"ax\" \n\t"
"3: \n\t"
"movb $1, %[fault] \n\t"
"jmp 2b \n\t"
".popsection \n\t"
_ASM_EXTABLE(1b, 3b)
: [fault]"+qm"(fault));
ctxt->ops->put_fpu(ctxt);
if (unlikely(fault))
return emulate_exception(ctxt, MF_VECTOR, 0, false);
return X86EMUL_CONTINUE;
}
static void fetch_possible_mmx_operand(struct x86_emulate_ctxt *ctxt,
struct operand *op)
{
if (op->type == OP_MM)
read_mmx_reg(ctxt, &op->mm_val, op->addr.mm);
}
static int fastop(struct x86_emulate_ctxt *ctxt, void (*fop)(struct fastop *))
{
register void *__sp asm(_ASM_SP);
ulong flags = (ctxt->eflags & EFLAGS_MASK) | X86_EFLAGS_IF;
if (!(ctxt->d & ByteOp))
fop += __ffs(ctxt->dst.bytes) * FASTOP_SIZE;
asm("push %[flags]; popf; call *%[fastop]; pushf; pop %[flags]\n"
: "+a"(ctxt->dst.val), "+d"(ctxt->src.val), [flags]"+D"(flags),
[fastop]"+S"(fop), "+r"(__sp)
: "c"(ctxt->src2.val));
ctxt->eflags = (ctxt->eflags & ~EFLAGS_MASK) | (flags & EFLAGS_MASK);
if (!fop) /* exception is returned in fop variable */
return emulate_de(ctxt);
return X86EMUL_CONTINUE;
}
void init_decode_cache(struct x86_emulate_ctxt *ctxt)
{
memset(&ctxt->rip_relative, 0,
(void *)&ctxt->modrm - (void *)&ctxt->rip_relative);
ctxt->io_read.pos = 0;
ctxt->io_read.end = 0;
ctxt->mem_read.end = 0;
}
int x86_emulate_insn(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
int rc = X86EMUL_CONTINUE;
int saved_dst_type = ctxt->dst.type;
ctxt->mem_read.pos = 0;
/* LOCK prefix is allowed only with some instructions */
if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) {
rc = emulate_ud(ctxt);
goto done;
}
if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) {
rc = emulate_ud(ctxt);
goto done;
}
if (unlikely(ctxt->d &
(No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) {
if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) ||
(ctxt->d & Undefined)) {
rc = emulate_ud(ctxt);
goto done;
}
if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM)))
|| ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) {
rc = emulate_ud(ctxt);
goto done;
}
if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) {
rc = emulate_nm(ctxt);
goto done;
}
if (ctxt->d & Mmx) {
rc = flush_pending_x87_faults(ctxt);
if (rc != X86EMUL_CONTINUE)
goto done;
/*
* Now that we know the fpu is exception safe, we can fetch
* operands from it.
*/
fetch_possible_mmx_operand(ctxt, &ctxt->src);
fetch_possible_mmx_operand(ctxt, &ctxt->src2);
if (!(ctxt->d & Mov))
fetch_possible_mmx_operand(ctxt, &ctxt->dst);
}
if (unlikely(ctxt->emul_flags & X86EMUL_GUEST_MASK) && ctxt->intercept) {
rc = emulator_check_intercept(ctxt, ctxt->intercept,
X86_ICPT_PRE_EXCEPT);
if (rc != X86EMUL_CONTINUE)
goto done;
}
/* Instruction can only be executed in protected mode */
if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) {
rc = emulate_ud(ctxt);
goto done;
}
/* Privileged instruction can be executed only in CPL=0 */
if ((ctxt->d & Priv) && ops->cpl(ctxt)) {
if (ctxt->d & PrivUD)
rc = emulate_ud(ctxt);
else
rc = emulate_gp(ctxt, 0);
goto done;
}
/* Do instruction specific permission checks */
if (ctxt->d & CheckPerm) {
rc = ctxt->check_perm(ctxt);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if (unlikely(ctxt->emul_flags & X86EMUL_GUEST_MASK) && (ctxt->d & Intercept)) {
rc = emulator_check_intercept(ctxt, ctxt->intercept,
X86_ICPT_POST_EXCEPT);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if (ctxt->rep_prefix && (ctxt->d & String)) {
/* All REP prefixes have the same first termination condition */
if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) {
string_registers_quirk(ctxt);
ctxt->eip = ctxt->_eip;
ctxt->eflags &= ~X86_EFLAGS_RF;
goto done;
}
}
}
if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) {
rc = segmented_read(ctxt, ctxt->src.addr.mem,
ctxt->src.valptr, ctxt->src.bytes);
if (rc != X86EMUL_CONTINUE)
goto done;
ctxt->src.orig_val64 = ctxt->src.val64;
}
if (ctxt->src2.type == OP_MEM) {
rc = segmented_read(ctxt, ctxt->src2.addr.mem,
&ctxt->src2.val, ctxt->src2.bytes);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if ((ctxt->d & DstMask) == ImplicitOps)
goto special_insn;
if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) {
/* optimisation - avoid slow emulated read if Mov */
rc = segmented_read(ctxt, ctxt->dst.addr.mem,
&ctxt->dst.val, ctxt->dst.bytes);
if (rc != X86EMUL_CONTINUE) {
if (!(ctxt->d & NoWrite) &&
rc == X86EMUL_PROPAGATE_FAULT &&
ctxt->exception.vector == PF_VECTOR)
ctxt->exception.error_code |= PFERR_WRITE_MASK;
goto done;
}
}
/* Copy full 64-bit value for CMPXCHG8B. */
ctxt->dst.orig_val64 = ctxt->dst.val64;
special_insn:
if (unlikely(ctxt->emul_flags & X86EMUL_GUEST_MASK) && (ctxt->d & Intercept)) {
rc = emulator_check_intercept(ctxt, ctxt->intercept,
X86_ICPT_POST_MEMACCESS);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if (ctxt->rep_prefix && (ctxt->d & String))
ctxt->eflags |= X86_EFLAGS_RF;
else
ctxt->eflags &= ~X86_EFLAGS_RF;
if (ctxt->execute) {
if (ctxt->d & Fastop) {
void (*fop)(struct fastop *) = (void *)ctxt->execute;
rc = fastop(ctxt, fop);
if (rc != X86EMUL_CONTINUE)
goto done;
goto writeback;
}
rc = ctxt->execute(ctxt);
if (rc != X86EMUL_CONTINUE)
goto done;
goto writeback;
}
if (ctxt->opcode_len == 2)
goto twobyte_insn;
else if (ctxt->opcode_len == 3)
goto threebyte_insn;
switch (ctxt->b) {
case 0x70 ... 0x7f: /* jcc (short) */
if (test_cc(ctxt->b, ctxt->eflags))
rc = jmp_rel(ctxt, ctxt->src.val);
break;
case 0x8d: /* lea r16/r32, m */
ctxt->dst.val = ctxt->src.addr.mem.ea;
break;
case 0x90 ... 0x97: /* nop / xchg reg, rax */
if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX))
ctxt->dst.type = OP_NONE;
else
rc = em_xchg(ctxt);
break;
case 0x98: /* cbw/cwde/cdqe */
switch (ctxt->op_bytes) {
case 2: ctxt->dst.val = (s8)ctxt->dst.val; break;
case 4: ctxt->dst.val = (s16)ctxt->dst.val; break;
case 8: ctxt->dst.val = (s32)ctxt->dst.val; break;
}
break;
case 0xcc: /* int3 */
rc = emulate_int(ctxt, 3);
break;
case 0xcd: /* int n */
rc = emulate_int(ctxt, ctxt->src.val);
break;
case 0xce: /* into */
if (ctxt->eflags & X86_EFLAGS_OF)
rc = emulate_int(ctxt, 4);
break;
case 0xe9: /* jmp rel */
case 0xeb: /* jmp rel short */
rc = jmp_rel(ctxt, ctxt->src.val);
ctxt->dst.type = OP_NONE; /* Disable writeback. */
break;
case 0xf4: /* hlt */
ctxt->ops->halt(ctxt);
break;
case 0xf5: /* cmc */
/* complement carry flag from eflags reg */
ctxt->eflags ^= X86_EFLAGS_CF;
break;
case 0xf8: /* clc */
ctxt->eflags &= ~X86_EFLAGS_CF;
break;
case 0xf9: /* stc */
ctxt->eflags |= X86_EFLAGS_CF;
break;
case 0xfc: /* cld */
ctxt->eflags &= ~X86_EFLAGS_DF;
break;
case 0xfd: /* std */
ctxt->eflags |= X86_EFLAGS_DF;
break;
default:
goto cannot_emulate;
}
if (rc != X86EMUL_CONTINUE)
goto done;
writeback:
if (ctxt->d & SrcWrite) {
BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR);
rc = writeback(ctxt, &ctxt->src);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if (!(ctxt->d & NoWrite)) {
rc = writeback(ctxt, &ctxt->dst);
if (rc != X86EMUL_CONTINUE)
goto done;
}
/*
* restore dst type in case the decoding will be reused
* (happens for string instruction )
*/
ctxt->dst.type = saved_dst_type;
if ((ctxt->d & SrcMask) == SrcSI)
string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src);
if ((ctxt->d & DstMask) == DstDI)
string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst);
if (ctxt->rep_prefix && (ctxt->d & String)) {
unsigned int count;
struct read_cache *r = &ctxt->io_read;
if ((ctxt->d & SrcMask) == SrcSI)
count = ctxt->src.count;
else
count = ctxt->dst.count;
register_address_increment(ctxt, VCPU_REGS_RCX, -count);
if (!string_insn_completed(ctxt)) {
/*
* Re-enter guest when pio read ahead buffer is empty
* or, if it is not used, after each 1024 iteration.
*/
if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) &&
(r->end == 0 || r->end != r->pos)) {
/*
* Reset read cache. Usually happens before
* decode, but since instruction is restarted
* we have to do it here.
*/
ctxt->mem_read.end = 0;
writeback_registers(ctxt);
return EMULATION_RESTART;
}
goto done; /* skip rip writeback */
}
ctxt->eflags &= ~X86_EFLAGS_RF;
}
ctxt->eip = ctxt->_eip;
done:
if (rc == X86EMUL_PROPAGATE_FAULT) {
WARN_ON(ctxt->exception.vector > 0x1f);
ctxt->have_exception = true;
}
if (rc == X86EMUL_INTERCEPTED)
return EMULATION_INTERCEPTED;
if (rc == X86EMUL_CONTINUE)
writeback_registers(ctxt);
return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK;
twobyte_insn:
switch (ctxt->b) {
case 0x09: /* wbinvd */
(ctxt->ops->wbinvd)(ctxt);
break;
case 0x08: /* invd */
case 0x0d: /* GrpP (prefetch) */
case 0x18: /* Grp16 (prefetch/nop) */
case 0x1f: /* nop */
break;
case 0x20: /* mov cr, reg */
ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg);
break;
case 0x21: /* mov from dr to reg */
ops->get_dr(ctxt, ctxt->modrm_reg, &ctxt->dst.val);
break;
case 0x40 ... 0x4f: /* cmov */
if (test_cc(ctxt->b, ctxt->eflags))
ctxt->dst.val = ctxt->src.val;
else if (ctxt->op_bytes != 4)
ctxt->dst.type = OP_NONE; /* no writeback */
break;
case 0x80 ... 0x8f: /* jnz rel, etc*/
if (test_cc(ctxt->b, ctxt->eflags))
rc = jmp_rel(ctxt, ctxt->src.val);
break;
case 0x90 ... 0x9f: /* setcc r/m8 */
ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags);
break;
case 0xb6 ... 0xb7: /* movzx */
ctxt->dst.bytes = ctxt->op_bytes;
ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val
: (u16) ctxt->src.val;
break;
case 0xbe ... 0xbf: /* movsx */
ctxt->dst.bytes = ctxt->op_bytes;
ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val :
(s16) ctxt->src.val;
break;
default:
goto cannot_emulate;
}
threebyte_insn:
if (rc != X86EMUL_CONTINUE)
goto done;
goto writeback;
cannot_emulate:
return EMULATION_FAILED;
}
void emulator_invalidate_register_cache(struct x86_emulate_ctxt *ctxt)
{
invalidate_registers(ctxt);
}
void emulator_writeback_register_cache(struct x86_emulate_ctxt *ctxt)
{
writeback_registers(ctxt);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_5345_0 |
crossvul-cpp_data_bad_3960_0 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* USB IBM C-It Video Camera driver
*
* Supports Xirlink C-It Video Camera, IBM PC Camera,
* IBM NetCamera and Veo Stingray.
*
* Copyright (C) 2010 Hans de Goede <hdegoede@redhat.com>
*
* This driver is based on earlier work of:
*
* (C) Copyright 1999 Johannes Erdfelt
* (C) Copyright 1999 Randy Dunlap
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define MODULE_NAME "xirlink-cit"
#include <linux/input.h>
#include "gspca.h"
MODULE_AUTHOR("Hans de Goede <hdegoede@redhat.com>");
MODULE_DESCRIPTION("Xirlink C-IT");
MODULE_LICENSE("GPL");
/* FIXME we should autodetect this */
static int ibm_netcam_pro;
module_param(ibm_netcam_pro, int, 0);
MODULE_PARM_DESC(ibm_netcam_pro,
"Use IBM Netcamera Pro init sequences for Model 3 cams");
/* FIXME this should be handled through the V4L2 input selection API */
static int rca_input;
module_param(rca_input, int, 0644);
MODULE_PARM_DESC(rca_input,
"Use rca input instead of ccd sensor on Model 3 cams");
/* specific webcam descriptor */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
struct v4l2_ctrl *lighting;
u8 model;
#define CIT_MODEL0 0 /* bcd version 0.01 cams ie the xvp-500 */
#define CIT_MODEL1 1 /* The model 1 - 4 nomenclature comes from the old */
#define CIT_MODEL2 2 /* ibmcam driver */
#define CIT_MODEL3 3
#define CIT_MODEL4 4
#define CIT_IBM_NETCAM_PRO 5
u8 input_index;
u8 button_state;
u8 stop_on_control_change;
u8 sof_read;
u8 sof_len;
};
static void sd_stop0(struct gspca_dev *gspca_dev);
static const struct v4l2_pix_format cif_yuv_mode[] = {
{176, 144, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{352, 288, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 352,
.sizeimage = 352 * 288 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
};
static const struct v4l2_pix_format vga_yuv_mode[] = {
{160, 120, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{320, 240, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{640, 480, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
};
static const struct v4l2_pix_format model0_mode[] = {
{160, 120, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{176, 144, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{320, 240, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
};
static const struct v4l2_pix_format model2_mode[] = {
{160, 120, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{176, 144, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{320, 240, V4L2_PIX_FMT_SGRBG8, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{352, 288, V4L2_PIX_FMT_SGRBG8, V4L2_FIELD_NONE,
.bytesperline = 352,
.sizeimage = 352 * 288 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
};
/*
* 01.01.08 - Added for RCA video in support -LO
* This struct is used to init the Model3 cam to use the RCA video in port
* instead of the CCD sensor.
*/
static const u16 rca_initdata[][3] = {
{0, 0x0000, 0x010c},
{0, 0x0006, 0x012c},
{0, 0x0078, 0x012d},
{0, 0x0046, 0x012f},
{0, 0xd141, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfea8, 0x0124},
{1, 0x0000, 0x0116},
{0, 0x0064, 0x0116},
{1, 0x0000, 0x0115},
{0, 0x0003, 0x0115},
{0, 0x0008, 0x0123},
{0, 0x0000, 0x0117},
{0, 0x0000, 0x0112},
{0, 0x0080, 0x0100},
{0, 0x0000, 0x0100},
{1, 0x0000, 0x0116},
{0, 0x0060, 0x0116},
{0, 0x0002, 0x0112},
{0, 0x0000, 0x0123},
{0, 0x0001, 0x0117},
{0, 0x0040, 0x0108},
{0, 0x0019, 0x012c},
{0, 0x0040, 0x0116},
{0, 0x000a, 0x0115},
{0, 0x000b, 0x0115},
{0, 0x0078, 0x012d},
{0, 0x0046, 0x012f},
{0, 0xd141, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfea8, 0x0124},
{0, 0x0064, 0x0116},
{0, 0x0000, 0x0115},
{0, 0x0001, 0x0115},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00aa, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00f2, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x000f, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00f8, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00fc, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00f9, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x003c, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0027, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0019, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0021, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0006, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0045, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002a, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x000e, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002b, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00f4, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002c, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0004, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002d, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0014, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002e, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0003, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002f, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0003, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0014, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0053, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0x0000, 0x0101},
{0, 0x00a0, 0x0103},
{0, 0x0078, 0x0105},
{0, 0x0000, 0x010a},
{0, 0x0024, 0x010b},
{0, 0x0028, 0x0119},
{0, 0x0088, 0x011b},
{0, 0x0002, 0x011d},
{0, 0x0003, 0x011e},
{0, 0x0000, 0x0129},
{0, 0x00fc, 0x012b},
{0, 0x0008, 0x0102},
{0, 0x0000, 0x0104},
{0, 0x0008, 0x011a},
{0, 0x0028, 0x011c},
{0, 0x0021, 0x012a},
{0, 0x0000, 0x0118},
{0, 0x0000, 0x0132},
{0, 0x0000, 0x0109},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0031, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00dc, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0032, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0020, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0030, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0008, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0x0003, 0x0111},
};
/* TESTME the old ibmcam driver repeats certain commands to Model1 cameras, we
do the same for now (testing needed to see if this is really necessary) */
static const int cit_model1_ntries = 5;
static const int cit_model1_ntries2 = 2;
static int cit_write_reg(struct gspca_dev *gspca_dev, u16 value, u16 index)
{
struct usb_device *udev = gspca_dev->dev;
int err;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT,
value, index, NULL, 0, 1000);
if (err < 0)
pr_err("Failed to write a register (index 0x%04X, value 0x%02X, error %d)\n",
index, value, err);
return 0;
}
static int cit_read_reg(struct gspca_dev *gspca_dev, u16 index, int verbose)
{
struct usb_device *udev = gspca_dev->dev;
__u8 *buf = gspca_dev->usb_buf;
int res;
res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x01,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT,
0x00, index, buf, 8, 1000);
if (res < 0) {
pr_err("Failed to read a register (index 0x%04X, error %d)\n",
index, res);
return res;
}
if (verbose)
gspca_dbg(gspca_dev, D_PROBE, "Register %04x value: %02x\n",
index, buf[0]);
return 0;
}
/*
* cit_send_FF_04_02()
*
* This procedure sends magic 3-command prefix to the camera.
* The purpose of this prefix is not known.
*
* History:
* 1/2/00 Created.
*/
static void cit_send_FF_04_02(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x00FF, 0x0127);
cit_write_reg(gspca_dev, 0x0004, 0x0124);
cit_write_reg(gspca_dev, 0x0002, 0x0124);
}
static void cit_send_00_04_06(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x0004, 0x0124);
cit_write_reg(gspca_dev, 0x0006, 0x0124);
}
static void cit_send_x_00(struct gspca_dev *gspca_dev, unsigned short x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
}
static void cit_send_x_00_05(struct gspca_dev *gspca_dev, unsigned short x)
{
cit_send_x_00(gspca_dev, x);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
}
static void cit_send_x_00_05_02(struct gspca_dev *gspca_dev, unsigned short x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
cit_write_reg(gspca_dev, 0x0002, 0x0124);
}
static void cit_send_x_01_00_05(struct gspca_dev *gspca_dev, u16 x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0001, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
}
static void cit_send_x_00_05_02_01(struct gspca_dev *gspca_dev, u16 x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
cit_write_reg(gspca_dev, 0x0002, 0x0124);
cit_write_reg(gspca_dev, 0x0001, 0x0124);
}
static void cit_send_x_00_05_02_08_01(struct gspca_dev *gspca_dev, u16 x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
cit_write_reg(gspca_dev, 0x0002, 0x0124);
cit_write_reg(gspca_dev, 0x0008, 0x0124);
cit_write_reg(gspca_dev, 0x0001, 0x0124);
}
static void cit_Packet_Format1(struct gspca_dev *gspca_dev, u16 fkey, u16 val)
{
cit_send_x_01_00_05(gspca_dev, 0x0088);
cit_send_x_00_05(gspca_dev, fkey);
cit_send_x_00_05_02_08_01(gspca_dev, val);
cit_send_x_00_05(gspca_dev, 0x0088);
cit_send_x_00_05_02_01(gspca_dev, fkey);
cit_send_x_00_05(gspca_dev, 0x0089);
cit_send_x_00(gspca_dev, fkey);
cit_send_00_04_06(gspca_dev);
cit_read_reg(gspca_dev, 0x0126, 0);
cit_send_FF_04_02(gspca_dev);
}
static void cit_PacketFormat2(struct gspca_dev *gspca_dev, u16 fkey, u16 val)
{
cit_send_x_01_00_05(gspca_dev, 0x0088);
cit_send_x_00_05(gspca_dev, fkey);
cit_send_x_00_05_02(gspca_dev, val);
}
static void cit_model2_Packet2(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x00ff, 0x012d);
cit_write_reg(gspca_dev, 0xfea3, 0x0124);
}
static void cit_model2_Packet1(struct gspca_dev *gspca_dev, u16 v1, u16 v2)
{
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x00ff, 0x012e);
cit_write_reg(gspca_dev, v1, 0x012f);
cit_write_reg(gspca_dev, 0x00ff, 0x0130);
cit_write_reg(gspca_dev, 0xc719, 0x0124);
cit_write_reg(gspca_dev, v2, 0x0127);
cit_model2_Packet2(gspca_dev);
}
/*
* cit_model3_Packet1()
*
* 00_0078_012d
* 00_0097_012f
* 00_d141_0124
* 00_0096_0127
* 00_fea8_0124
*/
static void cit_model3_Packet1(struct gspca_dev *gspca_dev, u16 v1, u16 v2)
{
cit_write_reg(gspca_dev, 0x0078, 0x012d);
cit_write_reg(gspca_dev, v1, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, v2, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
}
static void cit_model4_Packet1(struct gspca_dev *gspca_dev, u16 v1, u16 v2)
{
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, v1, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, v2, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
}
static void cit_model4_BrightnessPacket(struct gspca_dev *gspca_dev, u16 val)
{
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0026, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, val, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0038, 0x012d);
cit_write_reg(gspca_dev, 0x0004, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
}
/* this function is called at probe time */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
struct cam *cam;
sd->model = id->driver_info;
if (sd->model == CIT_MODEL3 && ibm_netcam_pro)
sd->model = CIT_IBM_NETCAM_PRO;
cam = &gspca_dev->cam;
switch (sd->model) {
case CIT_MODEL0:
cam->cam_mode = model0_mode;
cam->nmodes = ARRAY_SIZE(model0_mode);
sd->sof_len = 4;
break;
case CIT_MODEL1:
cam->cam_mode = cif_yuv_mode;
cam->nmodes = ARRAY_SIZE(cif_yuv_mode);
sd->sof_len = 4;
break;
case CIT_MODEL2:
cam->cam_mode = model2_mode + 1; /* no 160x120 */
cam->nmodes = 3;
break;
case CIT_MODEL3:
cam->cam_mode = vga_yuv_mode;
cam->nmodes = ARRAY_SIZE(vga_yuv_mode);
sd->stop_on_control_change = 1;
sd->sof_len = 4;
break;
case CIT_MODEL4:
cam->cam_mode = model2_mode;
cam->nmodes = ARRAY_SIZE(model2_mode);
break;
case CIT_IBM_NETCAM_PRO:
cam->cam_mode = vga_yuv_mode;
cam->nmodes = 2; /* no 640 x 480 */
cam->input_flags = V4L2_IN_ST_VFLIP;
sd->stop_on_control_change = 1;
sd->sof_len = 4;
break;
}
return 0;
}
static int cit_init_model0(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x0000, 0x0100); /* turn on led */
cit_write_reg(gspca_dev, 0x0001, 0x0112); /* turn on autogain ? */
cit_write_reg(gspca_dev, 0x0000, 0x0400);
cit_write_reg(gspca_dev, 0x0001, 0x0400);
cit_write_reg(gspca_dev, 0x0000, 0x0420);
cit_write_reg(gspca_dev, 0x0001, 0x0420);
cit_write_reg(gspca_dev, 0x000d, 0x0409);
cit_write_reg(gspca_dev, 0x0002, 0x040a);
cit_write_reg(gspca_dev, 0x0018, 0x0405);
cit_write_reg(gspca_dev, 0x0008, 0x0435);
cit_write_reg(gspca_dev, 0x0026, 0x040b);
cit_write_reg(gspca_dev, 0x0007, 0x0437);
cit_write_reg(gspca_dev, 0x0015, 0x042f);
cit_write_reg(gspca_dev, 0x002b, 0x0439);
cit_write_reg(gspca_dev, 0x0026, 0x043a);
cit_write_reg(gspca_dev, 0x0008, 0x0438);
cit_write_reg(gspca_dev, 0x001e, 0x042b);
cit_write_reg(gspca_dev, 0x0041, 0x042c);
return 0;
}
static int cit_init_ibm_netcam_pro(struct gspca_dev *gspca_dev)
{
cit_read_reg(gspca_dev, 0x128, 1);
cit_write_reg(gspca_dev, 0x0003, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0117);
cit_write_reg(gspca_dev, 0x0008, 0x0123);
cit_write_reg(gspca_dev, 0x0000, 0x0100);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0112);
cit_write_reg(gspca_dev, 0x0000, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0123);
cit_write_reg(gspca_dev, 0x0001, 0x0117);
cit_write_reg(gspca_dev, 0x0040, 0x0108);
cit_write_reg(gspca_dev, 0x0019, 0x012c);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0115);
cit_write_reg(gspca_dev, 0x000b, 0x0115);
cit_write_reg(gspca_dev, 0x0078, 0x012d);
cit_write_reg(gspca_dev, 0x0001, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0079, 0x012d);
cit_write_reg(gspca_dev, 0x00ff, 0x0130);
cit_write_reg(gspca_dev, 0xcd41, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_read_reg(gspca_dev, 0x0126, 1);
cit_model3_Packet1(gspca_dev, 0x0000, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0000, 0x0001);
cit_model3_Packet1(gspca_dev, 0x000b, 0x0000);
cit_model3_Packet1(gspca_dev, 0x000c, 0x0008);
cit_model3_Packet1(gspca_dev, 0x000d, 0x003a);
cit_model3_Packet1(gspca_dev, 0x000e, 0x0060);
cit_model3_Packet1(gspca_dev, 0x000f, 0x0060);
cit_model3_Packet1(gspca_dev, 0x0010, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0011, 0x0004);
cit_model3_Packet1(gspca_dev, 0x0012, 0x0028);
cit_model3_Packet1(gspca_dev, 0x0013, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0014, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0015, 0x00fb);
cit_model3_Packet1(gspca_dev, 0x0016, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0017, 0x0037);
cit_model3_Packet1(gspca_dev, 0x0018, 0x0036);
cit_model3_Packet1(gspca_dev, 0x001e, 0x0000);
cit_model3_Packet1(gspca_dev, 0x001f, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0020, 0x00c1);
cit_model3_Packet1(gspca_dev, 0x0021, 0x0034);
cit_model3_Packet1(gspca_dev, 0x0022, 0x0034);
cit_model3_Packet1(gspca_dev, 0x0025, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0028, 0x0022);
cit_model3_Packet1(gspca_dev, 0x0029, 0x000a);
cit_model3_Packet1(gspca_dev, 0x002b, 0x0000);
cit_model3_Packet1(gspca_dev, 0x002c, 0x0000);
cit_model3_Packet1(gspca_dev, 0x002d, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x002e, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x002f, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x0030, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x0031, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x0032, 0x0007);
cit_model3_Packet1(gspca_dev, 0x0033, 0x0005);
cit_model3_Packet1(gspca_dev, 0x0037, 0x0040);
cit_model3_Packet1(gspca_dev, 0x0039, 0x0000);
cit_model3_Packet1(gspca_dev, 0x003a, 0x0000);
cit_model3_Packet1(gspca_dev, 0x003b, 0x0001);
cit_model3_Packet1(gspca_dev, 0x003c, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0040, 0x000c);
cit_model3_Packet1(gspca_dev, 0x0041, 0x00fb);
cit_model3_Packet1(gspca_dev, 0x0042, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0043, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0045, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0046, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0047, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0048, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0049, 0x0000);
cit_model3_Packet1(gspca_dev, 0x004a, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x004b, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x004c, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x004f, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0050, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0051, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0055, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0056, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0057, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0058, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0059, 0x0000);
cit_model3_Packet1(gspca_dev, 0x005c, 0x0016);
cit_model3_Packet1(gspca_dev, 0x005d, 0x0022);
cit_model3_Packet1(gspca_dev, 0x005e, 0x003c);
cit_model3_Packet1(gspca_dev, 0x005f, 0x0050);
cit_model3_Packet1(gspca_dev, 0x0060, 0x0044);
cit_model3_Packet1(gspca_dev, 0x0061, 0x0005);
cit_model3_Packet1(gspca_dev, 0x006a, 0x007e);
cit_model3_Packet1(gspca_dev, 0x006f, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0072, 0x001b);
cit_model3_Packet1(gspca_dev, 0x0073, 0x0005);
cit_model3_Packet1(gspca_dev, 0x0074, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0075, 0x001b);
cit_model3_Packet1(gspca_dev, 0x0076, 0x002a);
cit_model3_Packet1(gspca_dev, 0x0077, 0x003c);
cit_model3_Packet1(gspca_dev, 0x0078, 0x0050);
cit_model3_Packet1(gspca_dev, 0x007b, 0x0000);
cit_model3_Packet1(gspca_dev, 0x007c, 0x0011);
cit_model3_Packet1(gspca_dev, 0x007d, 0x0024);
cit_model3_Packet1(gspca_dev, 0x007e, 0x0043);
cit_model3_Packet1(gspca_dev, 0x007f, 0x005a);
cit_model3_Packet1(gspca_dev, 0x0084, 0x0020);
cit_model3_Packet1(gspca_dev, 0x0085, 0x0033);
cit_model3_Packet1(gspca_dev, 0x0086, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0087, 0x0030);
cit_model3_Packet1(gspca_dev, 0x0088, 0x0070);
cit_model3_Packet1(gspca_dev, 0x008b, 0x0008);
cit_model3_Packet1(gspca_dev, 0x008f, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0090, 0x0006);
cit_model3_Packet1(gspca_dev, 0x0091, 0x0028);
cit_model3_Packet1(gspca_dev, 0x0092, 0x005a);
cit_model3_Packet1(gspca_dev, 0x0093, 0x0082);
cit_model3_Packet1(gspca_dev, 0x0096, 0x0014);
cit_model3_Packet1(gspca_dev, 0x0097, 0x0020);
cit_model3_Packet1(gspca_dev, 0x0098, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00b0, 0x0046);
cit_model3_Packet1(gspca_dev, 0x00b1, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00b2, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00b3, 0x0004);
cit_model3_Packet1(gspca_dev, 0x00b4, 0x0007);
cit_model3_Packet1(gspca_dev, 0x00b6, 0x0002);
cit_model3_Packet1(gspca_dev, 0x00b7, 0x0004);
cit_model3_Packet1(gspca_dev, 0x00bb, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00bc, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00bd, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00bf, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00c0, 0x00c8);
cit_model3_Packet1(gspca_dev, 0x00c1, 0x0014);
cit_model3_Packet1(gspca_dev, 0x00c2, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00c3, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00c4, 0x0004);
cit_model3_Packet1(gspca_dev, 0x00cb, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00cc, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00cd, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00ce, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00cf, 0x0020);
cit_model3_Packet1(gspca_dev, 0x00d0, 0x0040);
cit_model3_Packet1(gspca_dev, 0x00d1, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00d1, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00d2, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00d3, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00ea, 0x0008);
cit_model3_Packet1(gspca_dev, 0x00eb, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00ec, 0x00e8);
cit_model3_Packet1(gspca_dev, 0x00ed, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00ef, 0x0022);
cit_model3_Packet1(gspca_dev, 0x00f0, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00f2, 0x0028);
cit_model3_Packet1(gspca_dev, 0x00f4, 0x0002);
cit_model3_Packet1(gspca_dev, 0x00f5, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00fa, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00fb, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00fc, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00fd, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00fe, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00ff, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00be, 0x0003);
cit_model3_Packet1(gspca_dev, 0x00c8, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00c9, 0x0020);
cit_model3_Packet1(gspca_dev, 0x00ca, 0x0040);
cit_model3_Packet1(gspca_dev, 0x0053, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0082, 0x000e);
cit_model3_Packet1(gspca_dev, 0x0083, 0x0020);
cit_model3_Packet1(gspca_dev, 0x0034, 0x003c);
cit_model3_Packet1(gspca_dev, 0x006e, 0x0055);
cit_model3_Packet1(gspca_dev, 0x0062, 0x0005);
cit_model3_Packet1(gspca_dev, 0x0063, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0066, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0067, 0x0006);
cit_model3_Packet1(gspca_dev, 0x006b, 0x0010);
cit_model3_Packet1(gspca_dev, 0x005a, 0x0001);
cit_model3_Packet1(gspca_dev, 0x005b, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0023, 0x0006);
cit_model3_Packet1(gspca_dev, 0x0026, 0x0004);
cit_model3_Packet1(gspca_dev, 0x0036, 0x0069);
cit_model3_Packet1(gspca_dev, 0x0038, 0x0064);
cit_model3_Packet1(gspca_dev, 0x003d, 0x0003);
cit_model3_Packet1(gspca_dev, 0x003e, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00b8, 0x0014);
cit_model3_Packet1(gspca_dev, 0x00b9, 0x0014);
cit_model3_Packet1(gspca_dev, 0x00e6, 0x0004);
cit_model3_Packet1(gspca_dev, 0x00e8, 0x0001);
return 0;
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
cit_init_model0(gspca_dev);
sd_stop0(gspca_dev);
break;
case CIT_MODEL1:
case CIT_MODEL2:
case CIT_MODEL3:
case CIT_MODEL4:
break; /* All is done in sd_start */
case CIT_IBM_NETCAM_PRO:
cit_init_ibm_netcam_pro(gspca_dev);
sd_stop0(gspca_dev);
break;
}
return 0;
}
static int cit_set_brightness(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
int i;
switch (sd->model) {
case CIT_MODEL0:
case CIT_IBM_NETCAM_PRO:
/* No (known) brightness control for these */
break;
case CIT_MODEL1:
/* Model 1: Brightness range 0 - 63 */
cit_Packet_Format1(gspca_dev, 0x0031, val);
cit_Packet_Format1(gspca_dev, 0x0032, val);
cit_Packet_Format1(gspca_dev, 0x0033, val);
break;
case CIT_MODEL2:
/* Model 2: Brightness range 0x60 - 0xee */
/* Scale 0 - 63 to 0x60 - 0xee */
i = 0x60 + val * 2254 / 1000;
cit_model2_Packet1(gspca_dev, 0x001a, i);
break;
case CIT_MODEL3:
/* Model 3: Brightness range 'i' in [0x0C..0x3F] */
i = val;
if (i < 0x0c)
i = 0x0c;
cit_model3_Packet1(gspca_dev, 0x0036, i);
break;
case CIT_MODEL4:
/* Model 4: Brightness range 'i' in [0x04..0xb4] */
/* Scale 0 - 63 to 0x04 - 0xb4 */
i = 0x04 + val * 2794 / 1000;
cit_model4_BrightnessPacket(gspca_dev, i);
break;
}
return 0;
}
static int cit_set_contrast(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0: {
int i;
/* gain 0-15, 0-20 -> 0-15 */
i = val * 1000 / 1333;
cit_write_reg(gspca_dev, i, 0x0422);
/* gain 0-31, may not be lower then 0x0422, 0-20 -> 0-31 */
i = val * 2000 / 1333;
cit_write_reg(gspca_dev, i, 0x0423);
/* gain 0-127, may not be lower then 0x0423, 0-20 -> 0-63 */
i = val * 4000 / 1333;
cit_write_reg(gspca_dev, i, 0x0424);
/* gain 0-127, may not be lower then 0x0424, , 0-20 -> 0-127 */
i = val * 8000 / 1333;
cit_write_reg(gspca_dev, i, 0x0425);
break;
}
case CIT_MODEL2:
case CIT_MODEL4:
/* These models do not have this control. */
break;
case CIT_MODEL1:
{
/* Scale 0 - 20 to 15 - 0 */
int i, new_contrast = (20 - val) * 1000 / 1333;
for (i = 0; i < cit_model1_ntries; i++) {
cit_Packet_Format1(gspca_dev, 0x0014, new_contrast);
cit_send_FF_04_02(gspca_dev);
}
break;
}
case CIT_MODEL3:
{ /* Preset hardware values */
static const struct {
unsigned short cv1;
unsigned short cv2;
unsigned short cv3;
} cv[7] = {
{ 0x05, 0x05, 0x0f }, /* Minimum */
{ 0x04, 0x04, 0x16 },
{ 0x02, 0x03, 0x16 },
{ 0x02, 0x08, 0x16 },
{ 0x01, 0x0c, 0x16 },
{ 0x01, 0x0e, 0x16 },
{ 0x01, 0x10, 0x16 } /* Maximum */
};
int i = val / 3;
cit_model3_Packet1(gspca_dev, 0x0067, cv[i].cv1);
cit_model3_Packet1(gspca_dev, 0x005b, cv[i].cv2);
cit_model3_Packet1(gspca_dev, 0x005c, cv[i].cv3);
break;
}
case CIT_IBM_NETCAM_PRO:
cit_model3_Packet1(gspca_dev, 0x005b, val + 1);
break;
}
return 0;
}
static int cit_set_hue(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL1:
case CIT_IBM_NETCAM_PRO:
/* No hue control for these models */
break;
case CIT_MODEL2:
cit_model2_Packet1(gspca_dev, 0x0024, val);
/* cit_model2_Packet1(gspca_dev, 0x0020, sat); */
break;
case CIT_MODEL3: {
/* Model 3: Brightness range 'i' in [0x05..0x37] */
/* TESTME according to the ibmcam driver this does not work */
if (0) {
/* Scale 0 - 127 to 0x05 - 0x37 */
int i = 0x05 + val * 1000 / 2540;
cit_model3_Packet1(gspca_dev, 0x007e, i);
}
break;
}
case CIT_MODEL4:
/* HDG: taken from ibmcam, setting the color gains does not
* really belong here.
*
* I am not sure r/g/b_gain variables exactly control gain
* of those channels. Most likely they subtly change some
* very internal image processing settings in the camera.
* In any case, here is what they do, and feel free to tweak:
*
* r_gain: seriously affects red gain
* g_gain: seriously affects green gain
* b_gain: seriously affects blue gain
* hue: changes average color from violet (0) to red (0xFF)
*/
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 160, 0x0127); /* Green gain */
cit_write_reg(gspca_dev, 160, 0x012e); /* Red gain */
cit_write_reg(gspca_dev, 160, 0x0130); /* Blue gain */
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, val, 0x012d); /* Hue */
cit_write_reg(gspca_dev, 0xf545, 0x0124);
break;
}
return 0;
}
static int cit_set_sharpness(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL2:
case CIT_MODEL4:
case CIT_IBM_NETCAM_PRO:
/* These models do not have this control */
break;
case CIT_MODEL1: {
int i;
static const unsigned short sa[] = {
0x11, 0x13, 0x16, 0x18, 0x1a, 0x8, 0x0a };
for (i = 0; i < cit_model1_ntries; i++)
cit_PacketFormat2(gspca_dev, 0x0013, sa[val]);
break;
}
case CIT_MODEL3:
{ /*
* "Use a table of magic numbers.
* This setting doesn't really change much.
* But that's how Windows does it."
*/
static const struct {
unsigned short sv1;
unsigned short sv2;
unsigned short sv3;
unsigned short sv4;
} sv[7] = {
{ 0x00, 0x00, 0x05, 0x14 }, /* Smoothest */
{ 0x01, 0x04, 0x05, 0x14 },
{ 0x02, 0x04, 0x05, 0x14 },
{ 0x03, 0x04, 0x05, 0x14 },
{ 0x03, 0x05, 0x05, 0x14 },
{ 0x03, 0x06, 0x05, 0x14 },
{ 0x03, 0x07, 0x05, 0x14 } /* Sharpest */
};
cit_model3_Packet1(gspca_dev, 0x0060, sv[val].sv1);
cit_model3_Packet1(gspca_dev, 0x0061, sv[val].sv2);
cit_model3_Packet1(gspca_dev, 0x0062, sv[val].sv3);
cit_model3_Packet1(gspca_dev, 0x0063, sv[val].sv4);
break;
}
}
return 0;
}
/*
* cit_set_lighting()
*
* Camera model 1:
* We have 3 levels of lighting conditions: 0=Bright, 1=Medium, 2=Low.
*
* Camera model 2:
* We have 16 levels of lighting, 0 for bright light and up to 15 for
* low light. But values above 5 or so are useless because camera is
* not really capable to produce anything worth viewing at such light.
* This setting may be altered only in certain camera state.
*
* Low lighting forces slower FPS.
*
* History:
* 1/5/00 Created.
* 2/20/00 Added support for Model 2 cameras.
*/
static void cit_set_lighting(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL2:
case CIT_MODEL3:
case CIT_MODEL4:
case CIT_IBM_NETCAM_PRO:
break;
case CIT_MODEL1: {
int i;
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x0027, val);
break;
}
}
}
static void cit_set_hflip(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
if (val)
cit_write_reg(gspca_dev, 0x0020, 0x0115);
else
cit_write_reg(gspca_dev, 0x0040, 0x0115);
break;
case CIT_MODEL1:
case CIT_MODEL2:
case CIT_MODEL3:
case CIT_MODEL4:
case CIT_IBM_NETCAM_PRO:
break;
}
}
static int cit_restart_stream(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL1:
cit_write_reg(gspca_dev, 0x0001, 0x0114);
/* Fall through */
case CIT_MODEL2:
case CIT_MODEL4:
cit_write_reg(gspca_dev, 0x00c0, 0x010c); /* Go! */
usb_clear_halt(gspca_dev->dev, gspca_dev->urb[0]->pipe);
break;
case CIT_MODEL3:
case CIT_IBM_NETCAM_PRO:
cit_write_reg(gspca_dev, 0x0001, 0x0114);
cit_write_reg(gspca_dev, 0x00c0, 0x010c); /* Go! */
usb_clear_halt(gspca_dev->dev, gspca_dev->urb[0]->pipe);
/* Clear button events from while we were not streaming */
cit_write_reg(gspca_dev, 0x0001, 0x0113);
break;
}
sd->sof_read = 0;
return 0;
}
static int cit_get_packet_size(struct gspca_dev *gspca_dev)
{
struct usb_host_interface *alt;
struct usb_interface *intf;
intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
alt = usb_altnum_to_altsetting(intf, gspca_dev->alt);
if (!alt) {
pr_err("Couldn't get altsetting\n");
return -EIO;
}
return le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
}
/* Calculate the clockdiv giving us max fps given the available bandwidth */
static int cit_get_clock_div(struct gspca_dev *gspca_dev)
{
int clock_div = 7; /* 0=30 1=25 2=20 3=15 4=12 5=7.5 6=6 7=3fps ?? */
int fps[8] = { 30, 25, 20, 15, 12, 8, 6, 3 };
int packet_size;
packet_size = cit_get_packet_size(gspca_dev);
if (packet_size < 0)
return packet_size;
while (clock_div > 3 &&
1000 * packet_size >
gspca_dev->pixfmt.width * gspca_dev->pixfmt.height *
fps[clock_div - 1] * 3 / 2)
clock_div--;
gspca_dbg(gspca_dev, D_PROBE,
"PacketSize: %d, res: %dx%d -> using clockdiv: %d (%d fps)\n",
packet_size,
gspca_dev->pixfmt.width, gspca_dev->pixfmt.height,
clock_div, fps[clock_div]);
return clock_div;
}
static int cit_start_model0(struct gspca_dev *gspca_dev)
{
const unsigned short compression = 0; /* 0=none, 7=best frame rate */
int clock_div;
clock_div = cit_get_clock_div(gspca_dev);
if (clock_div < 0)
return clock_div;
cit_write_reg(gspca_dev, 0x0000, 0x0100); /* turn on led */
cit_write_reg(gspca_dev, 0x0003, 0x0438);
cit_write_reg(gspca_dev, 0x001e, 0x042b);
cit_write_reg(gspca_dev, 0x0041, 0x042c);
cit_write_reg(gspca_dev, 0x0008, 0x0436);
cit_write_reg(gspca_dev, 0x0024, 0x0403);
cit_write_reg(gspca_dev, 0x002c, 0x0404);
cit_write_reg(gspca_dev, 0x0002, 0x0426);
cit_write_reg(gspca_dev, 0x0014, 0x0427);
switch (gspca_dev->pixfmt.width) {
case 160: /* 160x120 */
cit_write_reg(gspca_dev, 0x0004, 0x010b);
cit_write_reg(gspca_dev, 0x0001, 0x010a);
cit_write_reg(gspca_dev, 0x0010, 0x0102);
cit_write_reg(gspca_dev, 0x00a0, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x0078, 0x0105);
break;
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0x0006, 0x010b);
cit_write_reg(gspca_dev, 0x0000, 0x010a);
cit_write_reg(gspca_dev, 0x0005, 0x0102);
cit_write_reg(gspca_dev, 0x00b0, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x0090, 0x0105);
break;
case 320: /* 320x240 */
cit_write_reg(gspca_dev, 0x0008, 0x010b);
cit_write_reg(gspca_dev, 0x0004, 0x010a);
cit_write_reg(gspca_dev, 0x0005, 0x0102);
cit_write_reg(gspca_dev, 0x00a0, 0x0103);
cit_write_reg(gspca_dev, 0x0010, 0x0104);
cit_write_reg(gspca_dev, 0x0078, 0x0105);
break;
}
cit_write_reg(gspca_dev, compression, 0x0109);
cit_write_reg(gspca_dev, clock_div, 0x0111);
return 0;
}
static int cit_start_model1(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int i, clock_div;
clock_div = cit_get_clock_div(gspca_dev);
if (clock_div < 0)
return clock_div;
cit_read_reg(gspca_dev, 0x0128, 1);
cit_read_reg(gspca_dev, 0x0100, 0);
cit_write_reg(gspca_dev, 0x01, 0x0100); /* LED On */
cit_read_reg(gspca_dev, 0x0100, 0);
cit_write_reg(gspca_dev, 0x81, 0x0100); /* LED Off */
cit_read_reg(gspca_dev, 0x0100, 0);
cit_write_reg(gspca_dev, 0x01, 0x0100); /* LED On */
cit_write_reg(gspca_dev, 0x01, 0x0108);
cit_write_reg(gspca_dev, 0x03, 0x0112);
cit_read_reg(gspca_dev, 0x0115, 0);
cit_write_reg(gspca_dev, 0x06, 0x0115);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x44, 0x0116);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x40, 0x0116);
cit_read_reg(gspca_dev, 0x0115, 0);
cit_write_reg(gspca_dev, 0x0e, 0x0115);
cit_write_reg(gspca_dev, 0x19, 0x012c);
cit_Packet_Format1(gspca_dev, 0x00, 0x1e);
cit_Packet_Format1(gspca_dev, 0x39, 0x0d);
cit_Packet_Format1(gspca_dev, 0x39, 0x09);
cit_Packet_Format1(gspca_dev, 0x3b, 0x00);
cit_Packet_Format1(gspca_dev, 0x28, 0x22);
cit_Packet_Format1(gspca_dev, 0x27, 0x00);
cit_Packet_Format1(gspca_dev, 0x2b, 0x1f);
cit_Packet_Format1(gspca_dev, 0x39, 0x08);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x2c, 0x00);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x30, 0x14);
cit_PacketFormat2(gspca_dev, 0x39, 0x02);
cit_PacketFormat2(gspca_dev, 0x01, 0xe1);
cit_PacketFormat2(gspca_dev, 0x02, 0xcd);
cit_PacketFormat2(gspca_dev, 0x03, 0xcd);
cit_PacketFormat2(gspca_dev, 0x04, 0xfa);
cit_PacketFormat2(gspca_dev, 0x3f, 0xff);
cit_PacketFormat2(gspca_dev, 0x39, 0x00);
cit_PacketFormat2(gspca_dev, 0x39, 0x02);
cit_PacketFormat2(gspca_dev, 0x0a, 0x37);
cit_PacketFormat2(gspca_dev, 0x0b, 0xb8);
cit_PacketFormat2(gspca_dev, 0x0c, 0xf3);
cit_PacketFormat2(gspca_dev, 0x0d, 0xe3);
cit_PacketFormat2(gspca_dev, 0x0e, 0x0d);
cit_PacketFormat2(gspca_dev, 0x0f, 0xf2);
cit_PacketFormat2(gspca_dev, 0x10, 0xd5);
cit_PacketFormat2(gspca_dev, 0x11, 0xba);
cit_PacketFormat2(gspca_dev, 0x12, 0x53);
cit_PacketFormat2(gspca_dev, 0x3f, 0xff);
cit_PacketFormat2(gspca_dev, 0x39, 0x00);
cit_PacketFormat2(gspca_dev, 0x39, 0x02);
cit_PacketFormat2(gspca_dev, 0x16, 0x00);
cit_PacketFormat2(gspca_dev, 0x17, 0x28);
cit_PacketFormat2(gspca_dev, 0x18, 0x7d);
cit_PacketFormat2(gspca_dev, 0x19, 0xbe);
cit_PacketFormat2(gspca_dev, 0x3f, 0xff);
cit_PacketFormat2(gspca_dev, 0x39, 0x00);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x00, 0x18);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x13, 0x18);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x14, 0x06);
/* TESTME These are handled through controls
KEEP until someone can test leaving this out is ok */
if (0) {
/* This is default brightness */
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x31, 0x37);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x32, 0x46);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x33, 0x55);
}
cit_Packet_Format1(gspca_dev, 0x2e, 0x04);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x2d, 0x04);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x29, 0x80);
cit_Packet_Format1(gspca_dev, 0x2c, 0x01);
cit_Packet_Format1(gspca_dev, 0x30, 0x17);
cit_Packet_Format1(gspca_dev, 0x39, 0x08);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x34, 0x00);
cit_write_reg(gspca_dev, 0x00, 0x0101);
cit_write_reg(gspca_dev, 0x00, 0x010a);
switch (gspca_dev->pixfmt.width) {
case 128: /* 128x96 */
cit_write_reg(gspca_dev, 0x80, 0x0103);
cit_write_reg(gspca_dev, 0x60, 0x0105);
cit_write_reg(gspca_dev, 0x0c, 0x010b);
cit_write_reg(gspca_dev, 0x04, 0x011b); /* Same everywhere */
cit_write_reg(gspca_dev, 0x0b, 0x011d);
cit_write_reg(gspca_dev, 0x00, 0x011e); /* Same everywhere */
cit_write_reg(gspca_dev, 0x00, 0x0129);
break;
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0xb0, 0x0103);
cit_write_reg(gspca_dev, 0x8f, 0x0105);
cit_write_reg(gspca_dev, 0x06, 0x010b);
cit_write_reg(gspca_dev, 0x04, 0x011b); /* Same everywhere */
cit_write_reg(gspca_dev, 0x0d, 0x011d);
cit_write_reg(gspca_dev, 0x00, 0x011e); /* Same everywhere */
cit_write_reg(gspca_dev, 0x03, 0x0129);
break;
case 352: /* 352x288 */
cit_write_reg(gspca_dev, 0xb0, 0x0103);
cit_write_reg(gspca_dev, 0x90, 0x0105);
cit_write_reg(gspca_dev, 0x02, 0x010b);
cit_write_reg(gspca_dev, 0x04, 0x011b); /* Same everywhere */
cit_write_reg(gspca_dev, 0x05, 0x011d);
cit_write_reg(gspca_dev, 0x00, 0x011e); /* Same everywhere */
cit_write_reg(gspca_dev, 0x00, 0x0129);
break;
}
cit_write_reg(gspca_dev, 0xff, 0x012b);
/* TESTME These are handled through controls
KEEP until someone can test leaving this out is ok */
if (0) {
/* This is another brightness - don't know why */
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x31, 0xc3);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x32, 0xd2);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x33, 0xe1);
/* Default contrast */
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x14, 0x0a);
/* Default sharpness */
for (i = 0; i < cit_model1_ntries2; i++)
cit_PacketFormat2(gspca_dev, 0x13, 0x1a);
/* Default lighting conditions */
cit_Packet_Format1(gspca_dev, 0x0027,
v4l2_ctrl_g_ctrl(sd->lighting));
}
/* Assorted init */
switch (gspca_dev->pixfmt.width) {
case 128: /* 128x96 */
cit_Packet_Format1(gspca_dev, 0x2b, 0x1e);
cit_write_reg(gspca_dev, 0xc9, 0x0119); /* Same everywhere */
cit_write_reg(gspca_dev, 0x80, 0x0109); /* Same everywhere */
cit_write_reg(gspca_dev, 0x36, 0x0102);
cit_write_reg(gspca_dev, 0x1a, 0x0104);
cit_write_reg(gspca_dev, 0x04, 0x011a); /* Same everywhere */
cit_write_reg(gspca_dev, 0x2b, 0x011c);
cit_write_reg(gspca_dev, 0x23, 0x012a); /* Same everywhere */
break;
case 176: /* 176x144 */
cit_Packet_Format1(gspca_dev, 0x2b, 0x1e);
cit_write_reg(gspca_dev, 0xc9, 0x0119); /* Same everywhere */
cit_write_reg(gspca_dev, 0x80, 0x0109); /* Same everywhere */
cit_write_reg(gspca_dev, 0x04, 0x0102);
cit_write_reg(gspca_dev, 0x02, 0x0104);
cit_write_reg(gspca_dev, 0x04, 0x011a); /* Same everywhere */
cit_write_reg(gspca_dev, 0x2b, 0x011c);
cit_write_reg(gspca_dev, 0x23, 0x012a); /* Same everywhere */
break;
case 352: /* 352x288 */
cit_Packet_Format1(gspca_dev, 0x2b, 0x1f);
cit_write_reg(gspca_dev, 0xc9, 0x0119); /* Same everywhere */
cit_write_reg(gspca_dev, 0x80, 0x0109); /* Same everywhere */
cit_write_reg(gspca_dev, 0x08, 0x0102);
cit_write_reg(gspca_dev, 0x01, 0x0104);
cit_write_reg(gspca_dev, 0x04, 0x011a); /* Same everywhere */
cit_write_reg(gspca_dev, 0x2f, 0x011c);
cit_write_reg(gspca_dev, 0x23, 0x012a); /* Same everywhere */
break;
}
cit_write_reg(gspca_dev, 0x01, 0x0100); /* LED On */
cit_write_reg(gspca_dev, clock_div, 0x0111);
return 0;
}
static int cit_start_model2(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int clock_div = 0;
cit_write_reg(gspca_dev, 0x0000, 0x0100); /* LED on */
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0112);
cit_write_reg(gspca_dev, 0x00bc, 0x012c);
cit_write_reg(gspca_dev, 0x0008, 0x012b);
cit_write_reg(gspca_dev, 0x0000, 0x0108);
cit_write_reg(gspca_dev, 0x0001, 0x0133);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
switch (gspca_dev->pixfmt.width) {
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0x002c, 0x0103); /* All except 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x0104); /* Same */
cit_write_reg(gspca_dev, 0x0024, 0x0105); /* 176x144, 352x288 */
cit_write_reg(gspca_dev, 0x00b9, 0x010a); /* Unique to this mode */
cit_write_reg(gspca_dev, 0x0038, 0x0119); /* Unique to this mode */
/* TESTME HDG: this does not seem right
(it is 2 for all other resolutions) */
sd->sof_len = 10;
break;
case 320: /* 320x240 */
cit_write_reg(gspca_dev, 0x0028, 0x0103); /* Unique to this mode */
cit_write_reg(gspca_dev, 0x0000, 0x0104); /* Same */
cit_write_reg(gspca_dev, 0x001e, 0x0105); /* 320x240, 352x240 */
cit_write_reg(gspca_dev, 0x0039, 0x010a); /* All except 176x144 */
cit_write_reg(gspca_dev, 0x0070, 0x0119); /* All except 176x144 */
sd->sof_len = 2;
break;
#if 0
case VIDEOSIZE_352x240:
cit_write_reg(gspca_dev, 0x002c, 0x0103); /* All except 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x0104); /* Same */
cit_write_reg(gspca_dev, 0x001e, 0x0105); /* 320x240, 352x240 */
cit_write_reg(gspca_dev, 0x0039, 0x010a); /* All except 176x144 */
cit_write_reg(gspca_dev, 0x0070, 0x0119); /* All except 176x144 */
sd->sof_len = 2;
break;
#endif
case 352: /* 352x288 */
cit_write_reg(gspca_dev, 0x002c, 0x0103); /* All except 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x0104); /* Same */
cit_write_reg(gspca_dev, 0x0024, 0x0105); /* 176x144, 352x288 */
cit_write_reg(gspca_dev, 0x0039, 0x010a); /* All except 176x144 */
cit_write_reg(gspca_dev, 0x0070, 0x0119); /* All except 176x144 */
sd->sof_len = 2;
break;
}
cit_write_reg(gspca_dev, 0x0000, 0x0100); /* LED on */
switch (gspca_dev->pixfmt.width) {
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0x0050, 0x0111);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
break;
case 320: /* 320x240 */
case 352: /* 352x288 */
cit_write_reg(gspca_dev, 0x0040, 0x0111);
cit_write_reg(gspca_dev, 0x00c0, 0x0111);
break;
}
cit_write_reg(gspca_dev, 0x009b, 0x010f);
cit_write_reg(gspca_dev, 0x00bb, 0x010f);
/*
* Hardware settings, may affect CMOS sensor; not user controls!
* -------------------------------------------------------------
* 0x0004: no effect
* 0x0006: hardware effect
* 0x0008: no effect
* 0x000a: stops video stream, probably important h/w setting
* 0x000c: changes color in hardware manner (not user setting)
* 0x0012: changes number of colors (does not affect speed)
* 0x002a: no effect
* 0x002c: hardware setting (related to scan lines)
* 0x002e: stops video stream, probably important h/w setting
*/
cit_model2_Packet1(gspca_dev, 0x000a, 0x005c);
cit_model2_Packet1(gspca_dev, 0x0004, 0x0000);
cit_model2_Packet1(gspca_dev, 0x0006, 0x00fb);
cit_model2_Packet1(gspca_dev, 0x0008, 0x0000);
cit_model2_Packet1(gspca_dev, 0x000c, 0x0009);
cit_model2_Packet1(gspca_dev, 0x0012, 0x000a);
cit_model2_Packet1(gspca_dev, 0x002a, 0x0000);
cit_model2_Packet1(gspca_dev, 0x002c, 0x0000);
cit_model2_Packet1(gspca_dev, 0x002e, 0x0008);
/*
* Function 0x0030 pops up all over the place. Apparently
* it is a hardware control register, with every bit assigned to
* do something.
*/
cit_model2_Packet1(gspca_dev, 0x0030, 0x0000);
/*
* Magic control of CMOS sensor. Only lower values like
* 0-3 work, and picture shifts left or right. Don't change.
*/
switch (gspca_dev->pixfmt.width) {
case 176: /* 176x144 */
cit_model2_Packet1(gspca_dev, 0x0014, 0x0002);
cit_model2_Packet1(gspca_dev, 0x0016, 0x0002); /* Horizontal shift */
cit_model2_Packet1(gspca_dev, 0x0018, 0x004a); /* Another hardware setting */
clock_div = 6;
break;
case 320: /* 320x240 */
cit_model2_Packet1(gspca_dev, 0x0014, 0x0009);
cit_model2_Packet1(gspca_dev, 0x0016, 0x0005); /* Horizontal shift */
cit_model2_Packet1(gspca_dev, 0x0018, 0x0044); /* Another hardware setting */
clock_div = 8;
break;
#if 0
case VIDEOSIZE_352x240:
/* This mode doesn't work as Windows programs it; changed to work */
cit_model2_Packet1(gspca_dev, 0x0014, 0x0009); /* Windows sets this to 8 */
cit_model2_Packet1(gspca_dev, 0x0016, 0x0003); /* Horizontal shift */
cit_model2_Packet1(gspca_dev, 0x0018, 0x0044); /* Windows sets this to 0x0045 */
clock_div = 10;
break;
#endif
case 352: /* 352x288 */
cit_model2_Packet1(gspca_dev, 0x0014, 0x0003);
cit_model2_Packet1(gspca_dev, 0x0016, 0x0002); /* Horizontal shift */
cit_model2_Packet1(gspca_dev, 0x0018, 0x004a); /* Another hardware setting */
clock_div = 16;
break;
}
/* TESTME These are handled through controls
KEEP until someone can test leaving this out is ok */
if (0)
cit_model2_Packet1(gspca_dev, 0x001a, 0x005a);
/*
* We have our own frame rate setting varying from 0 (slowest) to 6
* (fastest). The camera model 2 allows frame rate in range [0..0x1F]
# where 0 is also the slowest setting. However for all practical
# reasons high settings make no sense because USB is not fast enough
# to support high FPS. Be aware that the picture datastream will be
# severely disrupted if you ask for frame rate faster than allowed
# for the video size - see below:
*
* Allowable ranges (obtained experimentally on OHCI, K6-3, 450 MHz):
* -----------------------------------------------------------------
* 176x144: [6..31]
* 320x240: [8..31]
* 352x240: [10..31]
* 352x288: [16..31] I have to raise lower threshold for stability...
*
* As usual, slower FPS provides better sensitivity.
*/
cit_model2_Packet1(gspca_dev, 0x001c, clock_div);
/*
* This setting does not visibly affect pictures; left it here
* because it was present in Windows USB data stream. This function
* does not allow arbitrary values and apparently is a bit mask, to
* be activated only at appropriate time. Don't change it randomly!
*/
switch (gspca_dev->pixfmt.width) {
case 176: /* 176x144 */
cit_model2_Packet1(gspca_dev, 0x0026, 0x00c2);
break;
case 320: /* 320x240 */
cit_model2_Packet1(gspca_dev, 0x0026, 0x0044);
break;
#if 0
case VIDEOSIZE_352x240:
cit_model2_Packet1(gspca_dev, 0x0026, 0x0046);
break;
#endif
case 352: /* 352x288 */
cit_model2_Packet1(gspca_dev, 0x0026, 0x0048);
break;
}
cit_model2_Packet1(gspca_dev, 0x0028, v4l2_ctrl_g_ctrl(sd->lighting));
/* model2 cannot change the backlight compensation while streaming */
v4l2_ctrl_grab(sd->lighting, true);
/* color balance rg2 */
cit_model2_Packet1(gspca_dev, 0x001e, 0x002f);
/* saturation */
cit_model2_Packet1(gspca_dev, 0x0020, 0x0034);
/* color balance yb */
cit_model2_Packet1(gspca_dev, 0x0022, 0x00a0);
/* Hardware control command */
cit_model2_Packet1(gspca_dev, 0x0030, 0x0004);
return 0;
}
static int cit_start_model3(struct gspca_dev *gspca_dev)
{
const unsigned short compression = 0; /* 0=none, 7=best frame rate */
int i, clock_div = 0;
/* HDG not in ibmcam driver, added to see if it helps with
auto-detecting between model3 and ibm netcamera pro */
cit_read_reg(gspca_dev, 0x128, 1);
cit_write_reg(gspca_dev, 0x0000, 0x0100);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0112);
cit_write_reg(gspca_dev, 0x0000, 0x0123);
cit_write_reg(gspca_dev, 0x0001, 0x0117);
cit_write_reg(gspca_dev, 0x0040, 0x0108);
cit_write_reg(gspca_dev, 0x0019, 0x012c);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0115);
cit_write_reg(gspca_dev, 0x0003, 0x0115);
cit_read_reg(gspca_dev, 0x0115, 0);
cit_write_reg(gspca_dev, 0x000b, 0x0115);
/* TESTME HDG not in ibmcam driver, added to see if it helps with
auto-detecting between model3 and ibm netcamera pro */
if (0) {
cit_write_reg(gspca_dev, 0x0078, 0x012d);
cit_write_reg(gspca_dev, 0x0001, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0079, 0x012d);
cit_write_reg(gspca_dev, 0x00ff, 0x0130);
cit_write_reg(gspca_dev, 0xcd41, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_read_reg(gspca_dev, 0x0126, 1);
}
cit_model3_Packet1(gspca_dev, 0x000a, 0x0040);
cit_model3_Packet1(gspca_dev, 0x000b, 0x00f6);
cit_model3_Packet1(gspca_dev, 0x000c, 0x0002);
cit_model3_Packet1(gspca_dev, 0x000d, 0x0020);
cit_model3_Packet1(gspca_dev, 0x000e, 0x0033);
cit_model3_Packet1(gspca_dev, 0x000f, 0x0007);
cit_model3_Packet1(gspca_dev, 0x0010, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0011, 0x0070);
cit_model3_Packet1(gspca_dev, 0x0012, 0x0030);
cit_model3_Packet1(gspca_dev, 0x0013, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0014, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0015, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0016, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0017, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0018, 0x0000);
cit_model3_Packet1(gspca_dev, 0x001e, 0x00c3);
cit_model3_Packet1(gspca_dev, 0x0020, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0028, 0x0010);
cit_model3_Packet1(gspca_dev, 0x0029, 0x0054);
cit_model3_Packet1(gspca_dev, 0x002a, 0x0013);
cit_model3_Packet1(gspca_dev, 0x002b, 0x0007);
cit_model3_Packet1(gspca_dev, 0x002d, 0x0028);
cit_model3_Packet1(gspca_dev, 0x002e, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0031, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0032, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0033, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0034, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0035, 0x0038);
cit_model3_Packet1(gspca_dev, 0x003a, 0x0001);
cit_model3_Packet1(gspca_dev, 0x003c, 0x001e);
cit_model3_Packet1(gspca_dev, 0x003f, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0041, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0046, 0x003f);
cit_model3_Packet1(gspca_dev, 0x0047, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0050, 0x0005);
cit_model3_Packet1(gspca_dev, 0x0052, 0x001a);
cit_model3_Packet1(gspca_dev, 0x0053, 0x0003);
cit_model3_Packet1(gspca_dev, 0x005a, 0x006b);
cit_model3_Packet1(gspca_dev, 0x005d, 0x001e);
cit_model3_Packet1(gspca_dev, 0x005e, 0x0030);
cit_model3_Packet1(gspca_dev, 0x005f, 0x0041);
cit_model3_Packet1(gspca_dev, 0x0064, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0065, 0x0015);
cit_model3_Packet1(gspca_dev, 0x0068, 0x000f);
cit_model3_Packet1(gspca_dev, 0x0079, 0x0000);
cit_model3_Packet1(gspca_dev, 0x007a, 0x0000);
cit_model3_Packet1(gspca_dev, 0x007c, 0x003f);
cit_model3_Packet1(gspca_dev, 0x0082, 0x000f);
cit_model3_Packet1(gspca_dev, 0x0085, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0099, 0x0000);
cit_model3_Packet1(gspca_dev, 0x009b, 0x0023);
cit_model3_Packet1(gspca_dev, 0x009c, 0x0022);
cit_model3_Packet1(gspca_dev, 0x009d, 0x0096);
cit_model3_Packet1(gspca_dev, 0x009e, 0x0096);
cit_model3_Packet1(gspca_dev, 0x009f, 0x000a);
switch (gspca_dev->pixfmt.width) {
case 160:
cit_write_reg(gspca_dev, 0x0000, 0x0101); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x00a0, 0x0103); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0078, 0x0105); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x010a); /* Same */
cit_write_reg(gspca_dev, 0x0024, 0x010b); /* Differs everywhere */
cit_write_reg(gspca_dev, 0x00a9, 0x0119);
cit_write_reg(gspca_dev, 0x0016, 0x011b);
cit_write_reg(gspca_dev, 0x0002, 0x011d); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0003, 0x011e); /* Same on 160x120, 640x480 */
cit_write_reg(gspca_dev, 0x0000, 0x0129); /* Same */
cit_write_reg(gspca_dev, 0x00fc, 0x012b); /* Same */
cit_write_reg(gspca_dev, 0x0018, 0x0102);
cit_write_reg(gspca_dev, 0x0004, 0x0104);
cit_write_reg(gspca_dev, 0x0004, 0x011a);
cit_write_reg(gspca_dev, 0x0028, 0x011c);
cit_write_reg(gspca_dev, 0x0022, 0x012a); /* Same */
cit_write_reg(gspca_dev, 0x0000, 0x0118);
cit_write_reg(gspca_dev, 0x0000, 0x0132);
cit_model3_Packet1(gspca_dev, 0x0021, 0x0001); /* Same */
cit_write_reg(gspca_dev, compression, 0x0109);
clock_div = 3;
break;
case 320:
cit_write_reg(gspca_dev, 0x0000, 0x0101); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x00a0, 0x0103); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0078, 0x0105); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x010a); /* Same */
cit_write_reg(gspca_dev, 0x0028, 0x010b); /* Differs everywhere */
cit_write_reg(gspca_dev, 0x0002, 0x011d); /* Same */
cit_write_reg(gspca_dev, 0x0000, 0x011e);
cit_write_reg(gspca_dev, 0x0000, 0x0129); /* Same */
cit_write_reg(gspca_dev, 0x00fc, 0x012b); /* Same */
/* 4 commands from 160x120 skipped */
cit_write_reg(gspca_dev, 0x0022, 0x012a); /* Same */
cit_model3_Packet1(gspca_dev, 0x0021, 0x0001); /* Same */
cit_write_reg(gspca_dev, compression, 0x0109);
cit_write_reg(gspca_dev, 0x00d9, 0x0119);
cit_write_reg(gspca_dev, 0x0006, 0x011b);
cit_write_reg(gspca_dev, 0x0021, 0x0102); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0010, 0x0104);
cit_write_reg(gspca_dev, 0x0004, 0x011a);
cit_write_reg(gspca_dev, 0x003f, 0x011c);
cit_write_reg(gspca_dev, 0x001c, 0x0118);
cit_write_reg(gspca_dev, 0x0000, 0x0132);
clock_div = 5;
break;
case 640:
cit_write_reg(gspca_dev, 0x00f0, 0x0105);
cit_write_reg(gspca_dev, 0x0000, 0x010a); /* Same */
cit_write_reg(gspca_dev, 0x0038, 0x010b); /* Differs everywhere */
cit_write_reg(gspca_dev, 0x00d9, 0x0119); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0006, 0x011b); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0004, 0x011d); /* NC */
cit_write_reg(gspca_dev, 0x0003, 0x011e); /* Same on 160x120, 640x480 */
cit_write_reg(gspca_dev, 0x0000, 0x0129); /* Same */
cit_write_reg(gspca_dev, 0x00fc, 0x012b); /* Same */
cit_write_reg(gspca_dev, 0x0021, 0x0102); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0016, 0x0104); /* NC */
cit_write_reg(gspca_dev, 0x0004, 0x011a); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x003f, 0x011c); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0022, 0x012a); /* Same */
cit_write_reg(gspca_dev, 0x001c, 0x0118); /* Same on 320x240, 640x480 */
cit_model3_Packet1(gspca_dev, 0x0021, 0x0001); /* Same */
cit_write_reg(gspca_dev, compression, 0x0109);
cit_write_reg(gspca_dev, 0x0040, 0x0101);
cit_write_reg(gspca_dev, 0x0040, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0132); /* Same on 320x240, 640x480 */
clock_div = 7;
break;
}
cit_model3_Packet1(gspca_dev, 0x007e, 0x000e); /* Hue */
cit_model3_Packet1(gspca_dev, 0x0036, 0x0011); /* Brightness */
cit_model3_Packet1(gspca_dev, 0x0060, 0x0002); /* Sharpness */
cit_model3_Packet1(gspca_dev, 0x0061, 0x0004); /* Sharpness */
cit_model3_Packet1(gspca_dev, 0x0062, 0x0005); /* Sharpness */
cit_model3_Packet1(gspca_dev, 0x0063, 0x0014); /* Sharpness */
cit_model3_Packet1(gspca_dev, 0x0096, 0x00a0); /* Red sharpness */
cit_model3_Packet1(gspca_dev, 0x0097, 0x0096); /* Blue sharpness */
cit_model3_Packet1(gspca_dev, 0x0067, 0x0001); /* Contrast */
cit_model3_Packet1(gspca_dev, 0x005b, 0x000c); /* Contrast */
cit_model3_Packet1(gspca_dev, 0x005c, 0x0016); /* Contrast */
cit_model3_Packet1(gspca_dev, 0x0098, 0x000b);
cit_model3_Packet1(gspca_dev, 0x002c, 0x0003); /* Was 1, broke 640x480 */
cit_model3_Packet1(gspca_dev, 0x002f, 0x002a);
cit_model3_Packet1(gspca_dev, 0x0030, 0x0029);
cit_model3_Packet1(gspca_dev, 0x0037, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0038, 0x0059);
cit_model3_Packet1(gspca_dev, 0x003d, 0x002e);
cit_model3_Packet1(gspca_dev, 0x003e, 0x0028);
cit_model3_Packet1(gspca_dev, 0x0078, 0x0005);
cit_model3_Packet1(gspca_dev, 0x007b, 0x0011);
cit_model3_Packet1(gspca_dev, 0x007d, 0x004b);
cit_model3_Packet1(gspca_dev, 0x007f, 0x0022);
cit_model3_Packet1(gspca_dev, 0x0080, 0x000c);
cit_model3_Packet1(gspca_dev, 0x0081, 0x000b);
cit_model3_Packet1(gspca_dev, 0x0083, 0x00fd);
cit_model3_Packet1(gspca_dev, 0x0086, 0x000b);
cit_model3_Packet1(gspca_dev, 0x0087, 0x000b);
cit_model3_Packet1(gspca_dev, 0x007e, 0x000e);
cit_model3_Packet1(gspca_dev, 0x0096, 0x00a0); /* Red sharpness */
cit_model3_Packet1(gspca_dev, 0x0097, 0x0096); /* Blue sharpness */
cit_model3_Packet1(gspca_dev, 0x0098, 0x000b);
/* FIXME we should probably use cit_get_clock_div() here (in
combination with isoc negotiation using the programmable isoc size)
like with the IBM netcam pro). */
cit_write_reg(gspca_dev, clock_div, 0x0111); /* Clock Divider */
switch (gspca_dev->pixfmt.width) {
case 160:
cit_model3_Packet1(gspca_dev, 0x001f, 0x0000); /* Same */
cit_model3_Packet1(gspca_dev, 0x0039, 0x001f); /* Same */
cit_model3_Packet1(gspca_dev, 0x003b, 0x003c); /* Same */
cit_model3_Packet1(gspca_dev, 0x0040, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0051, 0x000a);
break;
case 320:
cit_model3_Packet1(gspca_dev, 0x001f, 0x0000); /* Same */
cit_model3_Packet1(gspca_dev, 0x0039, 0x001f); /* Same */
cit_model3_Packet1(gspca_dev, 0x003b, 0x003c); /* Same */
cit_model3_Packet1(gspca_dev, 0x0040, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0051, 0x000b);
break;
case 640:
cit_model3_Packet1(gspca_dev, 0x001f, 0x0002); /* !Same */
cit_model3_Packet1(gspca_dev, 0x0039, 0x003e); /* !Same */
cit_model3_Packet1(gspca_dev, 0x0040, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0051, 0x000a);
break;
}
/* if (sd->input_index) { */
if (rca_input) {
for (i = 0; i < ARRAY_SIZE(rca_initdata); i++) {
if (rca_initdata[i][0])
cit_read_reg(gspca_dev, rca_initdata[i][2], 0);
else
cit_write_reg(gspca_dev, rca_initdata[i][1],
rca_initdata[i][2]);
}
}
return 0;
}
static int cit_start_model4(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
cit_write_reg(gspca_dev, 0x0000, 0x0100);
cit_write_reg(gspca_dev, 0x00c0, 0x0111);
cit_write_reg(gspca_dev, 0x00bc, 0x012c);
cit_write_reg(gspca_dev, 0x0080, 0x012b);
cit_write_reg(gspca_dev, 0x0000, 0x0108);
cit_write_reg(gspca_dev, 0x0001, 0x0133);
cit_write_reg(gspca_dev, 0x009b, 0x010f);
cit_write_reg(gspca_dev, 0x00bb, 0x010f);
cit_model4_Packet1(gspca_dev, 0x0038, 0x0000);
cit_model4_Packet1(gspca_dev, 0x000a, 0x005c);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0004, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x00fb, 0x012e);
cit_write_reg(gspca_dev, 0x0000, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x000c, 0x0127);
cit_write_reg(gspca_dev, 0x0009, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0012, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0008, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x002a, 0x012d);
cit_write_reg(gspca_dev, 0x0000, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_model4_Packet1(gspca_dev, 0x0034, 0x0000);
switch (gspca_dev->pixfmt.width) {
case 128: /* 128x96 */
cit_write_reg(gspca_dev, 0x0070, 0x0119);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
cit_write_reg(gspca_dev, 0x0039, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x0028, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x001e, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x000a, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005a, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0043, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00eb, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0017, 0x0127);
cit_write_reg(gspca_dev, 0x0013, 0x012e);
cit_write_reg(gspca_dev, 0x0031, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0017, 0x012d);
cit_write_reg(gspca_dev, 0x0078, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
sd->sof_len = 2;
break;
case 160: /* 160x120 */
cit_write_reg(gspca_dev, 0x0038, 0x0119);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
cit_write_reg(gspca_dev, 0x00b9, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x0028, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x001e, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x000b, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005a, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0043, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00c7, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0025, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0048, 0x0127);
cit_write_reg(gspca_dev, 0x0035, 0x012e);
cit_write_reg(gspca_dev, 0x00d0, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0048, 0x012d);
cit_write_reg(gspca_dev, 0x0090, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0001, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
sd->sof_len = 2;
break;
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0x0038, 0x0119);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
cit_write_reg(gspca_dev, 0x00b9, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x002c, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x0024, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0007, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0001, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005e, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0049, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00c7, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0028, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0010, 0x0127);
cit_write_reg(gspca_dev, 0x0013, 0x012e);
cit_write_reg(gspca_dev, 0x002a, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0010, 0x012d);
cit_write_reg(gspca_dev, 0x006d, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0001, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
/* TESTME HDG: this does not seem right
(it is 2 for all other resolutions) */
sd->sof_len = 10;
break;
case 320: /* 320x240 */
cit_write_reg(gspca_dev, 0x0070, 0x0119);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
cit_write_reg(gspca_dev, 0x0039, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x0028, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x001e, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x000a, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005a, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0043, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00eb, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0017, 0x0127);
cit_write_reg(gspca_dev, 0x0013, 0x012e);
cit_write_reg(gspca_dev, 0x0031, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0017, 0x012d);
cit_write_reg(gspca_dev, 0x0078, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
sd->sof_len = 2;
break;
case 352: /* 352x288 */
cit_write_reg(gspca_dev, 0x0070, 0x0119);
cit_write_reg(gspca_dev, 0x00c0, 0x0111);
cit_write_reg(gspca_dev, 0x0039, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x002c, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x0024, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0006, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0002, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005e, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0049, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00cf, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0010, 0x0127);
cit_write_reg(gspca_dev, 0x0013, 0x012e);
cit_write_reg(gspca_dev, 0x0025, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0010, 0x012d);
cit_write_reg(gspca_dev, 0x0048, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
sd->sof_len = 2;
break;
}
cit_model4_Packet1(gspca_dev, 0x0038, 0x0004);
return 0;
}
static int cit_start_ibm_netcam_pro(struct gspca_dev *gspca_dev)
{
const unsigned short compression = 0; /* 0=none, 7=best frame rate */
int i, clock_div;
clock_div = cit_get_clock_div(gspca_dev);
if (clock_div < 0)
return clock_div;
cit_write_reg(gspca_dev, 0x0003, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0117);
cit_write_reg(gspca_dev, 0x0008, 0x0123);
cit_write_reg(gspca_dev, 0x0000, 0x0100);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
/* cit_write_reg(gspca_dev, 0x0002, 0x0112); see sd_stop0 */
cit_write_reg(gspca_dev, 0x0000, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0123);
cit_write_reg(gspca_dev, 0x0001, 0x0117);
cit_write_reg(gspca_dev, 0x0040, 0x0108);
cit_write_reg(gspca_dev, 0x0019, 0x012c);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
/* cit_write_reg(gspca_dev, 0x000b, 0x0115); see sd_stop0 */
cit_model3_Packet1(gspca_dev, 0x0049, 0x0000);
cit_write_reg(gspca_dev, 0x0000, 0x0101); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x003a, 0x0102); /* Hstart */
cit_write_reg(gspca_dev, 0x00a0, 0x0103); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0078, 0x0105); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x010a); /* Same */
cit_write_reg(gspca_dev, 0x0002, 0x011d); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x0129); /* Same */
cit_write_reg(gspca_dev, 0x00fc, 0x012b); /* Same */
cit_write_reg(gspca_dev, 0x0022, 0x012a); /* Same */
switch (gspca_dev->pixfmt.width) {
case 160: /* 160x120 */
cit_write_reg(gspca_dev, 0x0024, 0x010b);
cit_write_reg(gspca_dev, 0x0089, 0x0119);
cit_write_reg(gspca_dev, 0x000a, 0x011b);
cit_write_reg(gspca_dev, 0x0003, 0x011e);
cit_write_reg(gspca_dev, 0x0007, 0x0104);
cit_write_reg(gspca_dev, 0x0009, 0x011a);
cit_write_reg(gspca_dev, 0x008b, 0x011c);
cit_write_reg(gspca_dev, 0x0008, 0x0118);
cit_write_reg(gspca_dev, 0x0000, 0x0132);
break;
case 320: /* 320x240 */
cit_write_reg(gspca_dev, 0x0028, 0x010b);
cit_write_reg(gspca_dev, 0x00d9, 0x0119);
cit_write_reg(gspca_dev, 0x0006, 0x011b);
cit_write_reg(gspca_dev, 0x0000, 0x011e);
cit_write_reg(gspca_dev, 0x000e, 0x0104);
cit_write_reg(gspca_dev, 0x0004, 0x011a);
cit_write_reg(gspca_dev, 0x003f, 0x011c);
cit_write_reg(gspca_dev, 0x000c, 0x0118);
cit_write_reg(gspca_dev, 0x0000, 0x0132);
break;
}
cit_model3_Packet1(gspca_dev, 0x0019, 0x0031);
cit_model3_Packet1(gspca_dev, 0x001a, 0x0003);
cit_model3_Packet1(gspca_dev, 0x001b, 0x0038);
cit_model3_Packet1(gspca_dev, 0x001c, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0024, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0027, 0x0001);
cit_model3_Packet1(gspca_dev, 0x002a, 0x0004);
cit_model3_Packet1(gspca_dev, 0x0035, 0x000b);
cit_model3_Packet1(gspca_dev, 0x003f, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0044, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0054, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00c4, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00e7, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00e9, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00ee, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00f3, 0x00c0);
cit_write_reg(gspca_dev, compression, 0x0109);
cit_write_reg(gspca_dev, clock_div, 0x0111);
/* if (sd->input_index) { */
if (rca_input) {
for (i = 0; i < ARRAY_SIZE(rca_initdata); i++) {
if (rca_initdata[i][0])
cit_read_reg(gspca_dev, rca_initdata[i][2], 0);
else
cit_write_reg(gspca_dev, rca_initdata[i][1],
rca_initdata[i][2]);
}
}
return 0;
}
/* -- start the camera -- */
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int packet_size;
packet_size = cit_get_packet_size(gspca_dev);
if (packet_size < 0)
return packet_size;
switch (sd->model) {
case CIT_MODEL0:
cit_start_model0(gspca_dev);
break;
case CIT_MODEL1:
cit_start_model1(gspca_dev);
break;
case CIT_MODEL2:
cit_start_model2(gspca_dev);
break;
case CIT_MODEL3:
cit_start_model3(gspca_dev);
break;
case CIT_MODEL4:
cit_start_model4(gspca_dev);
break;
case CIT_IBM_NETCAM_PRO:
cit_start_ibm_netcam_pro(gspca_dev);
break;
}
/* Program max isoc packet size */
cit_write_reg(gspca_dev, packet_size >> 8, 0x0106);
cit_write_reg(gspca_dev, packet_size & 0xff, 0x0107);
cit_restart_stream(gspca_dev);
return 0;
}
static int sd_isoc_init(struct gspca_dev *gspca_dev)
{
struct usb_host_interface *alt;
int max_packet_size;
switch (gspca_dev->pixfmt.width) {
case 160:
max_packet_size = 450;
break;
case 176:
max_packet_size = 600;
break;
default:
max_packet_size = 1022;
break;
}
/* Start isoc bandwidth "negotiation" at max isoc bandwidth */
alt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];
alt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(max_packet_size);
return 0;
}
static int sd_isoc_nego(struct gspca_dev *gspca_dev)
{
int ret, packet_size, min_packet_size;
struct usb_host_interface *alt;
switch (gspca_dev->pixfmt.width) {
case 160:
min_packet_size = 200;
break;
case 176:
min_packet_size = 266;
break;
default:
min_packet_size = 400;
break;
}
alt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
if (packet_size <= min_packet_size)
return -EIO;
packet_size -= 100;
if (packet_size < min_packet_size)
packet_size = min_packet_size;
alt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(packet_size);
ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 1);
if (ret < 0)
pr_err("set alt 1 err %d\n", ret);
return ret;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x0000, 0x010c);
}
static void sd_stop0(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
if (!gspca_dev->present)
return;
switch (sd->model) {
case CIT_MODEL0:
/* HDG windows does this, but it causes the cams autogain to
restart from a gain of 0, which does not look good when
changing resolutions. */
/* cit_write_reg(gspca_dev, 0x0000, 0x0112); */
cit_write_reg(gspca_dev, 0x00c0, 0x0100); /* LED Off */
break;
case CIT_MODEL1:
cit_send_FF_04_02(gspca_dev);
cit_read_reg(gspca_dev, 0x0100, 0);
cit_write_reg(gspca_dev, 0x81, 0x0100); /* LED Off */
break;
case CIT_MODEL2:
v4l2_ctrl_grab(sd->lighting, false);
/* Fall through! */
case CIT_MODEL4:
cit_model2_Packet1(gspca_dev, 0x0030, 0x0004);
cit_write_reg(gspca_dev, 0x0080, 0x0100); /* LED Off */
cit_write_reg(gspca_dev, 0x0020, 0x0111);
cit_write_reg(gspca_dev, 0x00a0, 0x0111);
cit_model2_Packet1(gspca_dev, 0x0030, 0x0002);
cit_write_reg(gspca_dev, 0x0020, 0x0111);
cit_write_reg(gspca_dev, 0x0000, 0x0112);
break;
case CIT_MODEL3:
cit_write_reg(gspca_dev, 0x0006, 0x012c);
cit_model3_Packet1(gspca_dev, 0x0046, 0x0000);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x0064, 0x0116);
cit_read_reg(gspca_dev, 0x0115, 0);
cit_write_reg(gspca_dev, 0x0003, 0x0115);
cit_write_reg(gspca_dev, 0x0008, 0x0123);
cit_write_reg(gspca_dev, 0x0000, 0x0117);
cit_write_reg(gspca_dev, 0x0000, 0x0112);
cit_write_reg(gspca_dev, 0x0080, 0x0100);
break;
case CIT_IBM_NETCAM_PRO:
cit_model3_Packet1(gspca_dev, 0x0049, 0x00ff);
cit_write_reg(gspca_dev, 0x0006, 0x012c);
cit_write_reg(gspca_dev, 0x0000, 0x0116);
/* HDG windows does this, but I cannot get the camera
to restart with this without redoing the entire init
sequence which makes switching modes really slow */
/* cit_write_reg(gspca_dev, 0x0006, 0x0115); */
cit_write_reg(gspca_dev, 0x0008, 0x0123);
cit_write_reg(gspca_dev, 0x0000, 0x0117);
cit_write_reg(gspca_dev, 0x0003, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0111);
/* HDG windows does this, but I get a green picture when
restarting the stream after this */
/* cit_write_reg(gspca_dev, 0x0000, 0x0112); */
cit_write_reg(gspca_dev, 0x00c0, 0x0100);
break;
}
#if IS_ENABLED(CONFIG_INPUT)
/* If the last button state is pressed, release it now! */
if (sd->button_state) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
sd->button_state = 0;
}
#endif
}
static u8 *cit_find_sof(struct gspca_dev *gspca_dev, u8 *data, int len)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 byte3 = 0, byte4 = 0;
int i;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL1:
case CIT_MODEL3:
case CIT_IBM_NETCAM_PRO:
switch (gspca_dev->pixfmt.width) {
case 160: /* 160x120 */
byte3 = 0x02;
byte4 = 0x0a;
break;
case 176: /* 176x144 */
byte3 = 0x02;
byte4 = 0x0e;
break;
case 320: /* 320x240 */
byte3 = 0x02;
byte4 = 0x08;
break;
case 352: /* 352x288 */
byte3 = 0x02;
byte4 = 0x00;
break;
case 640:
byte3 = 0x03;
byte4 = 0x08;
break;
}
/* These have a different byte3 */
if (sd->model <= CIT_MODEL1)
byte3 = 0x00;
for (i = 0; i < len; i++) {
/* For this model the SOF always starts at offset 0
so no need to search the entire frame */
if (sd->model == CIT_MODEL0 && sd->sof_read != i)
break;
switch (sd->sof_read) {
case 0:
if (data[i] == 0x00)
sd->sof_read++;
break;
case 1:
if (data[i] == 0xff)
sd->sof_read++;
else if (data[i] == 0x00)
sd->sof_read = 1;
else
sd->sof_read = 0;
break;
case 2:
if (data[i] == byte3)
sd->sof_read++;
else if (data[i] == 0x00)
sd->sof_read = 1;
else
sd->sof_read = 0;
break;
case 3:
if (data[i] == byte4) {
sd->sof_read = 0;
return data + i + (sd->sof_len - 3);
}
if (byte3 == 0x00 && data[i] == 0xff)
sd->sof_read = 2;
else if (data[i] == 0x00)
sd->sof_read = 1;
else
sd->sof_read = 0;
break;
}
}
break;
case CIT_MODEL2:
case CIT_MODEL4:
/* TESTME we need to find a longer sof signature to avoid
false positives */
for (i = 0; i < len; i++) {
switch (sd->sof_read) {
case 0:
if (data[i] == 0x00)
sd->sof_read++;
break;
case 1:
sd->sof_read = 0;
if (data[i] == 0xff) {
if (i >= 4)
gspca_dbg(gspca_dev, D_FRAM,
"header found at offset: %d: %02x %02x 00 %3ph\n\n",
i - 1,
data[i - 4],
data[i - 3],
&data[i]);
else
gspca_dbg(gspca_dev, D_FRAM,
"header found at offset: %d: 00 %3ph\n\n",
i - 1,
&data[i]);
return data + i + (sd->sof_len - 1);
}
break;
}
}
break;
}
return NULL;
}
static void sd_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, int len)
{
struct sd *sd = (struct sd *) gspca_dev;
unsigned char *sof;
sof = cit_find_sof(gspca_dev, data, len);
if (sof) {
int n;
/* finish decoding current frame */
n = sof - data;
if (n > sd->sof_len)
n -= sd->sof_len;
else
n = 0;
gspca_frame_add(gspca_dev, LAST_PACKET,
data, n);
gspca_frame_add(gspca_dev, FIRST_PACKET, NULL, 0);
len -= sof - data;
data = sof;
}
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
#if IS_ENABLED(CONFIG_INPUT)
static void cit_check_button(struct gspca_dev *gspca_dev)
{
int new_button_state;
struct sd *sd = (struct sd *)gspca_dev;
switch (sd->model) {
case CIT_MODEL3:
case CIT_IBM_NETCAM_PRO:
break;
default: /* TEST ME unknown if this works on other models too */
return;
}
/* Read the button state */
cit_read_reg(gspca_dev, 0x0113, 0);
new_button_state = !gspca_dev->usb_buf[0];
/* Tell the cam we've seen the button press, notice that this
is a nop (iow the cam keeps reporting pressed) until the
button is actually released. */
if (new_button_state)
cit_write_reg(gspca_dev, 0x01, 0x0113);
if (sd->button_state != new_button_state) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA,
new_button_state);
input_sync(gspca_dev->input_dev);
sd->button_state = new_button_state;
}
}
#endif
static int sd_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct gspca_dev *gspca_dev =
container_of(ctrl->handler, struct gspca_dev, ctrl_handler);
struct sd *sd = (struct sd *)gspca_dev;
gspca_dev->usb_err = 0;
if (!gspca_dev->streaming)
return 0;
if (sd->stop_on_control_change)
sd_stopN(gspca_dev);
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
cit_set_brightness(gspca_dev, ctrl->val);
break;
case V4L2_CID_CONTRAST:
cit_set_contrast(gspca_dev, ctrl->val);
break;
case V4L2_CID_HUE:
cit_set_hue(gspca_dev, ctrl->val);
break;
case V4L2_CID_HFLIP:
cit_set_hflip(gspca_dev, ctrl->val);
break;
case V4L2_CID_SHARPNESS:
cit_set_sharpness(gspca_dev, ctrl->val);
break;
case V4L2_CID_BACKLIGHT_COMPENSATION:
cit_set_lighting(gspca_dev, ctrl->val);
break;
}
if (sd->stop_on_control_change)
cit_restart_stream(gspca_dev);
return gspca_dev->usb_err;
}
static const struct v4l2_ctrl_ops sd_ctrl_ops = {
.s_ctrl = sd_s_ctrl,
};
static int sd_init_controls(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *)gspca_dev;
struct v4l2_ctrl_handler *hdl = &gspca_dev->ctrl_handler;
bool has_brightness;
bool has_contrast;
bool has_hue;
bool has_sharpness;
bool has_lighting;
bool has_hflip;
has_brightness = has_contrast = has_hue =
has_sharpness = has_hflip = has_lighting = false;
switch (sd->model) {
case CIT_MODEL0:
has_contrast = has_hflip = true;
break;
case CIT_MODEL1:
has_brightness = has_contrast =
has_sharpness = has_lighting = true;
break;
case CIT_MODEL2:
has_brightness = has_hue = has_lighting = true;
break;
case CIT_MODEL3:
has_brightness = has_contrast = has_sharpness = true;
break;
case CIT_MODEL4:
has_brightness = has_hue = true;
break;
case CIT_IBM_NETCAM_PRO:
has_brightness = has_hue =
has_sharpness = has_hflip = has_lighting = true;
break;
}
gspca_dev->vdev.ctrl_handler = hdl;
v4l2_ctrl_handler_init(hdl, 5);
if (has_brightness)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_BRIGHTNESS, 0, 63, 1, 32);
if (has_contrast)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_CONTRAST, 0, 20, 1, 10);
if (has_hue)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_HUE, 0, 127, 1, 63);
if (has_sharpness)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_SHARPNESS, 0, 6, 1, 3);
if (has_lighting)
sd->lighting = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_BACKLIGHT_COMPENSATION, 0, 2, 1, 1);
if (has_hflip)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
if (hdl->error) {
pr_err("Could not initialize controls\n");
return hdl->error;
}
return 0;
}
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.init_controls = sd_init_controls,
.start = sd_start,
.stopN = sd_stopN,
.stop0 = sd_stop0,
.pkt_scan = sd_pkt_scan,
#if IS_ENABLED(CONFIG_INPUT)
.dq_callback = cit_check_button,
.other_input = 1,
#endif
};
static const struct sd_desc sd_desc_isoc_nego = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.init_controls = sd_init_controls,
.start = sd_start,
.isoc_init = sd_isoc_init,
.isoc_nego = sd_isoc_nego,
.stopN = sd_stopN,
.stop0 = sd_stop0,
.pkt_scan = sd_pkt_scan,
#if IS_ENABLED(CONFIG_INPUT)
.dq_callback = cit_check_button,
.other_input = 1,
#endif
};
/* -- module initialisation -- */
static const struct usb_device_id device_table[] = {
{ USB_DEVICE_VER(0x0545, 0x8080, 0x0001, 0x0001), .driver_info = CIT_MODEL0 },
{ USB_DEVICE_VER(0x0545, 0x8080, 0x0002, 0x0002), .driver_info = CIT_MODEL1 },
{ USB_DEVICE_VER(0x0545, 0x8080, 0x030a, 0x030a), .driver_info = CIT_MODEL2 },
{ USB_DEVICE_VER(0x0545, 0x8080, 0x0301, 0x0301), .driver_info = CIT_MODEL3 },
{ USB_DEVICE_VER(0x0545, 0x8002, 0x030a, 0x030a), .driver_info = CIT_MODEL4 },
{ USB_DEVICE_VER(0x0545, 0x800c, 0x030a, 0x030a), .driver_info = CIT_MODEL2 },
{ USB_DEVICE_VER(0x0545, 0x800d, 0x030a, 0x030a), .driver_info = CIT_MODEL4 },
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
const struct sd_desc *desc = &sd_desc;
switch (id->driver_info) {
case CIT_MODEL0:
case CIT_MODEL1:
if (intf->cur_altsetting->desc.bInterfaceNumber != 2)
return -ENODEV;
break;
case CIT_MODEL2:
case CIT_MODEL4:
if (intf->cur_altsetting->desc.bInterfaceNumber != 0)
return -ENODEV;
break;
case CIT_MODEL3:
if (intf->cur_altsetting->desc.bInterfaceNumber != 0)
return -ENODEV;
/* FIXME this likely applies to all model3 cams and probably
to other models too. */
if (ibm_netcam_pro)
desc = &sd_desc_isoc_nego;
break;
}
return gspca_dev_probe2(intf, id, desc, sizeof(struct sd), THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_3960_0 |
crossvul-cpp_data_bad_1275_2 | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used for analyzing expressions and
** for generating VDBE code that evaluates expressions in SQLite.
*/
#include "sqliteInt.h"
/* Forward declarations */
static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
/*
** Return the affinity character for a single column of a table.
*/
char sqlite3TableColumnAffinity(Table *pTab, int iCol){
assert( iCol<pTab->nCol );
return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
}
/*
** Return the 'affinity' of the expression pExpr if any.
**
** If pExpr is a column, a reference to a column via an 'AS' alias,
** or a sub-select with a column as the return value, then the
** affinity of that column is returned. Otherwise, 0x00 is returned,
** indicating no affinity for the expression.
**
** i.e. the WHERE clause expressions in the following statements all
** have an affinity:
**
** CREATE TABLE t1(a);
** SELECT * FROM t1 WHERE a;
** SELECT a AS b FROM t1 WHERE b;
** SELECT * FROM t1 WHERE (select a from t1);
*/
char sqlite3ExprAffinity(Expr *pExpr){
int op;
while( ExprHasProperty(pExpr, EP_Skip) ){
assert( pExpr->op==TK_COLLATE );
pExpr = pExpr->pLeft;
assert( pExpr!=0 );
}
op = pExpr->op;
if( op==TK_SELECT ){
assert( pExpr->flags&EP_xIsSelect );
return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
}
if( op==TK_REGISTER ) op = pExpr->op2;
#ifndef SQLITE_OMIT_CAST
if( op==TK_CAST ){
assert( !ExprHasProperty(pExpr, EP_IntValue) );
return sqlite3AffinityType(pExpr->u.zToken, 0);
}
#endif
if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
}
if( op==TK_SELECT_COLUMN ){
assert( pExpr->pLeft->flags&EP_xIsSelect );
return sqlite3ExprAffinity(
pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
);
}
if( op==TK_VECTOR ){
return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
}
return pExpr->affExpr;
}
/*
** Set the collating sequence for expression pExpr to be the collating
** sequence named by pToken. Return a pointer to a new Expr node that
** implements the COLLATE operator.
**
** If a memory allocation error occurs, that fact is recorded in pParse->db
** and the pExpr parameter is returned unchanged.
*/
Expr *sqlite3ExprAddCollateToken(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* Add the "COLLATE" clause to this expression */
const Token *pCollName, /* Name of collating sequence */
int dequote /* True to dequote pCollName */
){
if( pCollName->n>0 ){
Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
if( pNew ){
pNew->pLeft = pExpr;
pNew->flags |= EP_Collate|EP_Skip;
pExpr = pNew;
}
}
return pExpr;
}
Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
Token s;
assert( zC!=0 );
sqlite3TokenInit(&s, (char*)zC);
return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
}
/*
** Skip over any TK_COLLATE operators.
*/
Expr *sqlite3ExprSkipCollate(Expr *pExpr){
while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
assert( pExpr->op==TK_COLLATE );
pExpr = pExpr->pLeft;
}
return pExpr;
}
/*
** Skip over any TK_COLLATE operators and/or any unlikely()
** or likelihood() or likely() functions at the root of an
** expression.
*/
Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
if( ExprHasProperty(pExpr, EP_Unlikely) ){
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
assert( pExpr->x.pList->nExpr>0 );
assert( pExpr->op==TK_FUNCTION );
pExpr = pExpr->x.pList->a[0].pExpr;
}else{
assert( pExpr->op==TK_COLLATE );
pExpr = pExpr->pLeft;
}
}
return pExpr;
}
/*
** Return the collation sequence for the expression pExpr. If
** there is no defined collating sequence, return NULL.
**
** See also: sqlite3ExprNNCollSeq()
**
** The sqlite3ExprNNCollSeq() works the same exact that it returns the
** default collation if pExpr has no defined collation.
**
** The collating sequence might be determined by a COLLATE operator
** or by the presence of a column with a defined collating sequence.
** COLLATE operators take first precedence. Left operands take
** precedence over right operands.
*/
CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
sqlite3 *db = pParse->db;
CollSeq *pColl = 0;
Expr *p = pExpr;
while( p ){
int op = p->op;
if( op==TK_REGISTER ) op = p->op2;
if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
&& p->y.pTab!=0
){
/* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
** a TK_COLUMN but was previously evaluated and cached in a register */
int j = p->iColumn;
if( j>=0 ){
const char *zColl = p->y.pTab->aCol[j].zColl;
pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
}
break;
}
if( op==TK_CAST || op==TK_UPLUS ){
p = p->pLeft;
continue;
}
if( op==TK_VECTOR ){
p = p->x.pList->a[0].pExpr;
continue;
}
if( op==TK_COLLATE ){
pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
break;
}
if( p->flags & EP_Collate ){
if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
p = p->pLeft;
}else{
Expr *pNext = p->pRight;
/* The Expr.x union is never used at the same time as Expr.pRight */
assert( p->x.pList==0 || p->pRight==0 );
if( p->x.pList!=0
&& !db->mallocFailed
&& ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
){
int i;
for(i=0; i<p->x.pList->nExpr; i++){
if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
pNext = p->x.pList->a[i].pExpr;
break;
}
}
}
p = pNext;
}
}else{
break;
}
}
if( sqlite3CheckCollSeq(pParse, pColl) ){
pColl = 0;
}
return pColl;
}
/*
** Return the collation sequence for the expression pExpr. If
** there is no defined collating sequence, return a pointer to the
** defautl collation sequence.
**
** See also: sqlite3ExprCollSeq()
**
** The sqlite3ExprCollSeq() routine works the same except that it
** returns NULL if there is no defined collation.
*/
CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
if( p==0 ) p = pParse->db->pDfltColl;
assert( p!=0 );
return p;
}
/*
** Return TRUE if the two expressions have equivalent collating sequences.
*/
int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
}
/*
** pExpr is an operand of a comparison operator. aff2 is the
** type affinity of the other operand. This routine returns the
** type affinity that should be used for the comparison operator.
*/
char sqlite3CompareAffinity(Expr *pExpr, char aff2){
char aff1 = sqlite3ExprAffinity(pExpr);
if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
/* Both sides of the comparison are columns. If one has numeric
** affinity, use that. Otherwise use no affinity.
*/
if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
return SQLITE_AFF_NUMERIC;
}else{
return SQLITE_AFF_BLOB;
}
}else{
/* One side is a column, the other is not. Use the columns affinity. */
assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
}
}
/*
** pExpr is a comparison operator. Return the type affinity that should
** be applied to both operands prior to doing the comparison.
*/
static char comparisonAffinity(Expr *pExpr){
char aff;
assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
assert( pExpr->pLeft );
aff = sqlite3ExprAffinity(pExpr->pLeft);
if( pExpr->pRight ){
aff = sqlite3CompareAffinity(pExpr->pRight, aff);
}else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
}else if( aff==0 ){
aff = SQLITE_AFF_BLOB;
}
return aff;
}
/*
** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
** idx_affinity is the affinity of an indexed column. Return true
** if the index with affinity idx_affinity may be used to implement
** the comparison in pExpr.
*/
int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
char aff = comparisonAffinity(pExpr);
if( aff<SQLITE_AFF_TEXT ){
return 1;
}
if( aff==SQLITE_AFF_TEXT ){
return idx_affinity==SQLITE_AFF_TEXT;
}
return sqlite3IsNumericAffinity(idx_affinity);
}
/*
** Return the P5 value that should be used for a binary comparison
** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
*/
static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
u8 aff = (char)sqlite3ExprAffinity(pExpr2);
aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
return aff;
}
/*
** Return a pointer to the collation sequence that should be used by
** a binary comparison operator comparing pLeft and pRight.
**
** If the left hand expression has a collating sequence type, then it is
** used. Otherwise the collation sequence for the right hand expression
** is used, or the default (BINARY) if neither expression has a collating
** type.
**
** Argument pRight (but not pLeft) may be a null pointer. In this case,
** it is not considered.
*/
CollSeq *sqlite3BinaryCompareCollSeq(
Parse *pParse,
Expr *pLeft,
Expr *pRight
){
CollSeq *pColl;
assert( pLeft );
if( pLeft->flags & EP_Collate ){
pColl = sqlite3ExprCollSeq(pParse, pLeft);
}else if( pRight && (pRight->flags & EP_Collate)!=0 ){
pColl = sqlite3ExprCollSeq(pParse, pRight);
}else{
pColl = sqlite3ExprCollSeq(pParse, pLeft);
if( !pColl ){
pColl = sqlite3ExprCollSeq(pParse, pRight);
}
}
return pColl;
}
/* Expresssion p is a comparison operator. Return a collation sequence
** appropriate for the comparison operator.
**
** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
** However, if the OP_Commuted flag is set, then the order of the operands
** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
** correct collating sequence is found.
*/
CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, Expr *p){
if( ExprHasProperty(p, EP_Commuted) ){
return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
}else{
return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
}
}
/*
** Generate code for a comparison operator.
*/
static int codeCompare(
Parse *pParse, /* The parsing (and code generating) context */
Expr *pLeft, /* The left operand */
Expr *pRight, /* The right operand */
int opcode, /* The comparison opcode */
int in1, int in2, /* Register holding operands */
int dest, /* Jump here if true. */
int jumpIfNull, /* If true, jump if either operand is NULL */
int isCommuted /* The comparison has been commuted */
){
int p5;
int addr;
CollSeq *p4;
if( isCommuted ){
p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
}else{
p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
}
p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
(void*)p4, P4_COLLSEQ);
sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
return addr;
}
/*
** Return true if expression pExpr is a vector, or false otherwise.
**
** A vector is defined as any expression that results in two or more
** columns of result. Every TK_VECTOR node is an vector because the
** parser will not generate a TK_VECTOR with fewer than two entries.
** But a TK_SELECT might be either a vector or a scalar. It is only
** considered a vector if it has two or more result columns.
*/
int sqlite3ExprIsVector(Expr *pExpr){
return sqlite3ExprVectorSize(pExpr)>1;
}
/*
** If the expression passed as the only argument is of type TK_VECTOR
** return the number of expressions in the vector. Or, if the expression
** is a sub-select, return the number of columns in the sub-select. For
** any other type of expression, return 1.
*/
int sqlite3ExprVectorSize(Expr *pExpr){
u8 op = pExpr->op;
if( op==TK_REGISTER ) op = pExpr->op2;
if( op==TK_VECTOR ){
return pExpr->x.pList->nExpr;
}else if( op==TK_SELECT ){
return pExpr->x.pSelect->pEList->nExpr;
}else{
return 1;
}
}
/*
** Return a pointer to a subexpression of pVector that is the i-th
** column of the vector (numbered starting with 0). The caller must
** ensure that i is within range.
**
** If pVector is really a scalar (and "scalar" here includes subqueries
** that return a single column!) then return pVector unmodified.
**
** pVector retains ownership of the returned subexpression.
**
** If the vector is a (SELECT ...) then the expression returned is
** just the expression for the i-th term of the result set, and may
** not be ready for evaluation because the table cursor has not yet
** been positioned.
*/
Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
assert( i<sqlite3ExprVectorSize(pVector) );
if( sqlite3ExprIsVector(pVector) ){
assert( pVector->op2==0 || pVector->op==TK_REGISTER );
if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
return pVector->x.pSelect->pEList->a[i].pExpr;
}else{
return pVector->x.pList->a[i].pExpr;
}
}
return pVector;
}
/*
** Compute and return a new Expr object which when passed to
** sqlite3ExprCode() will generate all necessary code to compute
** the iField-th column of the vector expression pVector.
**
** It is ok for pVector to be a scalar (as long as iField==0).
** In that case, this routine works like sqlite3ExprDup().
**
** The caller owns the returned Expr object and is responsible for
** ensuring that the returned value eventually gets freed.
**
** The caller retains ownership of pVector. If pVector is a TK_SELECT,
** then the returned object will reference pVector and so pVector must remain
** valid for the life of the returned object. If pVector is a TK_VECTOR
** or a scalar expression, then it can be deleted as soon as this routine
** returns.
**
** A trick to cause a TK_SELECT pVector to be deleted together with
** the returned Expr object is to attach the pVector to the pRight field
** of the returned TK_SELECT_COLUMN Expr object.
*/
Expr *sqlite3ExprForVectorField(
Parse *pParse, /* Parsing context */
Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
int iField /* Which column of the vector to return */
){
Expr *pRet;
if( pVector->op==TK_SELECT ){
assert( pVector->flags & EP_xIsSelect );
/* The TK_SELECT_COLUMN Expr node:
**
** pLeft: pVector containing TK_SELECT. Not deleted.
** pRight: not used. But recursively deleted.
** iColumn: Index of a column in pVector
** iTable: 0 or the number of columns on the LHS of an assignment
** pLeft->iTable: First in an array of register holding result, or 0
** if the result is not yet computed.
**
** sqlite3ExprDelete() specifically skips the recursive delete of
** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
** can be attached to pRight to cause this node to take ownership of
** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
** with the same pLeft pointer to the pVector, but only one of them
** will own the pVector.
*/
pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
if( pRet ){
pRet->iColumn = iField;
pRet->pLeft = pVector;
}
assert( pRet==0 || pRet->iTable==0 );
}else{
if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
pRet = sqlite3ExprDup(pParse->db, pVector, 0);
sqlite3RenameTokenRemap(pParse, pRet, pVector);
}
return pRet;
}
/*
** If expression pExpr is of type TK_SELECT, generate code to evaluate
** it. Return the register in which the result is stored (or, if the
** sub-select returns more than one column, the first in an array
** of registers in which the result is stored).
**
** If pExpr is not a TK_SELECT expression, return 0.
*/
static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
int reg = 0;
#ifndef SQLITE_OMIT_SUBQUERY
if( pExpr->op==TK_SELECT ){
reg = sqlite3CodeSubselect(pParse, pExpr);
}
#endif
return reg;
}
/*
** Argument pVector points to a vector expression - either a TK_VECTOR
** or TK_SELECT that returns more than one column. This function returns
** the register number of a register that contains the value of
** element iField of the vector.
**
** If pVector is a TK_SELECT expression, then code for it must have
** already been generated using the exprCodeSubselect() routine. In this
** case parameter regSelect should be the first in an array of registers
** containing the results of the sub-select.
**
** If pVector is of type TK_VECTOR, then code for the requested field
** is generated. In this case (*pRegFree) may be set to the number of
** a temporary register to be freed by the caller before returning.
**
** Before returning, output parameter (*ppExpr) is set to point to the
** Expr object corresponding to element iElem of the vector.
*/
static int exprVectorRegister(
Parse *pParse, /* Parse context */
Expr *pVector, /* Vector to extract element from */
int iField, /* Field to extract from pVector */
int regSelect, /* First in array of registers */
Expr **ppExpr, /* OUT: Expression element */
int *pRegFree /* OUT: Temp register to free */
){
u8 op = pVector->op;
assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
if( op==TK_REGISTER ){
*ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
return pVector->iTable+iField;
}
if( op==TK_SELECT ){
*ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
return regSelect+iField;
}
*ppExpr = pVector->x.pList->a[iField].pExpr;
return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
}
/*
** Expression pExpr is a comparison between two vector values. Compute
** the result of the comparison (1, 0, or NULL) and write that
** result into register dest.
**
** The caller must satisfy the following preconditions:
**
** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
** otherwise: op==pExpr->op and p5==0
*/
static void codeVectorCompare(
Parse *pParse, /* Code generator context */
Expr *pExpr, /* The comparison operation */
int dest, /* Write results into this register */
u8 op, /* Comparison operator */
u8 p5 /* SQLITE_NULLEQ or zero */
){
Vdbe *v = pParse->pVdbe;
Expr *pLeft = pExpr->pLeft;
Expr *pRight = pExpr->pRight;
int nLeft = sqlite3ExprVectorSize(pLeft);
int i;
int regLeft = 0;
int regRight = 0;
u8 opx = op;
int addrDone = sqlite3VdbeMakeLabel(pParse);
int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
if( nLeft!=sqlite3ExprVectorSize(pRight) ){
sqlite3ErrorMsg(pParse, "row value misused");
return;
}
assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
|| pExpr->op==TK_IS || pExpr->op==TK_ISNOT
|| pExpr->op==TK_LT || pExpr->op==TK_GT
|| pExpr->op==TK_LE || pExpr->op==TK_GE
);
assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
|| (pExpr->op==TK_ISNOT && op==TK_NE) );
assert( p5==0 || pExpr->op!=op );
assert( p5==SQLITE_NULLEQ || pExpr->op==op );
p5 |= SQLITE_STOREP2;
if( opx==TK_LE ) opx = TK_LT;
if( opx==TK_GE ) opx = TK_GT;
regLeft = exprCodeSubselect(pParse, pLeft);
regRight = exprCodeSubselect(pParse, pRight);
for(i=0; 1 /*Loop exits by "break"*/; i++){
int regFree1 = 0, regFree2 = 0;
Expr *pL, *pR;
int r1, r2;
assert( i>=0 && i<nLeft );
r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, ®Free1);
r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, ®Free2);
codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
if( i==nLeft-1 ){
break;
}
if( opx==TK_EQ ){
sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
p5 |= SQLITE_KEEPNULL;
}else if( opx==TK_NE ){
sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
p5 |= SQLITE_KEEPNULL;
}else{
assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
VdbeCoverageIf(v, op==TK_LT);
VdbeCoverageIf(v, op==TK_GT);
VdbeCoverageIf(v, op==TK_LE);
VdbeCoverageIf(v, op==TK_GE);
if( i==nLeft-2 ) opx = op;
}
}
sqlite3VdbeResolveLabel(v, addrDone);
}
#if SQLITE_MAX_EXPR_DEPTH>0
/*
** Check that argument nHeight is less than or equal to the maximum
** expression depth allowed. If it is not, leave an error message in
** pParse.
*/
int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
int rc = SQLITE_OK;
int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
if( nHeight>mxHeight ){
sqlite3ErrorMsg(pParse,
"Expression tree is too large (maximum depth %d)", mxHeight
);
rc = SQLITE_ERROR;
}
return rc;
}
/* The following three functions, heightOfExpr(), heightOfExprList()
** and heightOfSelect(), are used to determine the maximum height
** of any expression tree referenced by the structure passed as the
** first argument.
**
** If this maximum height is greater than the current value pointed
** to by pnHeight, the second parameter, then set *pnHeight to that
** value.
*/
static void heightOfExpr(Expr *p, int *pnHeight){
if( p ){
if( p->nHeight>*pnHeight ){
*pnHeight = p->nHeight;
}
}
}
static void heightOfExprList(ExprList *p, int *pnHeight){
if( p ){
int i;
for(i=0; i<p->nExpr; i++){
heightOfExpr(p->a[i].pExpr, pnHeight);
}
}
}
static void heightOfSelect(Select *pSelect, int *pnHeight){
Select *p;
for(p=pSelect; p; p=p->pPrior){
heightOfExpr(p->pWhere, pnHeight);
heightOfExpr(p->pHaving, pnHeight);
heightOfExpr(p->pLimit, pnHeight);
heightOfExprList(p->pEList, pnHeight);
heightOfExprList(p->pGroupBy, pnHeight);
heightOfExprList(p->pOrderBy, pnHeight);
}
}
/*
** Set the Expr.nHeight variable in the structure passed as an
** argument. An expression with no children, Expr.pList or
** Expr.pSelect member has a height of 1. Any other expression
** has a height equal to the maximum height of any other
** referenced Expr plus one.
**
** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
** if appropriate.
*/
static void exprSetHeight(Expr *p){
int nHeight = 0;
heightOfExpr(p->pLeft, &nHeight);
heightOfExpr(p->pRight, &nHeight);
if( ExprHasProperty(p, EP_xIsSelect) ){
heightOfSelect(p->x.pSelect, &nHeight);
}else if( p->x.pList ){
heightOfExprList(p->x.pList, &nHeight);
p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
}
p->nHeight = nHeight + 1;
}
/*
** Set the Expr.nHeight variable using the exprSetHeight() function. If
** the height is greater than the maximum allowed expression depth,
** leave an error in pParse.
**
** Also propagate all EP_Propagate flags from the Expr.x.pList into
** Expr.flags.
*/
void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
if( pParse->nErr ) return;
exprSetHeight(p);
sqlite3ExprCheckHeight(pParse, p->nHeight);
}
/*
** Return the maximum height of any expression tree referenced
** by the select statement passed as an argument.
*/
int sqlite3SelectExprHeight(Select *p){
int nHeight = 0;
heightOfSelect(p, &nHeight);
return nHeight;
}
#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
/*
** Propagate all EP_Propagate flags from the Expr.x.pList into
** Expr.flags.
*/
void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
}
}
#define exprSetHeight(y)
#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
/*
** This routine is the core allocator for Expr nodes.
**
** Construct a new expression node and return a pointer to it. Memory
** for this node and for the pToken argument is a single allocation
** obtained from sqlite3DbMalloc(). The calling function
** is responsible for making sure the node eventually gets freed.
**
** If dequote is true, then the token (if it exists) is dequoted.
** If dequote is false, no dequoting is performed. The deQuote
** parameter is ignored if pToken is NULL or if the token does not
** appear to be quoted. If the quotes were of the form "..." (double-quotes)
** then the EP_DblQuoted flag is set on the expression node.
**
** Special case: If op==TK_INTEGER and pToken points to a string that
** can be translated into a 32-bit integer, then the token is not
** stored in u.zToken. Instead, the integer values is written
** into u.iValue and the EP_IntValue flag is set. No extra storage
** is allocated to hold the integer text and the dequote flag is ignored.
*/
Expr *sqlite3ExprAlloc(
sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
int op, /* Expression opcode */
const Token *pToken, /* Token argument. Might be NULL */
int dequote /* True to dequote */
){
Expr *pNew;
int nExtra = 0;
int iValue = 0;
assert( db!=0 );
if( pToken ){
if( op!=TK_INTEGER || pToken->z==0
|| sqlite3GetInt32(pToken->z, &iValue)==0 ){
nExtra = pToken->n+1;
assert( iValue>=0 );
}
}
pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
if( pNew ){
memset(pNew, 0, sizeof(Expr));
pNew->op = (u8)op;
pNew->iAgg = -1;
if( pToken ){
if( nExtra==0 ){
pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
pNew->u.iValue = iValue;
}else{
pNew->u.zToken = (char*)&pNew[1];
assert( pToken->z!=0 || pToken->n==0 );
if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
pNew->u.zToken[pToken->n] = 0;
if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
sqlite3DequoteExpr(pNew);
}
}
}
#if SQLITE_MAX_EXPR_DEPTH>0
pNew->nHeight = 1;
#endif
}
return pNew;
}
/*
** Allocate a new expression node from a zero-terminated token that has
** already been dequoted.
*/
Expr *sqlite3Expr(
sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
int op, /* Expression opcode */
const char *zToken /* Token argument. Might be NULL */
){
Token x;
x.z = zToken;
x.n = sqlite3Strlen30(zToken);
return sqlite3ExprAlloc(db, op, &x, 0);
}
/*
** Attach subtrees pLeft and pRight to the Expr node pRoot.
**
** If pRoot==NULL that means that a memory allocation error has occurred.
** In that case, delete the subtrees pLeft and pRight.
*/
void sqlite3ExprAttachSubtrees(
sqlite3 *db,
Expr *pRoot,
Expr *pLeft,
Expr *pRight
){
if( pRoot==0 ){
assert( db->mallocFailed );
sqlite3ExprDelete(db, pLeft);
sqlite3ExprDelete(db, pRight);
}else{
if( pRight ){
pRoot->pRight = pRight;
pRoot->flags |= EP_Propagate & pRight->flags;
}
if( pLeft ){
pRoot->pLeft = pLeft;
pRoot->flags |= EP_Propagate & pLeft->flags;
}
exprSetHeight(pRoot);
}
}
/*
** Allocate an Expr node which joins as many as two subtrees.
**
** One or both of the subtrees can be NULL. Return a pointer to the new
** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
** free the subtrees and return NULL.
*/
Expr *sqlite3PExpr(
Parse *pParse, /* Parsing context */
int op, /* Expression opcode */
Expr *pLeft, /* Left operand */
Expr *pRight /* Right operand */
){
Expr *p;
p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
if( p ){
memset(p, 0, sizeof(Expr));
p->op = op & 0xff;
p->iAgg = -1;
sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
sqlite3ExprCheckHeight(pParse, p->nHeight);
}else{
sqlite3ExprDelete(pParse->db, pLeft);
sqlite3ExprDelete(pParse->db, pRight);
}
return p;
}
/*
** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
** do a memory allocation failure) then delete the pSelect object.
*/
void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
if( pExpr ){
pExpr->x.pSelect = pSelect;
ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
sqlite3ExprSetHeightAndFlags(pParse, pExpr);
}else{
assert( pParse->db->mallocFailed );
sqlite3SelectDelete(pParse->db, pSelect);
}
}
/*
** Join two expressions using an AND operator. If either expression is
** NULL, then just return the other expression.
**
** If one side or the other of the AND is known to be false, then instead
** of returning an AND expression, just return a constant expression with
** a value of false.
*/
Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
sqlite3 *db = pParse->db;
if( pLeft==0 ){
return pRight;
}else if( pRight==0 ){
return pLeft;
}else if( ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight) ){
sqlite3ExprUnmapAndDelete(pParse, pLeft);
sqlite3ExprUnmapAndDelete(pParse, pRight);
return sqlite3Expr(db, TK_INTEGER, "0");
}else{
return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
}
}
/*
** Construct a new expression node for a function with multiple
** arguments.
*/
Expr *sqlite3ExprFunction(
Parse *pParse, /* Parsing context */
ExprList *pList, /* Argument list */
Token *pToken, /* Name of the function */
int eDistinct /* SF_Distinct or SF_ALL or 0 */
){
Expr *pNew;
sqlite3 *db = pParse->db;
assert( pToken );
pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
if( pNew==0 ){
sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
return 0;
}
if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
}
pNew->x.pList = pList;
ExprSetProperty(pNew, EP_HasFunc);
assert( !ExprHasProperty(pNew, EP_xIsSelect) );
sqlite3ExprSetHeightAndFlags(pParse, pNew);
if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
return pNew;
}
/*
** Assign a variable number to an expression that encodes a wildcard
** in the original SQL statement.
**
** Wildcards consisting of a single "?" are assigned the next sequential
** variable number.
**
** Wildcards of the form "?nnn" are assigned the number "nnn". We make
** sure "nnn" is not too big to avoid a denial of service attack when
** the SQL statement comes from an external source.
**
** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
** as the previous instance of the same wildcard. Or if this is the first
** instance of the wildcard, the next sequential variable number is
** assigned.
*/
void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
sqlite3 *db = pParse->db;
const char *z;
ynVar x;
if( pExpr==0 ) return;
assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
z = pExpr->u.zToken;
assert( z!=0 );
assert( z[0]!=0 );
assert( n==(u32)sqlite3Strlen30(z) );
if( z[1]==0 ){
/* Wildcard of the form "?". Assign the next variable number */
assert( z[0]=='?' );
x = (ynVar)(++pParse->nVar);
}else{
int doAdd = 0;
if( z[0]=='?' ){
/* Wildcard of the form "?nnn". Convert "nnn" to an integer and
** use it as the variable number */
i64 i;
int bOk;
if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
i = z[1]-'0'; /* The common case of ?N for a single digit N */
bOk = 1;
}else{
bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
}
testcase( i==0 );
testcase( i==1 );
testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
return;
}
x = (ynVar)i;
if( x>pParse->nVar ){
pParse->nVar = (int)x;
doAdd = 1;
}else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
doAdd = 1;
}
}else{
/* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
** number as the prior appearance of the same name, or if the name
** has never appeared before, reuse the same variable number
*/
x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
if( x==0 ){
x = (ynVar)(++pParse->nVar);
doAdd = 1;
}
}
if( doAdd ){
pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
}
}
pExpr->iColumn = x;
if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
sqlite3ErrorMsg(pParse, "too many SQL variables");
}
}
/*
** Recursively delete an expression tree.
*/
static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
assert( p!=0 );
/* Sanity check: Assert that the IntValue is non-negative if it exists */
assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
|| p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
#ifdef SQLITE_DEBUG
if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
assert( p->pLeft==0 );
assert( p->pRight==0 );
assert( p->x.pSelect==0 );
}
#endif
if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
/* The Expr.x union is never used at the same time as Expr.pRight */
assert( p->x.pList==0 || p->pRight==0 );
if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
if( p->pRight ){
assert( !ExprHasProperty(p, EP_WinFunc) );
sqlite3ExprDeleteNN(db, p->pRight);
}else if( ExprHasProperty(p, EP_xIsSelect) ){
assert( !ExprHasProperty(p, EP_WinFunc) );
sqlite3SelectDelete(db, p->x.pSelect);
}else{
sqlite3ExprListDelete(db, p->x.pList);
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(p, EP_WinFunc) ){
sqlite3WindowDelete(db, p->y.pWin);
}
#endif
}
}
if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
if( !ExprHasProperty(p, EP_Static) ){
sqlite3DbFreeNN(db, p);
}
}
void sqlite3ExprDelete(sqlite3 *db, Expr *p){
if( p ) sqlite3ExprDeleteNN(db, p);
}
/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
** expression.
*/
void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
if( p ){
if( IN_RENAME_OBJECT ){
sqlite3RenameExprUnmap(pParse, p);
}
sqlite3ExprDeleteNN(pParse->db, p);
}
}
/*
** Return the number of bytes allocated for the expression structure
** passed as the first argument. This is always one of EXPR_FULLSIZE,
** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
*/
static int exprStructSize(Expr *p){
if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
return EXPR_FULLSIZE;
}
/*
** The dupedExpr*Size() routines each return the number of bytes required
** to store a copy of an expression or expression tree. They differ in
** how much of the tree is measured.
**
** dupedExprStructSize() Size of only the Expr structure
** dupedExprNodeSize() Size of Expr + space for token
** dupedExprSize() Expr + token + subtree components
**
***************************************************************************
**
** The dupedExprStructSize() function returns two values OR-ed together:
** (1) the space required for a copy of the Expr structure only and
** (2) the EP_xxx flags that indicate what the structure size should be.
** The return values is always one of:
**
** EXPR_FULLSIZE
** EXPR_REDUCEDSIZE | EP_Reduced
** EXPR_TOKENONLYSIZE | EP_TokenOnly
**
** The size of the structure can be found by masking the return value
** of this routine with 0xfff. The flags can be found by masking the
** return value with EP_Reduced|EP_TokenOnly.
**
** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
** (unreduced) Expr objects as they or originally constructed by the parser.
** During expression analysis, extra information is computed and moved into
** later parts of the Expr object and that extra information might get chopped
** off if the expression is reduced. Note also that it does not work to
** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
** to reduce a pristine expression tree from the parser. The implementation
** of dupedExprStructSize() contain multiple assert() statements that attempt
** to enforce this constraint.
*/
static int dupedExprStructSize(Expr *p, int flags){
int nSize;
assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
assert( EXPR_FULLSIZE<=0xfff );
assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
if( 0==flags || p->op==TK_SELECT_COLUMN
#ifndef SQLITE_OMIT_WINDOWFUNC
|| ExprHasProperty(p, EP_WinFunc)
#endif
){
nSize = EXPR_FULLSIZE;
}else{
assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
assert( !ExprHasProperty(p, EP_FromJoin) );
assert( !ExprHasProperty(p, EP_MemToken) );
assert( !ExprHasProperty(p, EP_NoReduce) );
if( p->pLeft || p->x.pList ){
nSize = EXPR_REDUCEDSIZE | EP_Reduced;
}else{
assert( p->pRight==0 );
nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
}
}
return nSize;
}
/*
** This function returns the space in bytes required to store the copy
** of the Expr structure and a copy of the Expr.u.zToken string (if that
** string is defined.)
*/
static int dupedExprNodeSize(Expr *p, int flags){
int nByte = dupedExprStructSize(p, flags) & 0xfff;
if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
nByte += sqlite3Strlen30NN(p->u.zToken)+1;
}
return ROUND8(nByte);
}
/*
** Return the number of bytes required to create a duplicate of the
** expression passed as the first argument. The second argument is a
** mask containing EXPRDUP_XXX flags.
**
** The value returned includes space to create a copy of the Expr struct
** itself and the buffer referred to by Expr.u.zToken, if any.
**
** If the EXPRDUP_REDUCE flag is set, then the return value includes
** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
** and Expr.pRight variables (but not for any structures pointed to or
** descended from the Expr.x.pList or Expr.x.pSelect variables).
*/
static int dupedExprSize(Expr *p, int flags){
int nByte = 0;
if( p ){
nByte = dupedExprNodeSize(p, flags);
if( flags&EXPRDUP_REDUCE ){
nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
}
}
return nByte;
}
/*
** This function is similar to sqlite3ExprDup(), except that if pzBuffer
** is not NULL then *pzBuffer is assumed to point to a buffer large enough
** to store the copy of expression p, the copies of p->u.zToken
** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
** if any. Before returning, *pzBuffer is set to the first byte past the
** portion of the buffer copied into by this function.
*/
static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
Expr *pNew; /* Value to return */
u8 *zAlloc; /* Memory space from which to build Expr object */
u32 staticFlag; /* EP_Static if space not obtained from malloc */
assert( db!=0 );
assert( p );
assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
/* Figure out where to write the new Expr structure. */
if( pzBuffer ){
zAlloc = *pzBuffer;
staticFlag = EP_Static;
}else{
zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
staticFlag = 0;
}
pNew = (Expr *)zAlloc;
if( pNew ){
/* Set nNewSize to the size allocated for the structure pointed to
** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
** by the copy of the p->u.zToken string (if any).
*/
const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
const int nNewSize = nStructSize & 0xfff;
int nToken;
if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
nToken = sqlite3Strlen30(p->u.zToken) + 1;
}else{
nToken = 0;
}
if( dupFlags ){
assert( ExprHasProperty(p, EP_Reduced)==0 );
memcpy(zAlloc, p, nNewSize);
}else{
u32 nSize = (u32)exprStructSize(p);
memcpy(zAlloc, p, nSize);
if( nSize<EXPR_FULLSIZE ){
memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
}
}
/* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
pNew->flags |= staticFlag;
/* Copy the p->u.zToken string, if any. */
if( nToken ){
char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
memcpy(zToken, p->u.zToken, nToken);
}
if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
/* Fill in the pNew->x.pSelect or pNew->x.pList member. */
if( ExprHasProperty(p, EP_xIsSelect) ){
pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
}else{
pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
}
}
/* Fill in pNew->pLeft and pNew->pRight. */
if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
zAlloc += dupedExprNodeSize(p, dupFlags);
if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
pNew->pLeft = p->pLeft ?
exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
pNew->pRight = p->pRight ?
exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
}
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(p, EP_WinFunc) ){
pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
assert( ExprHasProperty(pNew, EP_WinFunc) );
}
#endif /* SQLITE_OMIT_WINDOWFUNC */
if( pzBuffer ){
*pzBuffer = zAlloc;
}
}else{
if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
if( pNew->op==TK_SELECT_COLUMN ){
pNew->pLeft = p->pLeft;
assert( p->iColumn==0 || p->pRight==0 );
assert( p->pRight==0 || p->pRight==p->pLeft );
}else{
pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
}
pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
}
}
}
return pNew;
}
/*
** Create and return a deep copy of the object passed as the second
** argument. If an OOM condition is encountered, NULL is returned
** and the db->mallocFailed flag set.
*/
#ifndef SQLITE_OMIT_CTE
static With *withDup(sqlite3 *db, With *p){
With *pRet = 0;
if( p ){
sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
pRet = sqlite3DbMallocZero(db, nByte);
if( pRet ){
int i;
pRet->nCte = p->nCte;
for(i=0; i<p->nCte; i++){
pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
}
}
}
return pRet;
}
#else
# define withDup(x,y) 0
#endif
#ifndef SQLITE_OMIT_WINDOWFUNC
/*
** The gatherSelectWindows() procedure and its helper routine
** gatherSelectWindowsCallback() are used to scan all the expressions
** an a newly duplicated SELECT statement and gather all of the Window
** objects found there, assembling them onto the linked list at Select->pWin.
*/
static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
Select *pSelect = pWalker->u.pSelect;
Window *pWin = pExpr->y.pWin;
assert( pWin );
assert( IsWindowFunc(pExpr) );
assert( pWin->ppThis==0 );
sqlite3WindowLink(pSelect, pWin);
}
return WRC_Continue;
}
static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
}
static void gatherSelectWindows(Select *p){
Walker w;
w.xExprCallback = gatherSelectWindowsCallback;
w.xSelectCallback = gatherSelectWindowsSelectCallback;
w.xSelectCallback2 = 0;
w.pParse = 0;
w.u.pSelect = p;
sqlite3WalkSelect(&w, p);
}
#endif
/*
** The following group of routines make deep copies of expressions,
** expression lists, ID lists, and select statements. The copies can
** be deleted (by being passed to their respective ...Delete() routines)
** without effecting the originals.
**
** The expression list, ID, and source lists return by sqlite3ExprListDup(),
** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
** by subsequent calls to sqlite*ListAppend() routines.
**
** Any tables that the SrcList might point to are not duplicated.
**
** The flags parameter contains a combination of the EXPRDUP_XXX flags.
** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
** truncated version of the usual Expr structure that will be stored as
** part of the in-memory representation of the database schema.
*/
Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
assert( flags==0 || flags==EXPRDUP_REDUCE );
return p ? exprDup(db, p, flags, 0) : 0;
}
ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
ExprList *pNew;
struct ExprList_item *pItem, *pOldItem;
int i;
Expr *pPriorSelectCol = 0;
assert( db!=0 );
if( p==0 ) return 0;
pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
if( pNew==0 ) return 0;
pNew->nExpr = p->nExpr;
pItem = pNew->a;
pOldItem = p->a;
for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
Expr *pOldExpr = pOldItem->pExpr;
Expr *pNewExpr;
pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
if( pOldExpr
&& pOldExpr->op==TK_SELECT_COLUMN
&& (pNewExpr = pItem->pExpr)!=0
){
assert( pNewExpr->iColumn==0 || i>0 );
if( pNewExpr->iColumn==0 ){
assert( pOldExpr->pLeft==pOldExpr->pRight );
pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
}else{
assert( i>0 );
assert( pItem[-1].pExpr!=0 );
assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
pNewExpr->pLeft = pPriorSelectCol;
}
}
pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
pItem->sortFlags = pOldItem->sortFlags;
pItem->done = 0;
pItem->bNulls = pOldItem->bNulls;
pItem->bSpanIsTab = pOldItem->bSpanIsTab;
pItem->bSorterRef = pOldItem->bSorterRef;
pItem->u = pOldItem->u;
}
return pNew;
}
/*
** If cursors, triggers, views and subqueries are all omitted from
** the build, then none of the following routines, except for
** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
** called with a NULL argument.
*/
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
|| !defined(SQLITE_OMIT_SUBQUERY)
SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
SrcList *pNew;
int i;
int nByte;
assert( db!=0 );
if( p==0 ) return 0;
nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
pNew = sqlite3DbMallocRawNN(db, nByte );
if( pNew==0 ) return 0;
pNew->nSrc = pNew->nAlloc = p->nSrc;
for(i=0; i<p->nSrc; i++){
struct SrcList_item *pNewItem = &pNew->a[i];
struct SrcList_item *pOldItem = &p->a[i];
Table *pTab;
pNewItem->pSchema = pOldItem->pSchema;
pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
pNewItem->fg = pOldItem->fg;
pNewItem->iCursor = pOldItem->iCursor;
pNewItem->addrFillSub = pOldItem->addrFillSub;
pNewItem->regReturn = pOldItem->regReturn;
if( pNewItem->fg.isIndexedBy ){
pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
}
pNewItem->pIBIndex = pOldItem->pIBIndex;
if( pNewItem->fg.isTabFunc ){
pNewItem->u1.pFuncArg =
sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
}
pTab = pNewItem->pTab = pOldItem->pTab;
if( pTab ){
pTab->nTabRef++;
}
pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
pNewItem->colUsed = pOldItem->colUsed;
}
return pNew;
}
IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
IdList *pNew;
int i;
assert( db!=0 );
if( p==0 ) return 0;
pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
if( pNew==0 ) return 0;
pNew->nId = p->nId;
pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
if( pNew->a==0 ){
sqlite3DbFreeNN(db, pNew);
return 0;
}
/* Note that because the size of the allocation for p->a[] is not
** necessarily a power of two, sqlite3IdListAppend() may not be called
** on the duplicate created by this function. */
for(i=0; i<p->nId; i++){
struct IdList_item *pNewItem = &pNew->a[i];
struct IdList_item *pOldItem = &p->a[i];
pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
pNewItem->idx = pOldItem->idx;
}
return pNew;
}
Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
Select *pRet = 0;
Select *pNext = 0;
Select **pp = &pRet;
Select *p;
assert( db!=0 );
for(p=pDup; p; p=p->pPrior){
Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
if( pNew==0 ) break;
pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
pNew->op = p->op;
pNew->pNext = pNext;
pNew->pPrior = 0;
pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
pNew->iLimit = 0;
pNew->iOffset = 0;
pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
pNew->addrOpenEphm[0] = -1;
pNew->addrOpenEphm[1] = -1;
pNew->nSelectRow = p->nSelectRow;
pNew->pWith = withDup(db, p->pWith);
#ifndef SQLITE_OMIT_WINDOWFUNC
pNew->pWin = 0;
pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
#endif
pNew->selId = p->selId;
*pp = pNew;
pp = &pNew->pPrior;
pNext = pNew;
}
return pRet;
}
#else
Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
assert( p==0 );
return 0;
}
#endif
/*
** Add a new element to the end of an expression list. If pList is
** initially NULL, then create a new expression list.
**
** The pList argument must be either NULL or a pointer to an ExprList
** obtained from a prior call to sqlite3ExprListAppend(). This routine
** may not be used with an ExprList obtained from sqlite3ExprListDup().
** Reason: This routine assumes that the number of slots in pList->a[]
** is a power of two. That is true for sqlite3ExprListAppend() returns
** but is not necessarily true from the return value of sqlite3ExprListDup().
**
** If a memory allocation error occurs, the entire list is freed and
** NULL is returned. If non-NULL is returned, then it is guaranteed
** that the new entry was successfully appended.
*/
ExprList *sqlite3ExprListAppend(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
Expr *pExpr /* Expression to be appended. Might be NULL */
){
struct ExprList_item *pItem;
sqlite3 *db = pParse->db;
assert( db!=0 );
if( pList==0 ){
pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
if( pList==0 ){
goto no_mem;
}
pList->nExpr = 0;
}else if( (pList->nExpr & (pList->nExpr-1))==0 ){
ExprList *pNew;
pNew = sqlite3DbRealloc(db, pList,
sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
if( pNew==0 ){
goto no_mem;
}
pList = pNew;
}
pItem = &pList->a[pList->nExpr++];
assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
assert( offsetof(struct ExprList_item,pExpr)==0 );
memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
pItem->pExpr = pExpr;
return pList;
no_mem:
/* Avoid leaking memory if malloc has failed. */
sqlite3ExprDelete(db, pExpr);
sqlite3ExprListDelete(db, pList);
return 0;
}
/*
** pColumns and pExpr form a vector assignment which is part of the SET
** clause of an UPDATE statement. Like this:
**
** (a,b,c) = (expr1,expr2,expr3)
** Or: (a,b,c) = (SELECT x,y,z FROM ....)
**
** For each term of the vector assignment, append new entries to the
** expression list pList. In the case of a subquery on the RHS, append
** TK_SELECT_COLUMN expressions.
*/
ExprList *sqlite3ExprListAppendVector(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
IdList *pColumns, /* List of names of LHS of the assignment */
Expr *pExpr /* Vector expression to be appended. Might be NULL */
){
sqlite3 *db = pParse->db;
int n;
int i;
int iFirst = pList ? pList->nExpr : 0;
/* pColumns can only be NULL due to an OOM but an OOM will cause an
** exit prior to this routine being invoked */
if( NEVER(pColumns==0) ) goto vector_append_error;
if( pExpr==0 ) goto vector_append_error;
/* If the RHS is a vector, then we can immediately check to see that
** the size of the RHS and LHS match. But if the RHS is a SELECT,
** wildcards ("*") in the result set of the SELECT must be expanded before
** we can do the size check, so defer the size check until code generation.
*/
if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
pColumns->nId, n);
goto vector_append_error;
}
for(i=0; i<pColumns->nId; i++){
Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
assert( pSubExpr!=0 || db->mallocFailed );
assert( pSubExpr==0 || pSubExpr->iTable==0 );
if( pSubExpr==0 ) continue;
pSubExpr->iTable = pColumns->nId;
pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
if( pList ){
assert( pList->nExpr==iFirst+i+1 );
pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
pColumns->a[i].zName = 0;
}
}
if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
Expr *pFirst = pList->a[iFirst].pExpr;
assert( pFirst!=0 );
assert( pFirst->op==TK_SELECT_COLUMN );
/* Store the SELECT statement in pRight so it will be deleted when
** sqlite3ExprListDelete() is called */
pFirst->pRight = pExpr;
pExpr = 0;
/* Remember the size of the LHS in iTable so that we can check that
** the RHS and LHS sizes match during code generation. */
pFirst->iTable = pColumns->nId;
}
vector_append_error:
sqlite3ExprUnmapAndDelete(pParse, pExpr);
sqlite3IdListDelete(db, pColumns);
return pList;
}
/*
** Set the sort order for the last element on the given ExprList.
*/
void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
struct ExprList_item *pItem;
if( p==0 ) return;
assert( p->nExpr>0 );
assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
assert( iSortOrder==SQLITE_SO_UNDEFINED
|| iSortOrder==SQLITE_SO_ASC
|| iSortOrder==SQLITE_SO_DESC
);
assert( eNulls==SQLITE_SO_UNDEFINED
|| eNulls==SQLITE_SO_ASC
|| eNulls==SQLITE_SO_DESC
);
pItem = &p->a[p->nExpr-1];
assert( pItem->bNulls==0 );
if( iSortOrder==SQLITE_SO_UNDEFINED ){
iSortOrder = SQLITE_SO_ASC;
}
pItem->sortFlags = (u8)iSortOrder;
if( eNulls!=SQLITE_SO_UNDEFINED ){
pItem->bNulls = 1;
if( iSortOrder!=eNulls ){
pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;
}
}
}
/*
** Set the ExprList.a[].zName element of the most recently added item
** on the expression list.
**
** pList might be NULL following an OOM error. But pName should never be
** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
** is set.
*/
void sqlite3ExprListSetName(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to add the span. */
Token *pName, /* Name to be added */
int dequote /* True to cause the name to be dequoted */
){
assert( pList!=0 || pParse->db->mallocFailed!=0 );
if( pList ){
struct ExprList_item *pItem;
assert( pList->nExpr>0 );
pItem = &pList->a[pList->nExpr-1];
assert( pItem->zName==0 );
pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
if( dequote ) sqlite3Dequote(pItem->zName);
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
}
}
}
/*
** Set the ExprList.a[].zSpan element of the most recently added item
** on the expression list.
**
** pList might be NULL following an OOM error. But pSpan should never be
** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
** is set.
*/
void sqlite3ExprListSetSpan(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to add the span. */
const char *zStart, /* Start of the span */
const char *zEnd /* End of the span */
){
sqlite3 *db = pParse->db;
assert( pList!=0 || db->mallocFailed!=0 );
if( pList ){
struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
assert( pList->nExpr>0 );
sqlite3DbFree(db, pItem->zSpan);
pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
}
}
/*
** If the expression list pEList contains more than iLimit elements,
** leave an error message in pParse.
*/
void sqlite3ExprListCheckLength(
Parse *pParse,
ExprList *pEList,
const char *zObject
){
int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
testcase( pEList && pEList->nExpr==mx );
testcase( pEList && pEList->nExpr==mx+1 );
if( pEList && pEList->nExpr>mx ){
sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
}
}
/*
** Delete an entire expression list.
*/
static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
int i = pList->nExpr;
struct ExprList_item *pItem = pList->a;
assert( pList->nExpr>0 );
do{
sqlite3ExprDelete(db, pItem->pExpr);
sqlite3DbFree(db, pItem->zName);
sqlite3DbFree(db, pItem->zSpan);
pItem++;
}while( --i>0 );
sqlite3DbFreeNN(db, pList);
}
void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
if( pList ) exprListDeleteNN(db, pList);
}
/*
** Return the bitwise-OR of all Expr.flags fields in the given
** ExprList.
*/
u32 sqlite3ExprListFlags(const ExprList *pList){
int i;
u32 m = 0;
assert( pList!=0 );
for(i=0; i<pList->nExpr; i++){
Expr *pExpr = pList->a[i].pExpr;
assert( pExpr!=0 );
m |= pExpr->flags;
}
return m;
}
/*
** This is a SELECT-node callback for the expression walker that
** always "fails". By "fail" in this case, we mean set
** pWalker->eCode to zero and abort.
**
** This callback is used by multiple expression walkers.
*/
int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
UNUSED_PARAMETER(NotUsed);
pWalker->eCode = 0;
return WRC_Abort;
}
/*
** If the input expression is an ID with the name "true" or "false"
** then convert it into an TK_TRUEFALSE term. Return non-zero if
** the conversion happened, and zero if the expression is unaltered.
*/
int sqlite3ExprIdToTrueFalse(Expr *pExpr){
assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
if( !ExprHasProperty(pExpr, EP_Quoted)
&& (sqlite3StrICmp(pExpr->u.zToken, "true")==0
|| sqlite3StrICmp(pExpr->u.zToken, "false")==0)
){
pExpr->op = TK_TRUEFALSE;
ExprSetProperty(pExpr, pExpr->u.zToken[4]==0 ? EP_IsTrue : EP_IsFalse);
return 1;
}
return 0;
}
/*
** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
** and 0 if it is FALSE.
*/
int sqlite3ExprTruthValue(const Expr *pExpr){
pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
assert( pExpr->op==TK_TRUEFALSE );
assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
|| sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
return pExpr->u.zToken[4]==0;
}
/*
** If pExpr is an AND or OR expression, try to simplify it by eliminating
** terms that are always true or false. Return the simplified expression.
** Or return the original expression if no simplification is possible.
**
** Examples:
**
** (x<10) AND true => (x<10)
** (x<10) AND false => false
** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
** (x<10) AND (y=22 OR true) => (x<10)
** (y=22) OR true => true
*/
Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
assert( pExpr!=0 );
if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
pExpr = pExpr->op==TK_AND ? pRight : pLeft;
}else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
pExpr = pExpr->op==TK_AND ? pLeft : pRight;
}
}
return pExpr;
}
/*
** These routines are Walker callbacks used to check expressions to
** see if they are "constant" for some definition of constant. The
** Walker.eCode value determines the type of "constant" we are looking
** for.
**
** These callback routines are used to implement the following:
**
** sqlite3ExprIsConstant() pWalker->eCode==1
** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
** sqlite3ExprIsTableConstant() pWalker->eCode==3
** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
**
** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
** is found to not be a constant.
**
** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
** an existing schema and 4 when processing a new statement. A bound
** parameter raises an error for new statements, but is silently converted
** to NULL for existing schemas. This allows sqlite_master tables that
** contain a bound parameter because they were generated by older versions
** of SQLite to be parsed by newer versions of SQLite without raising a
** malformed schema error.
*/
static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
/* If pWalker->eCode is 2 then any term of the expression that comes from
** the ON or USING clauses of a left join disqualifies the expression
** from being considered constant. */
if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
pWalker->eCode = 0;
return WRC_Abort;
}
switch( pExpr->op ){
/* Consider functions to be constant if all their arguments are constant
** and either pWalker->eCode==4 or 5 or the function has the
** SQLITE_FUNC_CONST flag. */
case TK_FUNCTION:
if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
return WRC_Continue;
}else{
pWalker->eCode = 0;
return WRC_Abort;
}
case TK_ID:
/* Convert "true" or "false" in a DEFAULT clause into the
** appropriate TK_TRUEFALSE operator */
if( sqlite3ExprIdToTrueFalse(pExpr) ){
return WRC_Prune;
}
/* Fall thru */
case TK_COLUMN:
case TK_AGG_FUNCTION:
case TK_AGG_COLUMN:
testcase( pExpr->op==TK_ID );
testcase( pExpr->op==TK_COLUMN );
testcase( pExpr->op==TK_AGG_FUNCTION );
testcase( pExpr->op==TK_AGG_COLUMN );
if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
return WRC_Continue;
}
if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
return WRC_Continue;
}
/* Fall through */
case TK_IF_NULL_ROW:
case TK_REGISTER:
testcase( pExpr->op==TK_REGISTER );
testcase( pExpr->op==TK_IF_NULL_ROW );
pWalker->eCode = 0;
return WRC_Abort;
case TK_VARIABLE:
if( pWalker->eCode==5 ){
/* Silently convert bound parameters that appear inside of CREATE
** statements into a NULL when parsing the CREATE statement text out
** of the sqlite_master table */
pExpr->op = TK_NULL;
}else if( pWalker->eCode==4 ){
/* A bound parameter in a CREATE statement that originates from
** sqlite3_prepare() causes an error */
pWalker->eCode = 0;
return WRC_Abort;
}
/* Fall through */
default:
testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
return WRC_Continue;
}
}
static int exprIsConst(Expr *p, int initFlag, int iCur){
Walker w;
w.eCode = initFlag;
w.xExprCallback = exprNodeIsConstant;
w.xSelectCallback = sqlite3SelectWalkFail;
#ifdef SQLITE_DEBUG
w.xSelectCallback2 = sqlite3SelectWalkAssert2;
#endif
w.u.iCur = iCur;
sqlite3WalkExpr(&w, p);
return w.eCode;
}
/*
** Walk an expression tree. Return non-zero if the expression is constant
** and 0 if it involves variables or function calls.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
int sqlite3ExprIsConstant(Expr *p){
return exprIsConst(p, 1, 0);
}
/*
** Walk an expression tree. Return non-zero if
**
** (1) the expression is constant, and
** (2) the expression does originate in the ON or USING clause
** of a LEFT JOIN, and
** (3) the expression does not contain any EP_FixedCol TK_COLUMN
** operands created by the constant propagation optimization.
**
** When this routine returns true, it indicates that the expression
** can be added to the pParse->pConstExpr list and evaluated once when
** the prepared statement starts up. See sqlite3ExprCodeAtInit().
*/
int sqlite3ExprIsConstantNotJoin(Expr *p){
return exprIsConst(p, 2, 0);
}
/*
** Walk an expression tree. Return non-zero if the expression is constant
** for any single row of the table with cursor iCur. In other words, the
** expression must not refer to any non-deterministic function nor any
** table other than iCur.
*/
int sqlite3ExprIsTableConstant(Expr *p, int iCur){
return exprIsConst(p, 3, iCur);
}
/*
** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
*/
static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
ExprList *pGroupBy = pWalker->u.pGroupBy;
int i;
/* Check if pExpr is identical to any GROUP BY term. If so, consider
** it constant. */
for(i=0; i<pGroupBy->nExpr; i++){
Expr *p = pGroupBy->a[i].pExpr;
if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
if( sqlite3IsBinary(pColl) ){
return WRC_Prune;
}
}
}
/* Check if pExpr is a sub-select. If so, consider it variable. */
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
pWalker->eCode = 0;
return WRC_Abort;
}
return exprNodeIsConstant(pWalker, pExpr);
}
/*
** Walk the expression tree passed as the first argument. Return non-zero
** if the expression consists entirely of constants or copies of terms
** in pGroupBy that sort with the BINARY collation sequence.
**
** This routine is used to determine if a term of the HAVING clause can
** be promoted into the WHERE clause. In order for such a promotion to work,
** the value of the HAVING clause term must be the same for all members of
** a "group". The requirement that the GROUP BY term must be BINARY
** assumes that no other collating sequence will have a finer-grained
** grouping than binary. In other words (A=B COLLATE binary) implies
** A=B in every other collating sequence. The requirement that the
** GROUP BY be BINARY is stricter than necessary. It would also work
** to promote HAVING clauses that use the same alternative collating
** sequence as the GROUP BY term, but that is much harder to check,
** alternative collating sequences are uncommon, and this is only an
** optimization, so we take the easy way out and simply require the
** GROUP BY to use the BINARY collating sequence.
*/
int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
Walker w;
w.eCode = 1;
w.xExprCallback = exprNodeIsConstantOrGroupBy;
w.xSelectCallback = 0;
w.u.pGroupBy = pGroupBy;
w.pParse = pParse;
sqlite3WalkExpr(&w, p);
return w.eCode;
}
/*
** Walk an expression tree. Return non-zero if the expression is constant
** or a function call with constant arguments. Return and 0 if there
** are any variables.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
assert( isInit==0 || isInit==1 );
return exprIsConst(p, 4+isInit, 0);
}
#ifdef SQLITE_ENABLE_CURSOR_HINTS
/*
** Walk an expression tree. Return 1 if the expression contains a
** subquery of some kind. Return 0 if there are no subqueries.
*/
int sqlite3ExprContainsSubquery(Expr *p){
Walker w;
w.eCode = 1;
w.xExprCallback = sqlite3ExprWalkNoop;
w.xSelectCallback = sqlite3SelectWalkFail;
#ifdef SQLITE_DEBUG
w.xSelectCallback2 = sqlite3SelectWalkAssert2;
#endif
sqlite3WalkExpr(&w, p);
return w.eCode==0;
}
#endif
/*
** If the expression p codes a constant integer that is small enough
** to fit in a 32-bit integer, return 1 and put the value of the integer
** in *pValue. If the expression is not an integer or if it is too big
** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
*/
int sqlite3ExprIsInteger(Expr *p, int *pValue){
int rc = 0;
if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
/* If an expression is an integer literal that fits in a signed 32-bit
** integer, then the EP_IntValue flag will have already been set */
assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
|| sqlite3GetInt32(p->u.zToken, &rc)==0 );
if( p->flags & EP_IntValue ){
*pValue = p->u.iValue;
return 1;
}
switch( p->op ){
case TK_UPLUS: {
rc = sqlite3ExprIsInteger(p->pLeft, pValue);
break;
}
case TK_UMINUS: {
int v;
if( sqlite3ExprIsInteger(p->pLeft, &v) ){
assert( v!=(-2147483647-1) );
*pValue = -v;
rc = 1;
}
break;
}
default: break;
}
return rc;
}
/*
** Return FALSE if there is no chance that the expression can be NULL.
**
** If the expression might be NULL or if the expression is too complex
** to tell return TRUE.
**
** This routine is used as an optimization, to skip OP_IsNull opcodes
** when we know that a value cannot be NULL. Hence, a false positive
** (returning TRUE when in fact the expression can never be NULL) might
** be a small performance hit but is otherwise harmless. On the other
** hand, a false negative (returning FALSE when the result could be NULL)
** will likely result in an incorrect answer. So when in doubt, return
** TRUE.
*/
int sqlite3ExprCanBeNull(const Expr *p){
u8 op;
while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
p = p->pLeft;
}
op = p->op;
if( op==TK_REGISTER ) op = p->op2;
switch( op ){
case TK_INTEGER:
case TK_STRING:
case TK_FLOAT:
case TK_BLOB:
return 0;
case TK_COLUMN:
return ExprHasProperty(p, EP_CanBeNull) ||
p->y.pTab==0 || /* Reference to column of index on expression */
(p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
default:
return 1;
}
}
/*
** Return TRUE if the given expression is a constant which would be
** unchanged by OP_Affinity with the affinity given in the second
** argument.
**
** This routine is used to determine if the OP_Affinity operation
** can be omitted. When in doubt return FALSE. A false negative
** is harmless. A false positive, however, can result in the wrong
** answer.
*/
int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
u8 op;
int unaryMinus = 0;
if( aff==SQLITE_AFF_BLOB ) return 1;
while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
if( p->op==TK_UMINUS ) unaryMinus = 1;
p = p->pLeft;
}
op = p->op;
if( op==TK_REGISTER ) op = p->op2;
switch( op ){
case TK_INTEGER: {
return aff>=SQLITE_AFF_NUMERIC;
}
case TK_FLOAT: {
return aff>=SQLITE_AFF_NUMERIC;
}
case TK_STRING: {
return !unaryMinus && aff==SQLITE_AFF_TEXT;
}
case TK_BLOB: {
return !unaryMinus;
}
case TK_COLUMN: {
assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
}
default: {
return 0;
}
}
}
/*
** Return TRUE if the given string is a row-id column name.
*/
int sqlite3IsRowid(const char *z){
if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
if( sqlite3StrICmp(z, "OID")==0 ) return 1;
return 0;
}
/*
** pX is the RHS of an IN operator. If pX is a SELECT statement
** that can be simplified to a direct table access, then return
** a pointer to the SELECT statement. If pX is not a SELECT statement,
** or if the SELECT statement needs to be manifested into a transient
** table, then return NULL.
*/
#ifndef SQLITE_OMIT_SUBQUERY
static Select *isCandidateForInOpt(Expr *pX){
Select *p;
SrcList *pSrc;
ExprList *pEList;
Table *pTab;
int i;
if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
p = pX->x.pSelect;
if( p->pPrior ) return 0; /* Not a compound SELECT */
if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
return 0; /* No DISTINCT keyword and no aggregate functions */
}
assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
if( p->pLimit ) return 0; /* Has no LIMIT clause */
if( p->pWhere ) return 0; /* Has no WHERE clause */
pSrc = p->pSrc;
assert( pSrc!=0 );
if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
pTab = pSrc->a[0].pTab;
assert( pTab!=0 );
assert( pTab->pSelect==0 ); /* FROM clause is not a view */
if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
pEList = p->pEList;
assert( pEList!=0 );
/* All SELECT results must be columns. */
for(i=0; i<pEList->nExpr; i++){
Expr *pRes = pEList->a[i].pExpr;
if( pRes->op!=TK_COLUMN ) return 0;
assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
}
return p;
}
#endif /* SQLITE_OMIT_SUBQUERY */
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code that checks the left-most column of index table iCur to see if
** it contains any NULL entries. Cause the register at regHasNull to be set
** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
** to be set to NULL if iCur contains one or more NULL values.
*/
static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
int addr1;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
VdbeComment((v, "first_entry_in(%d)", iCur));
sqlite3VdbeJumpHere(v, addr1);
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** The argument is an IN operator with a list (not a subquery) on the
** right-hand side. Return TRUE if that list is constant.
*/
static int sqlite3InRhsIsConstant(Expr *pIn){
Expr *pLHS;
int res;
assert( !ExprHasProperty(pIn, EP_xIsSelect) );
pLHS = pIn->pLeft;
pIn->pLeft = 0;
res = sqlite3ExprIsConstant(pIn);
pIn->pLeft = pLHS;
return res;
}
#endif
/*
** This function is used by the implementation of the IN (...) operator.
** The pX parameter is the expression on the RHS of the IN operator, which
** might be either a list of expressions or a subquery.
**
** The job of this routine is to find or create a b-tree object that can
** be used either to test for membership in the RHS set or to iterate through
** all members of the RHS set, skipping duplicates.
**
** A cursor is opened on the b-tree object that is the RHS of the IN operator
** and pX->iTable is set to the index of that cursor.
**
** The returned value of this function indicates the b-tree type, as follows:
**
** IN_INDEX_ROWID - The cursor was opened on a database table.
** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
** IN_INDEX_EPH - The cursor was opened on a specially created and
** populated epheremal table.
** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
** implemented as a sequence of comparisons.
**
** An existing b-tree might be used if the RHS expression pX is a simple
** subquery such as:
**
** SELECT <column1>, <column2>... FROM <table>
**
** If the RHS of the IN operator is a list or a more complex subquery, then
** an ephemeral table might need to be generated from the RHS and then
** pX->iTable made to point to the ephemeral table instead of an
** existing table.
**
** The inFlags parameter must contain, at a minimum, one of the bits
** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
** be used to loop over all values of the RHS of the IN operator.
**
** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
** through the set members) then the b-tree must not contain duplicates.
** An epheremal table will be created unless the selected columns are guaranteed
** to be unique - either because it is an INTEGER PRIMARY KEY or due to
** a UNIQUE constraint or index.
**
** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
** for fast set membership tests) then an epheremal table must
** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
** index can be found with the specified <columns> as its left-most.
**
** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
** if the RHS of the IN operator is a list (not a subquery) then this
** routine might decide that creating an ephemeral b-tree for membership
** testing is too expensive and return IN_INDEX_NOOP. In that case, the
** calling routine should implement the IN operator using a sequence
** of Eq or Ne comparison operations.
**
** When the b-tree is being used for membership tests, the calling function
** might need to know whether or not the RHS side of the IN operator
** contains a NULL. If prRhsHasNull is not a NULL pointer and
** if there is any chance that the (...) might contain a NULL value at
** runtime, then a register is allocated and the register number written
** to *prRhsHasNull. If there is no chance that the (...) contains a
** NULL value, then *prRhsHasNull is left unchanged.
**
** If a register is allocated and its location stored in *prRhsHasNull, then
** the value in that register will be NULL if the b-tree contains one or more
** NULL values, and it will be some non-NULL value if the b-tree contains no
** NULL values.
**
** If the aiMap parameter is not NULL, it must point to an array containing
** one element for each column returned by the SELECT statement on the RHS
** of the IN(...) operator. The i'th entry of the array is populated with the
** offset of the index column that matches the i'th column returned by the
** SELECT. For example, if the expression and selected index are:
**
** (?,?,?) IN (SELECT a, b, c FROM t1)
** CREATE INDEX i1 ON t1(b, c, a);
**
** then aiMap[] is populated with {2, 0, 1}.
*/
#ifndef SQLITE_OMIT_SUBQUERY
int sqlite3FindInIndex(
Parse *pParse, /* Parsing context */
Expr *pX, /* The IN expression */
u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
int *prRhsHasNull, /* Register holding NULL status. See notes */
int *aiMap, /* Mapping from Index fields to RHS fields */
int *piTab /* OUT: index to use */
){
Select *p; /* SELECT to the right of IN operator */
int eType = 0; /* Type of RHS table. IN_INDEX_* */
int iTab = pParse->nTab++; /* Cursor of the RHS table */
int mustBeUnique; /* True if RHS must be unique */
Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
assert( pX->op==TK_IN );
mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
/* If the RHS of this IN(...) operator is a SELECT, and if it matters
** whether or not the SELECT result contains NULL values, check whether
** or not NULL is actually possible (it may not be, for example, due
** to NOT NULL constraints in the schema). If no NULL values are possible,
** set prRhsHasNull to 0 before continuing. */
if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
int i;
ExprList *pEList = pX->x.pSelect->pEList;
for(i=0; i<pEList->nExpr; i++){
if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
}
if( i==pEList->nExpr ){
prRhsHasNull = 0;
}
}
/* Check to see if an existing table or index can be used to
** satisfy the query. This is preferable to generating a new
** ephemeral table. */
if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
sqlite3 *db = pParse->db; /* Database connection */
Table *pTab; /* Table <table>. */
i16 iDb; /* Database idx for pTab */
ExprList *pEList = p->pEList;
int nExpr = pEList->nExpr;
assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
pTab = p->pSrc->a[0].pTab;
/* Code an OP_Transaction and OP_TableLock for <table>. */
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
sqlite3CodeVerifySchema(pParse, iDb);
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
assert(v); /* sqlite3GetVdbe() has always been previously called */
if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
/* The "x IN (SELECT rowid FROM table)" case */
int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
VdbeCoverage(v);
sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
eType = IN_INDEX_ROWID;
ExplainQueryPlan((pParse, 0,
"USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
sqlite3VdbeJumpHere(v, iAddr);
}else{
Index *pIdx; /* Iterator variable */
int affinity_ok = 1;
int i;
/* Check that the affinity that will be used to perform each
** comparison is the same as the affinity of each column in table
** on the RHS of the IN operator. If it not, it is not possible to
** use any index of the RHS table. */
for(i=0; i<nExpr && affinity_ok; i++){
Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
int iCol = pEList->a[i].pExpr->iColumn;
char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
testcase( cmpaff==SQLITE_AFF_BLOB );
testcase( cmpaff==SQLITE_AFF_TEXT );
switch( cmpaff ){
case SQLITE_AFF_BLOB:
break;
case SQLITE_AFF_TEXT:
/* sqlite3CompareAffinity() only returns TEXT if one side or the
** other has no affinity and the other side is TEXT. Hence,
** the only way for cmpaff to be TEXT is for idxaff to be TEXT
** and for the term on the LHS of the IN to have no affinity. */
assert( idxaff==SQLITE_AFF_TEXT );
break;
default:
affinity_ok = sqlite3IsNumericAffinity(idxaff);
}
}
if( affinity_ok ){
/* Search for an existing index that will work for this IN operator */
for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
Bitmask colUsed; /* Columns of the index used */
Bitmask mCol; /* Mask for the current column */
if( pIdx->nColumn<nExpr ) continue;
if( pIdx->pPartIdxWhere!=0 ) continue;
/* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
** BITMASK(nExpr) without overflowing */
testcase( pIdx->nColumn==BMS-2 );
testcase( pIdx->nColumn==BMS-1 );
if( pIdx->nColumn>=BMS-1 ) continue;
if( mustBeUnique ){
if( pIdx->nKeyCol>nExpr
||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
){
continue; /* This index is not unique over the IN RHS columns */
}
}
colUsed = 0; /* Columns of index used so far */
for(i=0; i<nExpr; i++){
Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
Expr *pRhs = pEList->a[i].pExpr;
CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
int j;
assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
for(j=0; j<nExpr; j++){
if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
assert( pIdx->azColl[j] );
if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
continue;
}
break;
}
if( j==nExpr ) break;
mCol = MASKBIT(j);
if( mCol & colUsed ) break; /* Each column used only once */
colUsed |= mCol;
if( aiMap ) aiMap[i] = j;
}
assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
if( colUsed==(MASKBIT(nExpr)-1) ){
/* If we reach this point, that means the index pIdx is usable */
int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
ExplainQueryPlan((pParse, 0,
"USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
VdbeComment((v, "%s", pIdx->zName));
assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
if( prRhsHasNull ){
#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
i64 mask = (1<<nExpr)-1;
sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
iTab, 0, 0, (u8*)&mask, P4_INT64);
#endif
*prRhsHasNull = ++pParse->nMem;
if( nExpr==1 ){
sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
}
}
sqlite3VdbeJumpHere(v, iAddr);
}
} /* End loop over indexes */
} /* End if( affinity_ok ) */
} /* End if not an rowid index */
} /* End attempt to optimize using an index */
/* If no preexisting index is available for the IN clause
** and IN_INDEX_NOOP is an allowed reply
** and the RHS of the IN operator is a list, not a subquery
** and the RHS is not constant or has two or fewer terms,
** then it is not worth creating an ephemeral table to evaluate
** the IN operator so return IN_INDEX_NOOP.
*/
if( eType==0
&& (inFlags & IN_INDEX_NOOP_OK)
&& !ExprHasProperty(pX, EP_xIsSelect)
&& (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
){
eType = IN_INDEX_NOOP;
}
if( eType==0 ){
/* Could not find an existing table or index to use as the RHS b-tree.
** We will have to generate an ephemeral table to do the job.
*/
u32 savedNQueryLoop = pParse->nQueryLoop;
int rMayHaveNull = 0;
eType = IN_INDEX_EPH;
if( inFlags & IN_INDEX_LOOP ){
pParse->nQueryLoop = 0;
}else if( prRhsHasNull ){
*prRhsHasNull = rMayHaveNull = ++pParse->nMem;
}
assert( pX->op==TK_IN );
sqlite3CodeRhsOfIN(pParse, pX, iTab);
if( rMayHaveNull ){
sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
}
pParse->nQueryLoop = savedNQueryLoop;
}
if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
int i, n;
n = sqlite3ExprVectorSize(pX->pLeft);
for(i=0; i<n; i++) aiMap[i] = i;
}
*piTab = iTab;
return eType;
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Argument pExpr is an (?, ?...) IN(...) expression. This
** function allocates and returns a nul-terminated string containing
** the affinities to be used for each column of the comparison.
**
** It is the responsibility of the caller to ensure that the returned
** string is eventually freed using sqlite3DbFree().
*/
static char *exprINAffinity(Parse *pParse, Expr *pExpr){
Expr *pLeft = pExpr->pLeft;
int nVal = sqlite3ExprVectorSize(pLeft);
Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
char *zRet;
assert( pExpr->op==TK_IN );
zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
if( zRet ){
int i;
for(i=0; i<nVal; i++){
Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
char a = sqlite3ExprAffinity(pA);
if( pSelect ){
zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
}else{
zRet[i] = a;
}
}
zRet[nVal] = '\0';
}
return zRet;
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Load the Parse object passed as the first argument with an error
** message of the form:
**
** "sub-select returns N columns - expected M"
*/
void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
const char *zFmt = "sub-select returns %d columns - expected %d";
sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
}
#endif
/*
** Expression pExpr is a vector that has been used in a context where
** it is not permitted. If pExpr is a sub-select vector, this routine
** loads the Parse object with a message of the form:
**
** "sub-select returns N columns - expected 1"
**
** Or, if it is a regular scalar vector:
**
** "row value misused"
*/
void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
#ifndef SQLITE_OMIT_SUBQUERY
if( pExpr->flags & EP_xIsSelect ){
sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
}else
#endif
{
sqlite3ErrorMsg(pParse, "row value misused");
}
}
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code that will construct an ephemeral table containing all terms
** in the RHS of an IN operator. The IN operator can be in either of two
** forms:
**
** x IN (4,5,11) -- IN operator with list on right-hand side
** x IN (SELECT a FROM b) -- IN operator with subquery on the right
**
** The pExpr parameter is the IN operator. The cursor number for the
** constructed ephermeral table is returned. The first time the ephemeral
** table is computed, the cursor number is also stored in pExpr->iTable,
** however the cursor number returned might not be the same, as it might
** have been duplicated using OP_OpenDup.
**
** If the LHS expression ("x" in the examples) is a column value, or
** the SELECT statement returns a column value, then the affinity of that
** column is used to build the index keys. If both 'x' and the
** SELECT... statement are columns, then numeric affinity is used
** if either column has NUMERIC or INTEGER affinity. If neither
** 'x' nor the SELECT... statement are columns, then numeric affinity
** is used.
*/
void sqlite3CodeRhsOfIN(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* The IN operator */
int iTab /* Use this cursor number */
){
int addrOnce = 0; /* Address of the OP_Once instruction at top */
int addr; /* Address of OP_OpenEphemeral instruction */
Expr *pLeft; /* the LHS of the IN operator */
KeyInfo *pKeyInfo = 0; /* Key information */
int nVal; /* Size of vector pLeft */
Vdbe *v; /* The prepared statement under construction */
v = pParse->pVdbe;
assert( v!=0 );
/* The evaluation of the IN must be repeated every time it
** is encountered if any of the following is true:
**
** * The right-hand side is a correlated subquery
** * The right-hand side is an expression list containing variables
** * We are inside a trigger
**
** If all of the above are false, then we can compute the RHS just once
** and reuse it many names.
*/
if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
/* Reuse of the RHS is allowed */
/* If this routine has already been coded, but the previous code
** might not have been invoked yet, so invoke it now as a subroutine.
*/
if( ExprHasProperty(pExpr, EP_Subrtn) ){
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
pExpr->x.pSelect->selId));
}
sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
pExpr->y.sub.iAddr);
sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
sqlite3VdbeJumpHere(v, addrOnce);
return;
}
/* Begin coding the subroutine */
ExprSetProperty(pExpr, EP_Subrtn);
pExpr->y.sub.regReturn = ++pParse->nMem;
pExpr->y.sub.iAddr =
sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
VdbeComment((v, "return address"));
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
}
/* Check to see if this is a vector IN operator */
pLeft = pExpr->pLeft;
nVal = sqlite3ExprVectorSize(pLeft);
/* Construct the ephemeral table that will contain the content of
** RHS of the IN operator.
*/
pExpr->iTable = iTab;
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
}else{
VdbeComment((v, "RHS of IN operator"));
}
#endif
pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
/* Case 1: expr IN (SELECT ...)
**
** Generate code to write the results of the select into the temporary
** table allocated and opened above.
*/
Select *pSelect = pExpr->x.pSelect;
ExprList *pEList = pSelect->pEList;
ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
addrOnce?"":"CORRELATED ", pSelect->selId
));
/* If the LHS and RHS of the IN operator do not match, that
** error will have been caught long before we reach this point. */
if( ALWAYS(pEList->nExpr==nVal) ){
SelectDest dest;
int i;
sqlite3SelectDestInit(&dest, SRT_Set, iTab);
dest.zAffSdst = exprINAffinity(pParse, pExpr);
pSelect->iLimit = 0;
testcase( pSelect->selFlags & SF_Distinct );
testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
if( sqlite3Select(pParse, pSelect, &dest) ){
sqlite3DbFree(pParse->db, dest.zAffSdst);
sqlite3KeyInfoUnref(pKeyInfo);
return;
}
sqlite3DbFree(pParse->db, dest.zAffSdst);
assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
assert( pEList!=0 );
assert( pEList->nExpr>0 );
assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
for(i=0; i<nVal; i++){
Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
pParse, p, pEList->a[i].pExpr
);
}
}
}else if( ALWAYS(pExpr->x.pList!=0) ){
/* Case 2: expr IN (exprlist)
**
** For each expression, build an index key from the evaluation and
** store it in the temporary table. If <expr> is a column, then use
** that columns affinity when building index keys. If <expr> is not
** a column, use numeric affinity.
*/
char affinity; /* Affinity of the LHS of the IN */
int i;
ExprList *pList = pExpr->x.pList;
struct ExprList_item *pItem;
int r1, r2;
affinity = sqlite3ExprAffinity(pLeft);
if( affinity<=SQLITE_AFF_NONE ){
affinity = SQLITE_AFF_BLOB;
}
if( pKeyInfo ){
assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
}
/* Loop through each expression in <exprlist>. */
r1 = sqlite3GetTempReg(pParse);
r2 = sqlite3GetTempReg(pParse);
for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
Expr *pE2 = pItem->pExpr;
/* If the expression is not constant then we will need to
** disable the test that was generated above that makes sure
** this code only executes once. Because for a non-constant
** expression we need to rerun this code each time.
*/
if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
sqlite3VdbeChangeToNoop(v, addrOnce);
ExprClearProperty(pExpr, EP_Subrtn);
addrOnce = 0;
}
/* Evaluate the expression and insert it into the temp table */
sqlite3ExprCode(pParse, pE2, r1);
sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
}
sqlite3ReleaseTempReg(pParse, r1);
sqlite3ReleaseTempReg(pParse, r2);
}
if( pKeyInfo ){
sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
}
if( addrOnce ){
sqlite3VdbeJumpHere(v, addrOnce);
/* Subroutine return */
sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
sqlite3ClearTempRegCache(pParse);
}
}
#endif /* SQLITE_OMIT_SUBQUERY */
/*
** Generate code for scalar subqueries used as a subquery expression
** or EXISTS operator:
**
** (SELECT a FROM b) -- subquery
** EXISTS (SELECT a FROM b) -- EXISTS subquery
**
** The pExpr parameter is the SELECT or EXISTS operator to be coded.
**
** Return the register that holds the result. For a multi-column SELECT,
** the result is stored in a contiguous array of registers and the
** return value is the register of the left-most result column.
** Return 0 if an error occurs.
*/
#ifndef SQLITE_OMIT_SUBQUERY
int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
int addrOnce = 0; /* Address of OP_Once at top of subroutine */
int rReg = 0; /* Register storing resulting */
Select *pSel; /* SELECT statement to encode */
SelectDest dest; /* How to deal with SELECT result */
int nReg; /* Registers to allocate */
Expr *pLimit; /* New limit expression */
Vdbe *v = pParse->pVdbe;
assert( v!=0 );
testcase( pExpr->op==TK_EXISTS );
testcase( pExpr->op==TK_SELECT );
assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
assert( ExprHasProperty(pExpr, EP_xIsSelect) );
pSel = pExpr->x.pSelect;
/* The evaluation of the EXISTS/SELECT must be repeated every time it
** is encountered if any of the following is true:
**
** * The right-hand side is a correlated subquery
** * The right-hand side is an expression list containing variables
** * We are inside a trigger
**
** If all of the above are false, then we can run this code just once
** save the results, and reuse the same result on subsequent invocations.
*/
if( !ExprHasProperty(pExpr, EP_VarSelect) ){
/* If this routine has already been coded, then invoke it as a
** subroutine. */
if( ExprHasProperty(pExpr, EP_Subrtn) ){
ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
pExpr->y.sub.iAddr);
return pExpr->iTable;
}
/* Begin coding the subroutine */
ExprSetProperty(pExpr, EP_Subrtn);
pExpr->y.sub.regReturn = ++pParse->nMem;
pExpr->y.sub.iAddr =
sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
VdbeComment((v, "return address"));
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
}
/* For a SELECT, generate code to put the values for all columns of
** the first row into an array of registers and return the index of
** the first register.
**
** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
** into a register and return that register number.
**
** In both cases, the query is augmented with "LIMIT 1". Any
** preexisting limit is discarded in place of the new LIMIT 1.
*/
ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
addrOnce?"":"CORRELATED ", pSel->selId));
nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
pParse->nMem += nReg;
if( pExpr->op==TK_SELECT ){
dest.eDest = SRT_Mem;
dest.iSdst = dest.iSDParm;
dest.nSdst = nReg;
sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
VdbeComment((v, "Init subquery result"));
}else{
dest.eDest = SRT_Exists;
sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
VdbeComment((v, "Init EXISTS result"));
}
if( pSel->pLimit ){
/* The subquery already has a limit. If the pre-existing limit is X
** then make the new limit X<>0 so that the new limit is either 1 or 0 */
sqlite3 *db = pParse->db;
pLimit = sqlite3Expr(db, TK_INTEGER, "0");
if( pLimit ){
pLimit->affExpr = SQLITE_AFF_NUMERIC;
pLimit = sqlite3PExpr(pParse, TK_NE,
sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
}
sqlite3ExprDelete(db, pSel->pLimit->pLeft);
pSel->pLimit->pLeft = pLimit;
}else{
/* If there is no pre-existing limit add a limit of 1 */
pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
}
pSel->iLimit = 0;
if( sqlite3Select(pParse, pSel, &dest) ){
return 0;
}
pExpr->iTable = rReg = dest.iSDParm;
ExprSetVVAProperty(pExpr, EP_NoReduce);
if( addrOnce ){
sqlite3VdbeJumpHere(v, addrOnce);
/* Subroutine return */
sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
sqlite3ClearTempRegCache(pParse);
}
return rReg;
}
#endif /* SQLITE_OMIT_SUBQUERY */
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Expr pIn is an IN(...) expression. This function checks that the
** sub-select on the RHS of the IN() operator has the same number of
** columns as the vector on the LHS. Or, if the RHS of the IN() is not
** a sub-query, that the LHS is a vector of size 1.
*/
int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
int nVector = sqlite3ExprVectorSize(pIn->pLeft);
if( (pIn->flags & EP_xIsSelect) ){
if( nVector!=pIn->x.pSelect->pEList->nExpr ){
sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
return 1;
}
}else if( nVector!=1 ){
sqlite3VectorErrorMsg(pParse, pIn->pLeft);
return 1;
}
return 0;
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code for an IN expression.
**
** x IN (SELECT ...)
** x IN (value, value, ...)
**
** The left-hand side (LHS) is a scalar or vector expression. The
** right-hand side (RHS) is an array of zero or more scalar values, or a
** subquery. If the RHS is a subquery, the number of result columns must
** match the number of columns in the vector on the LHS. If the RHS is
** a list of values, the LHS must be a scalar.
**
** The IN operator is true if the LHS value is contained within the RHS.
** The result is false if the LHS is definitely not in the RHS. The
** result is NULL if the presence of the LHS in the RHS cannot be
** determined due to NULLs.
**
** This routine generates code that jumps to destIfFalse if the LHS is not
** contained within the RHS. If due to NULLs we cannot determine if the LHS
** is contained in the RHS then jump to destIfNull. If the LHS is contained
** within the RHS then fall through.
**
** See the separate in-operator.md documentation file in the canonical
** SQLite source tree for additional information.
*/
static void sqlite3ExprCodeIN(
Parse *pParse, /* Parsing and code generating context */
Expr *pExpr, /* The IN expression */
int destIfFalse, /* Jump here if LHS is not contained in the RHS */
int destIfNull /* Jump here if the results are unknown due to NULLs */
){
int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
int eType; /* Type of the RHS */
int rLhs; /* Register(s) holding the LHS values */
int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
Vdbe *v; /* Statement under construction */
int *aiMap = 0; /* Map from vector field to index column */
char *zAff = 0; /* Affinity string for comparisons */
int nVector; /* Size of vectors for this IN operator */
int iDummy; /* Dummy parameter to exprCodeVector() */
Expr *pLeft; /* The LHS of the IN operator */
int i; /* loop counter */
int destStep2; /* Where to jump when NULLs seen in step 2 */
int destStep6 = 0; /* Start of code for Step 6 */
int addrTruthOp; /* Address of opcode that determines the IN is true */
int destNotNull; /* Jump here if a comparison is not true in step 6 */
int addrTop; /* Top of the step-6 loop */
int iTab = 0; /* Index to use */
pLeft = pExpr->pLeft;
if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
zAff = exprINAffinity(pParse, pExpr);
nVector = sqlite3ExprVectorSize(pExpr->pLeft);
aiMap = (int*)sqlite3DbMallocZero(
pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
);
if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
/* Attempt to compute the RHS. After this step, if anything other than
** IN_INDEX_NOOP is returned, the table opened with cursor iTab
** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
** the RHS has not yet been coded. */
v = pParse->pVdbe;
assert( v!=0 ); /* OOM detected prior to this routine */
VdbeNoopComment((v, "begin IN expr"));
eType = sqlite3FindInIndex(pParse, pExpr,
IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
destIfFalse==destIfNull ? 0 : &rRhsHasNull,
aiMap, &iTab);
assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
|| eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
);
#ifdef SQLITE_DEBUG
/* Confirm that aiMap[] contains nVector integer values between 0 and
** nVector-1. */
for(i=0; i<nVector; i++){
int j, cnt;
for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
assert( cnt==1 );
}
#endif
/* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
** vector, then it is stored in an array of nVector registers starting
** at r1.
**
** sqlite3FindInIndex() might have reordered the fields of the LHS vector
** so that the fields are in the same order as an existing index. The
** aiMap[] array contains a mapping from the original LHS field order to
** the field order that matches the RHS index.
*/
rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
if( i==nVector ){
/* LHS fields are not reordered */
rLhs = rLhsOrig;
}else{
/* Need to reorder the LHS fields according to aiMap */
rLhs = sqlite3GetTempRange(pParse, nVector);
for(i=0; i<nVector; i++){
sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
}
}
/* If sqlite3FindInIndex() did not find or create an index that is
** suitable for evaluating the IN operator, then evaluate using a
** sequence of comparisons.
**
** This is step (1) in the in-operator.md optimized algorithm.
*/
if( eType==IN_INDEX_NOOP ){
ExprList *pList = pExpr->x.pList;
CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
int labelOk = sqlite3VdbeMakeLabel(pParse);
int r2, regToFree;
int regCkNull = 0;
int ii;
int bLhsReal; /* True if the LHS of the IN has REAL affinity */
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
if( destIfNull!=destIfFalse ){
regCkNull = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
}
bLhsReal = sqlite3ExprAffinity(pExpr->pLeft)==SQLITE_AFF_REAL;
for(ii=0; ii<pList->nExpr; ii++){
if( bLhsReal ){
r2 = regToFree = sqlite3GetTempReg(pParse);
sqlite3ExprCode(pParse, pList->a[ii].pExpr, r2);
sqlite3VdbeAddOp4(v, OP_Affinity, r2, 1, 0, "E", P4_STATIC);
}else{
r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree);
}
if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
}
if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
(void*)pColl, P4_COLLSEQ);
VdbeCoverageIf(v, ii<pList->nExpr-1);
VdbeCoverageIf(v, ii==pList->nExpr-1);
sqlite3VdbeChangeP5(v, zAff[0]);
}else{
assert( destIfNull==destIfFalse );
sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
(void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
}
sqlite3ReleaseTempReg(pParse, regToFree);
}
if( regCkNull ){
sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
sqlite3VdbeGoto(v, destIfFalse);
}
sqlite3VdbeResolveLabel(v, labelOk);
sqlite3ReleaseTempReg(pParse, regCkNull);
goto sqlite3ExprCodeIN_finished;
}
/* Step 2: Check to see if the LHS contains any NULL columns. If the
** LHS does contain NULLs then the result must be either FALSE or NULL.
** We will then skip the binary search of the RHS.
*/
if( destIfNull==destIfFalse ){
destStep2 = destIfFalse;
}else{
destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
}
for(i=0; i<nVector; i++){
Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
if( sqlite3ExprCanBeNull(p) ){
sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
VdbeCoverage(v);
}
}
/* Step 3. The LHS is now known to be non-NULL. Do the binary search
** of the RHS using the LHS as a probe. If found, the result is
** true.
*/
if( eType==IN_INDEX_ROWID ){
/* In this case, the RHS is the ROWID of table b-tree and so we also
** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
** into a single opcode. */
sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
VdbeCoverage(v);
addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
}else{
sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
if( destIfFalse==destIfNull ){
/* Combine Step 3 and Step 5 into a single opcode */
sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
rLhs, nVector); VdbeCoverage(v);
goto sqlite3ExprCodeIN_finished;
}
/* Ordinary Step 3, for the case where FALSE and NULL are distinct */
addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
rLhs, nVector); VdbeCoverage(v);
}
/* Step 4. If the RHS is known to be non-NULL and we did not find
** an match on the search above, then the result must be FALSE.
*/
if( rRhsHasNull && nVector==1 ){
sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
VdbeCoverage(v);
}
/* Step 5. If we do not care about the difference between NULL and
** FALSE, then just return false.
*/
if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
/* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
** If any comparison is NULL, then the result is NULL. If all
** comparisons are FALSE then the final result is FALSE.
**
** For a scalar LHS, it is sufficient to check just the first row
** of the RHS.
*/
if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
VdbeCoverage(v);
if( nVector>1 ){
destNotNull = sqlite3VdbeMakeLabel(pParse);
}else{
/* For nVector==1, combine steps 6 and 7 by immediately returning
** FALSE if the first comparison is not NULL */
destNotNull = destIfFalse;
}
for(i=0; i<nVector; i++){
Expr *p;
CollSeq *pColl;
int r3 = sqlite3GetTempReg(pParse);
p = sqlite3VectorFieldSubexpr(pLeft, i);
pColl = sqlite3ExprCollSeq(pParse, p);
sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
(void*)pColl, P4_COLLSEQ);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, r3);
}
sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
if( nVector>1 ){
sqlite3VdbeResolveLabel(v, destNotNull);
sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
VdbeCoverage(v);
/* Step 7: If we reach this point, we know that the result must
** be false. */
sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
}
/* Jumps here in order to return true. */
sqlite3VdbeJumpHere(v, addrTruthOp);
sqlite3ExprCodeIN_finished:
if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
VdbeComment((v, "end IN expr"));
sqlite3ExprCodeIN_oom_error:
sqlite3DbFree(pParse->db, aiMap);
sqlite3DbFree(pParse->db, zAff);
}
#endif /* SQLITE_OMIT_SUBQUERY */
#ifndef SQLITE_OMIT_FLOATING_POINT
/*
** Generate an instruction that will put the floating point
** value described by z[0..n-1] into register iMem.
**
** The z[] string will probably not be zero-terminated. But the
** z[n] character is guaranteed to be something that does not look
** like the continuation of the number.
*/
static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
if( ALWAYS(z!=0) ){
double value;
sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
if( negateFlag ) value = -value;
sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
}
}
#endif
/*
** Generate an instruction that will put the integer describe by
** text z[0..n-1] into register iMem.
**
** Expr.u.zToken is always UTF8 and zero-terminated.
*/
static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
Vdbe *v = pParse->pVdbe;
if( pExpr->flags & EP_IntValue ){
int i = pExpr->u.iValue;
assert( i>=0 );
if( negFlag ) i = -i;
sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
}else{
int c;
i64 value;
const char *z = pExpr->u.zToken;
assert( z!=0 );
c = sqlite3DecOrHexToI64(z, &value);
if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
#ifdef SQLITE_OMIT_FLOATING_POINT
sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
#else
#ifndef SQLITE_OMIT_HEX_INTEGER
if( sqlite3_strnicmp(z,"0x",2)==0 ){
sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
}else
#endif
{
codeReal(v, z, negFlag, iMem);
}
#endif
}else{
if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
}
}
}
/* Generate code that will load into register regOut a value that is
** appropriate for the iIdxCol-th column of index pIdx.
*/
void sqlite3ExprCodeLoadIndexColumn(
Parse *pParse, /* The parsing context */
Index *pIdx, /* The index whose column is to be loaded */
int iTabCur, /* Cursor pointing to a table row */
int iIdxCol, /* The column of the index to be loaded */
int regOut /* Store the index column value in this register */
){
i16 iTabCol = pIdx->aiColumn[iIdxCol];
if( iTabCol==XN_EXPR ){
assert( pIdx->aColExpr );
assert( pIdx->aColExpr->nExpr>iIdxCol );
pParse->iSelfTab = iTabCur + 1;
sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
pParse->iSelfTab = 0;
}else{
sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
iTabCol, regOut);
}
}
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
/*
** Generate code that will compute the value of generated column pCol
** and store the result in register regOut
*/
void sqlite3ExprCodeGeneratedColumn(
Parse *pParse,
Column *pCol,
int regOut
){
sqlite3ExprCode(pParse, pCol->pDflt, regOut);
if( pCol->affinity>=SQLITE_AFF_TEXT ){
sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, regOut, 1, 0,
&pCol->affinity, 1);
}
}
#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
/*
** Generate code to extract the value of the iCol-th column of a table.
*/
void sqlite3ExprCodeGetColumnOfTable(
Vdbe *v, /* Parsing context */
Table *pTab, /* The table containing the value */
int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
int iCol, /* Index of the column to extract */
int regOut /* Extract the value into this register */
){
Column *pCol;
assert( v!=0 );
if( pTab==0 ){
sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
return;
}
if( iCol<0 || iCol==pTab->iPKey ){
sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
}else{
int op;
int x;
if( IsVirtual(pTab) ){
op = OP_VColumn;
x = iCol;
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
}else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
Parse *pParse = sqlite3VdbeParser(v);
if( pCol->colFlags & COLFLAG_BUSY ){
sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
}else{
int savedSelfTab = pParse->iSelfTab;
pCol->colFlags |= COLFLAG_BUSY;
pParse->iSelfTab = iTabCur+1;
sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
pParse->iSelfTab = savedSelfTab;
pCol->colFlags &= ~COLFLAG_BUSY;
}
return;
#endif
}else if( !HasRowid(pTab) ){
testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
op = OP_Column;
}else{
x = sqlite3TableColumnToStorage(pTab,iCol);
testcase( x!=iCol );
op = OP_Column;
}
sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
sqlite3ColumnDefault(v, pTab, iCol, regOut);
}
}
/*
** Generate code that will extract the iColumn-th column from
** table pTab and store the column value in register iReg.
**
** There must be an open cursor to pTab in iTable when this routine
** is called. If iColumn<0 then code is generated that extracts the rowid.
*/
int sqlite3ExprCodeGetColumn(
Parse *pParse, /* Parsing and code generating context */
Table *pTab, /* Description of the table we are reading from */
int iColumn, /* Index of the table column */
int iTable, /* The cursor pointing to the table */
int iReg, /* Store results here */
u8 p5 /* P5 value for OP_Column + FLAGS */
){
assert( pParse->pVdbe!=0 );
sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
if( p5 ){
sqlite3VdbeChangeP5(pParse->pVdbe, p5);
}
return iReg;
}
/*
** Generate code to move content from registers iFrom...iFrom+nReg-1
** over to iTo..iTo+nReg-1.
*/
void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
}
/*
** Convert a scalar expression node to a TK_REGISTER referencing
** register iReg. The caller must ensure that iReg already contains
** the correct value for the expression.
*/
static void exprToRegister(Expr *pExpr, int iReg){
Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
p->op2 = p->op;
p->op = TK_REGISTER;
p->iTable = iReg;
ExprClearProperty(p, EP_Skip);
}
/*
** Evaluate an expression (either a vector or a scalar expression) and store
** the result in continguous temporary registers. Return the index of
** the first register used to store the result.
**
** If the returned result register is a temporary scalar, then also write
** that register number into *piFreeable. If the returned result register
** is not a temporary or if the expression is a vector set *piFreeable
** to 0.
*/
static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
int iResult;
int nResult = sqlite3ExprVectorSize(p);
if( nResult==1 ){
iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
}else{
*piFreeable = 0;
if( p->op==TK_SELECT ){
#if SQLITE_OMIT_SUBQUERY
iResult = 0;
#else
iResult = sqlite3CodeSubselect(pParse, p);
#endif
}else{
int i;
iResult = pParse->nMem+1;
pParse->nMem += nResult;
for(i=0; i<nResult; i++){
sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
}
}
}
return iResult;
}
/*
** Generate code into the current Vdbe to evaluate the given
** expression. Attempt to store the results in register "target".
** Return the register where results are stored.
**
** With this routine, there is no guarantee that results will
** be stored in target. The result might be stored in some other
** register if it is convenient to do so. The calling function
** must check the return code and move the results to the desired
** register.
*/
int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
Vdbe *v = pParse->pVdbe; /* The VM under construction */
int op; /* The opcode being coded */
int inReg = target; /* Results stored in register inReg */
int regFree1 = 0; /* If non-zero free this temporary register */
int regFree2 = 0; /* If non-zero free this temporary register */
int r1, r2; /* Various register numbers */
Expr tempX; /* Temporary expression node */
int p5 = 0;
assert( target>0 && target<=pParse->nMem );
if( v==0 ){
assert( pParse->db->mallocFailed );
return 0;
}
expr_code_doover:
if( pExpr==0 ){
op = TK_NULL;
}else{
op = pExpr->op;
}
switch( op ){
case TK_AGG_COLUMN: {
AggInfo *pAggInfo = pExpr->pAggInfo;
struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
if( !pAggInfo->directMode ){
assert( pCol->iMem>0 );
return pCol->iMem;
}else if( pAggInfo->useSortingIdx ){
sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
pCol->iSorterColumn, target);
return target;
}
/* Otherwise, fall thru into the TK_COLUMN case */
}
case TK_COLUMN: {
int iTab = pExpr->iTable;
if( ExprHasProperty(pExpr, EP_FixedCol) ){
/* This COLUMN expression is really a constant due to WHERE clause
** constraints, and that constant is coded by the pExpr->pLeft
** expresssion. However, make sure the constant has the correct
** datatype by applying the Affinity of the table column to the
** constant.
*/
int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
int aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
if( aff>SQLITE_AFF_BLOB ){
static const char zAff[] = "B\000C\000D\000E";
assert( SQLITE_AFF_BLOB=='A' );
assert( SQLITE_AFF_TEXT=='B' );
if( iReg!=target ){
sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
iReg = target;
}
sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
&zAff[(aff-'B')*2], P4_STATIC);
}
return iReg;
}
if( iTab<0 ){
if( pParse->iSelfTab<0 ){
/* Other columns in the same row for CHECK constraints or
** generated columns or for inserting into partial index.
** The row is unpacked into registers beginning at
** 0-(pParse->iSelfTab). The rowid (if any) is in a register
** immediately prior to the first column.
*/
Column *pCol;
Table *pTab = pExpr->y.pTab;
int iSrc;
int iCol = pExpr->iColumn;
assert( pTab!=0 );
assert( iCol>=XN_ROWID );
assert( iCol<pExpr->y.pTab->nCol );
if( iCol<0 ){
return -1-pParse->iSelfTab;
}
pCol = pTab->aCol + iCol;
testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
if( pCol->colFlags & COLFLAG_GENERATED ){
if( pCol->colFlags & COLFLAG_BUSY ){
sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
pCol->zName);
return 0;
}
pCol->colFlags |= COLFLAG_BUSY;
if( pCol->colFlags & COLFLAG_NOTAVAIL ){
sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
}
pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
return iSrc;
}else
#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
if( pCol->affinity==SQLITE_AFF_REAL ){
sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
return target;
}else{
return iSrc;
}
}else{
/* Coding an expression that is part of an index where column names
** in the index refer to the table to which the index belongs */
iTab = pParse->iSelfTab - 1;
}
}
return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
pExpr->iColumn, iTab, target,
pExpr->op2);
}
case TK_INTEGER: {
codeInteger(pParse, pExpr, 0, target);
return target;
}
case TK_TRUEFALSE: {
sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
return target;
}
#ifndef SQLITE_OMIT_FLOATING_POINT
case TK_FLOAT: {
assert( !ExprHasProperty(pExpr, EP_IntValue) );
codeReal(v, pExpr->u.zToken, 0, target);
return target;
}
#endif
case TK_STRING: {
assert( !ExprHasProperty(pExpr, EP_IntValue) );
sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
return target;
}
case TK_NULL: {
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
return target;
}
#ifndef SQLITE_OMIT_BLOB_LITERAL
case TK_BLOB: {
int n;
const char *z;
char *zBlob;
assert( !ExprHasProperty(pExpr, EP_IntValue) );
assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
assert( pExpr->u.zToken[1]=='\'' );
z = &pExpr->u.zToken[2];
n = sqlite3Strlen30(z) - 1;
assert( z[n]=='\'' );
zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
return target;
}
#endif
case TK_VARIABLE: {
assert( !ExprHasProperty(pExpr, EP_IntValue) );
assert( pExpr->u.zToken!=0 );
assert( pExpr->u.zToken[0]!=0 );
sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
if( pExpr->u.zToken[1]!=0 ){
const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
}
return target;
}
case TK_REGISTER: {
return pExpr->iTable;
}
#ifndef SQLITE_OMIT_CAST
case TK_CAST: {
/* Expressions of the form: CAST(pLeft AS token) */
inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
if( inReg!=target ){
sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
inReg = target;
}
sqlite3VdbeAddOp2(v, OP_Cast, target,
sqlite3AffinityType(pExpr->u.zToken, 0));
return inReg;
}
#endif /* SQLITE_OMIT_CAST */
case TK_IS:
case TK_ISNOT:
op = (op==TK_IS) ? TK_EQ : TK_NE;
p5 = SQLITE_NULLEQ;
/* fall-through */
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_NE:
case TK_EQ: {
Expr *pLeft = pExpr->pLeft;
if( sqlite3ExprIsVector(pLeft) ){
codeVectorCompare(pParse, pExpr, target, op, p5);
}else{
r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
codeCompare(pParse, pLeft, pExpr->pRight, op,
r1, r2, inReg, SQLITE_STOREP2 | p5,
ExprHasProperty(pExpr,EP_Commuted));
assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
testcase( regFree1==0 );
testcase( regFree2==0 );
}
break;
}
case TK_AND:
case TK_OR:
case TK_PLUS:
case TK_STAR:
case TK_MINUS:
case TK_REM:
case TK_BITAND:
case TK_BITOR:
case TK_SLASH:
case TK_LSHIFT:
case TK_RSHIFT:
case TK_CONCAT: {
assert( TK_AND==OP_And ); testcase( op==TK_AND );
assert( TK_OR==OP_Or ); testcase( op==TK_OR );
assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
sqlite3VdbeAddOp3(v, op, r2, r1, target);
testcase( regFree1==0 );
testcase( regFree2==0 );
break;
}
case TK_UMINUS: {
Expr *pLeft = pExpr->pLeft;
assert( pLeft );
if( pLeft->op==TK_INTEGER ){
codeInteger(pParse, pLeft, 1, target);
return target;
#ifndef SQLITE_OMIT_FLOATING_POINT
}else if( pLeft->op==TK_FLOAT ){
assert( !ExprHasProperty(pExpr, EP_IntValue) );
codeReal(v, pLeft->u.zToken, 1, target);
return target;
#endif
}else{
tempX.op = TK_INTEGER;
tempX.flags = EP_IntValue|EP_TokenOnly;
tempX.u.iValue = 0;
r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2);
sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
testcase( regFree2==0 );
}
break;
}
case TK_BITNOT:
case TK_NOT: {
assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
testcase( regFree1==0 );
sqlite3VdbeAddOp2(v, op, r1, inReg);
break;
}
case TK_TRUTH: {
int isTrue; /* IS TRUE or IS NOT TRUE */
int bNormal; /* IS TRUE or IS FALSE */
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
testcase( regFree1==0 );
isTrue = sqlite3ExprTruthValue(pExpr->pRight);
bNormal = pExpr->op2==TK_IS;
testcase( isTrue && bNormal);
testcase( !isTrue && bNormal);
sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
break;
}
case TK_ISNULL:
case TK_NOTNULL: {
int addr;
assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
testcase( regFree1==0 );
addr = sqlite3VdbeAddOp1(v, op, r1);
VdbeCoverageIf(v, op==TK_ISNULL);
VdbeCoverageIf(v, op==TK_NOTNULL);
sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
sqlite3VdbeJumpHere(v, addr);
break;
}
case TK_AGG_FUNCTION: {
AggInfo *pInfo = pExpr->pAggInfo;
if( pInfo==0 ){
assert( !ExprHasProperty(pExpr, EP_IntValue) );
sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
}else{
return pInfo->aFunc[pExpr->iAgg].iMem;
}
break;
}
case TK_FUNCTION: {
ExprList *pFarg; /* List of function arguments */
int nFarg; /* Number of function arguments */
FuncDef *pDef; /* The function definition object */
const char *zId; /* The function name */
u32 constMask = 0; /* Mask of function arguments that are constant */
int i; /* Loop counter */
sqlite3 *db = pParse->db; /* The database connection */
u8 enc = ENC(db); /* The text encoding used by this database */
CollSeq *pColl = 0; /* A collating sequence */
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(pExpr, EP_WinFunc) ){
return pExpr->y.pWin->regResult;
}
#endif
if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
/* SQL functions can be expensive. So try to move constant functions
** out of the inner loop, even if that means an extra OP_Copy. */
return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
}
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
if( ExprHasProperty(pExpr, EP_TokenOnly) ){
pFarg = 0;
}else{
pFarg = pExpr->x.pList;
}
nFarg = pFarg ? pFarg->nExpr : 0;
assert( !ExprHasProperty(pExpr, EP_IntValue) );
zId = pExpr->u.zToken;
pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
if( pDef==0 && pParse->explain ){
pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
}
#endif
if( pDef==0 || pDef->xFinalize!=0 ){
sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
break;
}
/* Attempt a direct implementation of the built-in COALESCE() and
** IFNULL() functions. This avoids unnecessary evaluation of
** arguments past the first non-NULL argument.
*/
if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
int endCoalesce = sqlite3VdbeMakeLabel(pParse);
assert( nFarg>=2 );
sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
for(i=1; i<nFarg; i++){
sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
VdbeCoverage(v);
sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
}
sqlite3VdbeResolveLabel(v, endCoalesce);
break;
}
/* The UNLIKELY() function is a no-op. The result is the value
** of the first argument.
*/
if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
assert( nFarg>=1 );
return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
}
#ifdef SQLITE_DEBUG
/* The AFFINITY() function evaluates to a string that describes
** the type affinity of the argument. This is used for testing of
** the SQLite type logic.
*/
if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
char aff;
assert( nFarg==1 );
aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
sqlite3VdbeLoadString(v, target,
(aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
return target;
}
#endif
for(i=0; i<nFarg; i++){
if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
testcase( i==31 );
constMask |= MASKBIT32(i);
}
if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
}
}
if( pFarg ){
if( constMask ){
r1 = pParse->nMem+1;
pParse->nMem += nFarg;
}else{
r1 = sqlite3GetTempRange(pParse, nFarg);
}
/* For length() and typeof() functions with a column argument,
** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
** loading.
*/
if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
u8 exprOp;
assert( nFarg==1 );
assert( pFarg->a[0].pExpr!=0 );
exprOp = pFarg->a[0].pExpr->op;
if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
pFarg->a[0].pExpr->op2 =
pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
}
}
sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
}else{
r1 = 0;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Possibly overload the function if the first argument is
** a virtual table column.
**
** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
** second argument, not the first, as the argument to test to
** see if it is a column in a virtual table. This is done because
** the left operand of infix functions (the operand we want to
** control overloading) ends up as the second argument to the
** function. The expression "A glob B" is equivalent to
** "glob(B,A). We want to use the A in "A glob B" to test
** for function overloading. But we use the B term in "glob(B,A)".
*/
if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
}else if( nFarg>0 ){
pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
}
#endif
if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
if( !pColl ) pColl = db->pDfltColl;
sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
}
#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
Expr *pArg = pFarg->a[0].pExpr;
if( pArg->op==TK_COLUMN ){
sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
}else{
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
}
}else
#endif
{
sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
pDef, pExpr->op2);
}
if( nFarg && constMask==0 ){
sqlite3ReleaseTempRange(pParse, r1, nFarg);
}
return target;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_EXISTS:
case TK_SELECT: {
int nCol;
testcase( op==TK_EXISTS );
testcase( op==TK_SELECT );
if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
sqlite3SubselectError(pParse, nCol, 1);
}else{
return sqlite3CodeSubselect(pParse, pExpr);
}
break;
}
case TK_SELECT_COLUMN: {
int n;
if( pExpr->pLeft->iTable==0 ){
pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
}
assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
if( pExpr->iTable!=0
&& pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
){
sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
pExpr->iTable, n);
}
return pExpr->pLeft->iTable + pExpr->iColumn;
}
case TK_IN: {
int destIfFalse = sqlite3VdbeMakeLabel(pParse);
int destIfNull = sqlite3VdbeMakeLabel(pParse);
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
sqlite3VdbeResolveLabel(v, destIfFalse);
sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
sqlite3VdbeResolveLabel(v, destIfNull);
return target;
}
#endif /* SQLITE_OMIT_SUBQUERY */
/*
** x BETWEEN y AND z
**
** This is equivalent to
**
** x>=y AND x<=z
**
** X is stored in pExpr->pLeft.
** Y is stored in pExpr->pList->a[0].pExpr.
** Z is stored in pExpr->pList->a[1].pExpr.
*/
case TK_BETWEEN: {
exprCodeBetween(pParse, pExpr, target, 0, 0);
return target;
}
case TK_SPAN:
case TK_COLLATE:
case TK_UPLUS: {
pExpr = pExpr->pLeft;
goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
}
case TK_TRIGGER: {
/* If the opcode is TK_TRIGGER, then the expression is a reference
** to a column in the new.* or old.* pseudo-tables available to
** trigger programs. In this case Expr.iTable is set to 1 for the
** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
** is set to the column of the pseudo-table to read, or to -1 to
** read the rowid field.
**
** The expression is implemented using an OP_Param opcode. The p1
** parameter is set to 0 for an old.rowid reference, or to (i+1)
** to reference another column of the old.* pseudo-table, where
** i is the index of the column. For a new.rowid reference, p1 is
** set to (n+1), where n is the number of columns in each pseudo-table.
** For a reference to any other column in the new.* pseudo-table, p1
** is set to (n+2+i), where n and i are as defined previously. For
** example, if the table on which triggers are being fired is
** declared as:
**
** CREATE TABLE t1(a, b);
**
** Then p1 is interpreted as follows:
**
** p1==0 -> old.rowid p1==3 -> new.rowid
** p1==1 -> old.a p1==4 -> new.a
** p1==2 -> old.b p1==5 -> new.b
*/
Table *pTab = pExpr->y.pTab;
int iCol = pExpr->iColumn;
int p1 = pExpr->iTable * (pTab->nCol+1) + 1
+ (iCol>=0 ? sqlite3TableColumnToStorage(pTab, iCol) : -1);
assert( pExpr->iTable==0 || pExpr->iTable==1 );
assert( iCol>=-1 && iCol<pTab->nCol );
assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
assert( p1>=0 && p1<(pTab->nCol*2+2) );
sqlite3VdbeAddOp2(v, OP_Param, p1, target);
VdbeComment((v, "r[%d]=%s.%s", target,
(pExpr->iTable ? "new" : "old"),
(pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
));
#ifndef SQLITE_OMIT_FLOATING_POINT
/* If the column has REAL affinity, it may currently be stored as an
** integer. Use OP_RealAffinity to make sure it is really real.
**
** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
** floating point when extracting it from the record. */
if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
}
#endif
break;
}
case TK_VECTOR: {
sqlite3ErrorMsg(pParse, "row value misused");
break;
}
/* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
** that derive from the right-hand table of a LEFT JOIN. The
** Expr.iTable value is the table number for the right-hand table.
** The expression is only evaluated if that table is not currently
** on a LEFT JOIN NULL row.
*/
case TK_IF_NULL_ROW: {
int addrINR;
u8 okConstFactor = pParse->okConstFactor;
addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
/* Temporarily disable factoring of constant expressions, since
** even though expressions may appear to be constant, they are not
** really constant because they originate from the right-hand side
** of a LEFT JOIN. */
pParse->okConstFactor = 0;
inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
pParse->okConstFactor = okConstFactor;
sqlite3VdbeJumpHere(v, addrINR);
sqlite3VdbeChangeP3(v, addrINR, inReg);
break;
}
/*
** Form A:
** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
**
** Form B:
** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
**
** Form A is can be transformed into the equivalent form B as follows:
** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
** WHEN x=eN THEN rN ELSE y END
**
** X (if it exists) is in pExpr->pLeft.
** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
** odd. The Y is also optional. If the number of elements in x.pList
** is even, then Y is omitted and the "otherwise" result is NULL.
** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
**
** The result of the expression is the Ri for the first matching Ei,
** or if there is no matching Ei, the ELSE term Y, or if there is
** no ELSE term, NULL.
*/
default: assert( op==TK_CASE ); {
int endLabel; /* GOTO label for end of CASE stmt */
int nextCase; /* GOTO label for next WHEN clause */
int nExpr; /* 2x number of WHEN terms */
int i; /* Loop counter */
ExprList *pEList; /* List of WHEN terms */
struct ExprList_item *aListelem; /* Array of WHEN terms */
Expr opCompare; /* The X==Ei expression */
Expr *pX; /* The X expression */
Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
Expr *pDel = 0;
sqlite3 *db = pParse->db;
assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
assert(pExpr->x.pList->nExpr > 0);
pEList = pExpr->x.pList;
aListelem = pEList->a;
nExpr = pEList->nExpr;
endLabel = sqlite3VdbeMakeLabel(pParse);
if( (pX = pExpr->pLeft)!=0 ){
pDel = sqlite3ExprDup(db, pX, 0);
if( db->mallocFailed ){
sqlite3ExprDelete(db, pDel);
break;
}
testcase( pX->op==TK_COLUMN );
exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1));
testcase( regFree1==0 );
memset(&opCompare, 0, sizeof(opCompare));
opCompare.op = TK_EQ;
opCompare.pLeft = pDel;
pTest = &opCompare;
/* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
** The value in regFree1 might get SCopy-ed into the file result.
** So make sure that the regFree1 register is not reused for other
** purposes and possibly overwritten. */
regFree1 = 0;
}
for(i=0; i<nExpr-1; i=i+2){
if( pX ){
assert( pTest!=0 );
opCompare.pRight = aListelem[i].pExpr;
}else{
pTest = aListelem[i].pExpr;
}
nextCase = sqlite3VdbeMakeLabel(pParse);
testcase( pTest->op==TK_COLUMN );
sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
sqlite3VdbeGoto(v, endLabel);
sqlite3VdbeResolveLabel(v, nextCase);
}
if( (nExpr&1)!=0 ){
sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
}else{
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
}
sqlite3ExprDelete(db, pDel);
sqlite3VdbeResolveLabel(v, endLabel);
break;
}
#ifndef SQLITE_OMIT_TRIGGER
case TK_RAISE: {
assert( pExpr->affExpr==OE_Rollback
|| pExpr->affExpr==OE_Abort
|| pExpr->affExpr==OE_Fail
|| pExpr->affExpr==OE_Ignore
);
if( !pParse->pTriggerTab ){
sqlite3ErrorMsg(pParse,
"RAISE() may only be used within a trigger-program");
return 0;
}
if( pExpr->affExpr==OE_Abort ){
sqlite3MayAbort(pParse);
}
assert( !ExprHasProperty(pExpr, EP_IntValue) );
if( pExpr->affExpr==OE_Ignore ){
sqlite3VdbeAddOp4(
v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
VdbeCoverage(v);
}else{
sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
pExpr->affExpr, pExpr->u.zToken, 0, 0);
}
break;
}
#endif
}
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
return inReg;
}
/*
** Factor out the code of the given expression to initialization time.
**
** If regDest>=0 then the result is always stored in that register and the
** result is not reusable. If regDest<0 then this routine is free to
** store the value whereever it wants. The register where the expression
** is stored is returned. When regDest<0, two identical expressions will
** code to the same register.
*/
int sqlite3ExprCodeAtInit(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* The expression to code when the VDBE initializes */
int regDest /* Store the value in this register */
){
ExprList *p;
assert( ConstFactorOk(pParse) );
p = pParse->pConstExpr;
if( regDest<0 && p ){
struct ExprList_item *pItem;
int i;
for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
return pItem->u.iConstExprReg;
}
}
}
pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
p = sqlite3ExprListAppend(pParse, p, pExpr);
if( p ){
struct ExprList_item *pItem = &p->a[p->nExpr-1];
pItem->reusable = regDest<0;
if( regDest<0 ) regDest = ++pParse->nMem;
pItem->u.iConstExprReg = regDest;
}
pParse->pConstExpr = p;
return regDest;
}
/*
** Generate code to evaluate an expression and store the results
** into a register. Return the register number where the results
** are stored.
**
** If the register is a temporary register that can be deallocated,
** then write its number into *pReg. If the result register is not
** a temporary, then set *pReg to zero.
**
** If pExpr is a constant, then this routine might generate this
** code to fill the register in the initialization section of the
** VDBE program, in order to factor it out of the evaluation loop.
*/
int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
int r2;
pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
if( ConstFactorOk(pParse)
&& pExpr->op!=TK_REGISTER
&& sqlite3ExprIsConstantNotJoin(pExpr)
){
*pReg = 0;
r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
}else{
int r1 = sqlite3GetTempReg(pParse);
r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
if( r2==r1 ){
*pReg = r1;
}else{
sqlite3ReleaseTempReg(pParse, r1);
*pReg = 0;
}
}
return r2;
}
/*
** Generate code that will evaluate expression pExpr and store the
** results in register target. The results are guaranteed to appear
** in register target.
*/
void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
int inReg;
assert( target>0 && target<=pParse->nMem );
inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
if( inReg!=target && pParse->pVdbe ){
sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
}
}
/*
** Make a transient copy of expression pExpr and then code it using
** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
** except that the input expression is guaranteed to be unchanged.
*/
void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
sqlite3 *db = pParse->db;
pExpr = sqlite3ExprDup(db, pExpr, 0);
if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
sqlite3ExprDelete(db, pExpr);
}
/*
** Generate code that will evaluate expression pExpr and store the
** results in register target. The results are guaranteed to appear
** in register target. If the expression is constant, then this routine
** might choose to code the expression at initialization time.
*/
void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
sqlite3ExprCodeAtInit(pParse, pExpr, target);
}else{
sqlite3ExprCode(pParse, pExpr, target);
}
}
/*
** Generate code that pushes the value of every element of the given
** expression list into a sequence of registers beginning at target.
**
** Return the number of elements evaluated. The number returned will
** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
** is defined.
**
** The SQLITE_ECEL_DUP flag prevents the arguments from being
** filled using OP_SCopy. OP_Copy must be used instead.
**
** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
** factored out into initialization code.
**
** The SQLITE_ECEL_REF flag means that expressions in the list with
** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
** in registers at srcReg, and so the value can be copied from there.
** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
** are simply omitted rather than being copied from srcReg.
*/
int sqlite3ExprCodeExprList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* The expression list to be coded */
int target, /* Where to write results */
int srcReg, /* Source registers if SQLITE_ECEL_REF */
u8 flags /* SQLITE_ECEL_* flags */
){
struct ExprList_item *pItem;
int i, j, n;
u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
Vdbe *v = pParse->pVdbe;
assert( pList!=0 );
assert( target>0 );
assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
n = pList->nExpr;
if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
for(pItem=pList->a, i=0; i<n; i++, pItem++){
Expr *pExpr = pItem->pExpr;
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( pItem->bSorterRef ){
i--;
n--;
}else
#endif
if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
if( flags & SQLITE_ECEL_OMITREF ){
i--;
n--;
}else{
sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
}
}else if( (flags & SQLITE_ECEL_FACTOR)!=0
&& sqlite3ExprIsConstantNotJoin(pExpr)
){
sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
}else{
int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
if( inReg!=target+i ){
VdbeOp *pOp;
if( copyOp==OP_Copy
&& (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
&& pOp->p1+pOp->p3+1==inReg
&& pOp->p2+pOp->p3+1==target+i
){
pOp->p3++;
}else{
sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
}
}
}
}
return n;
}
/*
** Generate code for a BETWEEN operator.
**
** x BETWEEN y AND z
**
** The above is equivalent to
**
** x>=y AND x<=z
**
** Code it as such, taking care to do the common subexpression
** elimination of x.
**
** The xJumpIf parameter determines details:
**
** NULL: Store the boolean result in reg[dest]
** sqlite3ExprIfTrue: Jump to dest if true
** sqlite3ExprIfFalse: Jump to dest if false
**
** The jumpIfNull parameter is ignored if xJumpIf is NULL.
*/
static void exprCodeBetween(
Parse *pParse, /* Parsing and code generating context */
Expr *pExpr, /* The BETWEEN expression */
int dest, /* Jump destination or storage location */
void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
int jumpIfNull /* Take the jump if the BETWEEN is NULL */
){
Expr exprAnd; /* The AND operator in x>=y AND x<=z */
Expr compLeft; /* The x>=y term */
Expr compRight; /* The x<=z term */
int regFree1 = 0; /* Temporary use register */
Expr *pDel = 0;
sqlite3 *db = pParse->db;
memset(&compLeft, 0, sizeof(Expr));
memset(&compRight, 0, sizeof(Expr));
memset(&exprAnd, 0, sizeof(Expr));
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
if( db->mallocFailed==0 ){
exprAnd.op = TK_AND;
exprAnd.pLeft = &compLeft;
exprAnd.pRight = &compRight;
compLeft.op = TK_GE;
compLeft.pLeft = pDel;
compLeft.pRight = pExpr->x.pList->a[0].pExpr;
compRight.op = TK_LE;
compRight.pLeft = pDel;
compRight.pRight = pExpr->x.pList->a[1].pExpr;
exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1));
if( xJump ){
xJump(pParse, &exprAnd, dest, jumpIfNull);
}else{
/* Mark the expression is being from the ON or USING clause of a join
** so that the sqlite3ExprCodeTarget() routine will not attempt to move
** it into the Parse.pConstExpr list. We should use a new bit for this,
** for clarity, but we are out of bits in the Expr.flags field so we
** have to reuse the EP_FromJoin bit. Bummer. */
pDel->flags |= EP_FromJoin;
sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
}
sqlite3ReleaseTempReg(pParse, regFree1);
}
sqlite3ExprDelete(db, pDel);
/* Ensure adequate test coverage */
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
testcase( xJump==0 );
}
/*
** Generate code for a boolean expression such that a jump is made
** to the label "dest" if the expression is true but execution
** continues straight thru if the expression is false.
**
** If the expression evaluates to NULL (neither true nor false), then
** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
**
** This code depends on the fact that certain token values (ex: TK_EQ)
** are the same as opcode values (ex: OP_Eq) that implement the corresponding
** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
** the make process cause these values to align. Assert()s in the code
** below verify that the numbers are aligned correctly.
*/
void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
Vdbe *v = pParse->pVdbe;
int op = 0;
int regFree1 = 0;
int regFree2 = 0;
int r1, r2;
assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
if( NEVER(pExpr==0) ) return; /* No way this can happen */
op = pExpr->op;
switch( op ){
case TK_AND:
case TK_OR: {
Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
if( pAlt!=pExpr ){
sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
}else if( op==TK_AND ){
int d2 = sqlite3VdbeMakeLabel(pParse);
testcase( jumpIfNull==0 );
sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
jumpIfNull^SQLITE_JUMPIFNULL);
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
sqlite3VdbeResolveLabel(v, d2);
}else{
testcase( jumpIfNull==0 );
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
}
break;
}
case TK_NOT: {
testcase( jumpIfNull==0 );
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
break;
}
case TK_TRUTH: {
int isNot; /* IS NOT TRUE or IS NOT FALSE */
int isTrue; /* IS TRUE or IS NOT TRUE */
testcase( jumpIfNull==0 );
isNot = pExpr->op2==TK_ISNOT;
isTrue = sqlite3ExprTruthValue(pExpr->pRight);
testcase( isTrue && isNot );
testcase( !isTrue && isNot );
if( isTrue ^ isNot ){
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
isNot ? SQLITE_JUMPIFNULL : 0);
}else{
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
isNot ? SQLITE_JUMPIFNULL : 0);
}
break;
}
case TK_IS:
case TK_ISNOT:
testcase( op==TK_IS );
testcase( op==TK_ISNOT );
op = (op==TK_IS) ? TK_EQ : TK_NE;
jumpIfNull = SQLITE_NULLEQ;
/* Fall thru */
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_NE:
case TK_EQ: {
if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
testcase( jumpIfNull==0 );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
testcase( regFree1==0 );
testcase( regFree2==0 );
break;
}
case TK_ISNULL:
case TK_NOTNULL: {
assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
sqlite3VdbeAddOp2(v, op, r1, dest);
VdbeCoverageIf(v, op==TK_ISNULL);
VdbeCoverageIf(v, op==TK_NOTNULL);
testcase( regFree1==0 );
break;
}
case TK_BETWEEN: {
testcase( jumpIfNull==0 );
exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_IN: {
int destIfFalse = sqlite3VdbeMakeLabel(pParse);
int destIfNull = jumpIfNull ? dest : destIfFalse;
sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
sqlite3VdbeGoto(v, dest);
sqlite3VdbeResolveLabel(v, destIfFalse);
break;
}
#endif
default: {
default_expr:
if( ExprAlwaysTrue(pExpr) ){
sqlite3VdbeGoto(v, dest);
}else if( ExprAlwaysFalse(pExpr) ){
/* No-op */
}else{
r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
VdbeCoverage(v);
testcase( regFree1==0 );
testcase( jumpIfNull==0 );
}
break;
}
}
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
}
/*
** Generate code for a boolean expression such that a jump is made
** to the label "dest" if the expression is false but execution
** continues straight thru if the expression is true.
**
** If the expression evaluates to NULL (neither true nor false) then
** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
** is 0.
*/
void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
Vdbe *v = pParse->pVdbe;
int op = 0;
int regFree1 = 0;
int regFree2 = 0;
int r1, r2;
assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
if( pExpr==0 ) return;
/* The value of pExpr->op and op are related as follows:
**
** pExpr->op op
** --------- ----------
** TK_ISNULL OP_NotNull
** TK_NOTNULL OP_IsNull
** TK_NE OP_Eq
** TK_EQ OP_Ne
** TK_GT OP_Le
** TK_LE OP_Gt
** TK_GE OP_Lt
** TK_LT OP_Ge
**
** For other values of pExpr->op, op is undefined and unused.
** The value of TK_ and OP_ constants are arranged such that we
** can compute the mapping above using the following expression.
** Assert()s verify that the computation is correct.
*/
op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
/* Verify correct alignment of TK_ and OP_ constants
*/
assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
assert( pExpr->op!=TK_NE || op==OP_Eq );
assert( pExpr->op!=TK_EQ || op==OP_Ne );
assert( pExpr->op!=TK_LT || op==OP_Ge );
assert( pExpr->op!=TK_LE || op==OP_Gt );
assert( pExpr->op!=TK_GT || op==OP_Le );
assert( pExpr->op!=TK_GE || op==OP_Lt );
switch( pExpr->op ){
case TK_AND:
case TK_OR: {
Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
if( pAlt!=pExpr ){
sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
}else if( pExpr->op==TK_AND ){
testcase( jumpIfNull==0 );
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
}else{
int d2 = sqlite3VdbeMakeLabel(pParse);
testcase( jumpIfNull==0 );
sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
jumpIfNull^SQLITE_JUMPIFNULL);
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
sqlite3VdbeResolveLabel(v, d2);
}
break;
}
case TK_NOT: {
testcase( jumpIfNull==0 );
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
break;
}
case TK_TRUTH: {
int isNot; /* IS NOT TRUE or IS NOT FALSE */
int isTrue; /* IS TRUE or IS NOT TRUE */
testcase( jumpIfNull==0 );
isNot = pExpr->op2==TK_ISNOT;
isTrue = sqlite3ExprTruthValue(pExpr->pRight);
testcase( isTrue && isNot );
testcase( !isTrue && isNot );
if( isTrue ^ isNot ){
/* IS TRUE and IS NOT FALSE */
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
isNot ? 0 : SQLITE_JUMPIFNULL);
}else{
/* IS FALSE and IS NOT TRUE */
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
isNot ? 0 : SQLITE_JUMPIFNULL);
}
break;
}
case TK_IS:
case TK_ISNOT:
testcase( pExpr->op==TK_IS );
testcase( pExpr->op==TK_ISNOT );
op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
jumpIfNull = SQLITE_NULLEQ;
/* Fall thru */
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_NE:
case TK_EQ: {
if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
testcase( jumpIfNull==0 );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
testcase( regFree1==0 );
testcase( regFree2==0 );
break;
}
case TK_ISNULL:
case TK_NOTNULL: {
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
sqlite3VdbeAddOp2(v, op, r1, dest);
testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
testcase( regFree1==0 );
break;
}
case TK_BETWEEN: {
testcase( jumpIfNull==0 );
exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_IN: {
if( jumpIfNull ){
sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
}else{
int destIfNull = sqlite3VdbeMakeLabel(pParse);
sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
sqlite3VdbeResolveLabel(v, destIfNull);
}
break;
}
#endif
default: {
default_expr:
if( ExprAlwaysFalse(pExpr) ){
sqlite3VdbeGoto(v, dest);
}else if( ExprAlwaysTrue(pExpr) ){
/* no-op */
}else{
r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
VdbeCoverage(v);
testcase( regFree1==0 );
testcase( jumpIfNull==0 );
}
break;
}
}
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
}
/*
** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
** code generation, and that copy is deleted after code generation. This
** ensures that the original pExpr is unchanged.
*/
void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
sqlite3 *db = pParse->db;
Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
if( db->mallocFailed==0 ){
sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
}
sqlite3ExprDelete(db, pCopy);
}
/*
** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
** type of expression.
**
** If pExpr is a simple SQL value - an integer, real, string, blob
** or NULL value - then the VDBE currently being prepared is configured
** to re-prepare each time a new value is bound to variable pVar.
**
** Additionally, if pExpr is a simple SQL value and the value is the
** same as that currently bound to variable pVar, non-zero is returned.
** Otherwise, if the values are not the same or if pExpr is not a simple
** SQL value, zero is returned.
*/
static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
int res = 0;
int iVar;
sqlite3_value *pL, *pR = 0;
sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
if( pR ){
iVar = pVar->iColumn;
sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
if( pL ){
if( sqlite3_value_type(pL)==SQLITE_TEXT ){
sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
}
res = 0==sqlite3MemCompare(pL, pR, 0);
}
sqlite3ValueFree(pR);
sqlite3ValueFree(pL);
}
return res;
}
/*
** Do a deep comparison of two expression trees. Return 0 if the two
** expressions are completely identical. Return 1 if they differ only
** by a COLLATE operator at the top level. Return 2 if there are differences
** other than the top-level COLLATE operator.
**
** If any subelement of pB has Expr.iTable==(-1) then it is allowed
** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
**
** The pA side might be using TK_REGISTER. If that is the case and pB is
** not using TK_REGISTER but is otherwise equivalent, then still return 0.
**
** Sometimes this routine will return 2 even if the two expressions
** really are equivalent. If we cannot prove that the expressions are
** identical, we return 2 just to be safe. So if this routine
** returns 2, then you do not really know for certain if the two
** expressions are the same. But if you get a 0 or 1 return, then you
** can be sure the expressions are the same. In the places where
** this routine is used, it does not hurt to get an extra 2 - that
** just might result in some slightly slower code. But returning
** an incorrect 0 or 1 could lead to a malfunction.
**
** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
** pParse->pReprepare can be matched against literals in pB. The
** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
** If pParse is NULL (the normal case) then any TK_VARIABLE term in
** Argument pParse should normally be NULL. If it is not NULL and pA or
** pB causes a return value of 2.
*/
int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
u32 combinedFlags;
if( pA==0 || pB==0 ){
return pB==pA ? 0 : 2;
}
if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
return 0;
}
combinedFlags = pA->flags | pB->flags;
if( combinedFlags & EP_IntValue ){
if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
return 0;
}
return 2;
}
if( pA->op!=pB->op || pA->op==TK_RAISE ){
if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
return 1;
}
if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
return 1;
}
return 2;
}
if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
#ifndef SQLITE_OMIT_WINDOWFUNC
assert( pA->op==pB->op );
if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
return 2;
}
if( ExprHasProperty(pA,EP_WinFunc) ){
if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
return 2;
}
}
#endif
}else if( pA->op==TK_NULL ){
return 0;
}else if( pA->op==TK_COLLATE ){
if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
}else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
return 2;
}
}
if( (pA->flags & (EP_Distinct|EP_Commuted))
!= (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
if( (combinedFlags & EP_TokenOnly)==0 ){
if( combinedFlags & EP_xIsSelect ) return 2;
if( (combinedFlags & EP_FixedCol)==0
&& sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
if( pA->op!=TK_STRING
&& pA->op!=TK_TRUEFALSE
&& (combinedFlags & EP_Reduced)==0
){
if( pA->iColumn!=pB->iColumn ) return 2;
if( pA->op2!=pB->op2 ){
if( pA->op==TK_TRUTH ) return 2;
if( pA->op==TK_FUNCTION && iTab<0 ){
/* Ex: CREATE TABLE t1(a CHECK( a<julianday('now') ));
** INSERT INTO t1(a) VALUES(julianday('now')+10);
** Without this test, sqlite3ExprCodeAtInit() will run on the
** the julianday() of INSERT first, and remember that expression.
** Then sqlite3ExprCodeInit() will see the julianday() in the CHECK
** constraint as redundant, reusing the one from the INSERT, even
** though the julianday() in INSERT lacks the critical NC_IsCheck
** flag. See ticket [830277d9db6c3ba1] (2019-10-30)
*/
return 2;
}
}
if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
return 2;
}
}
}
return 0;
}
/*
** Compare two ExprList objects. Return 0 if they are identical and
** non-zero if they differ in any way.
**
** If any subelement of pB has Expr.iTable==(-1) then it is allowed
** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
**
** This routine might return non-zero for equivalent ExprLists. The
** only consequence will be disabled optimizations. But this routine
** must never return 0 if the two ExprList objects are different, or
** a malfunction will result.
**
** Two NULL pointers are considered to be the same. But a NULL pointer
** always differs from a non-NULL pointer.
*/
int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
int i;
if( pA==0 && pB==0 ) return 0;
if( pA==0 || pB==0 ) return 1;
if( pA->nExpr!=pB->nExpr ) return 1;
for(i=0; i<pA->nExpr; i++){
Expr *pExprA = pA->a[i].pExpr;
Expr *pExprB = pB->a[i].pExpr;
if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
}
return 0;
}
/*
** Like sqlite3ExprCompare() except COLLATE operators at the top-level
** are ignored.
*/
int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
return sqlite3ExprCompare(0,
sqlite3ExprSkipCollateAndLikely(pA),
sqlite3ExprSkipCollateAndLikely(pB),
iTab);
}
/*
** Return non-zero if Expr p can only be true if pNN is not NULL.
**
** Or if seenNot is true, return non-zero if Expr p can only be
** non-NULL if pNN is not NULL
*/
static int exprImpliesNotNull(
Parse *pParse, /* Parsing context */
Expr *p, /* The expression to be checked */
Expr *pNN, /* The expression that is NOT NULL */
int iTab, /* Table being evaluated */
int seenNot /* Return true only if p can be any non-NULL value */
){
assert( p );
assert( pNN );
if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
return pNN->op!=TK_NULL;
}
switch( p->op ){
case TK_IN: {
if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
assert( ExprHasProperty(p,EP_xIsSelect)
|| (p->x.pList!=0 && p->x.pList->nExpr>0) );
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
case TK_BETWEEN: {
ExprList *pList = p->x.pList;
assert( pList!=0 );
assert( pList->nExpr==2 );
if( seenNot ) return 0;
if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
|| exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
){
return 1;
}
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
case TK_EQ:
case TK_NE:
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_PLUS:
case TK_MINUS:
case TK_BITOR:
case TK_LSHIFT:
case TK_RSHIFT:
case TK_CONCAT:
seenNot = 1;
/* Fall thru */
case TK_STAR:
case TK_REM:
case TK_BITAND:
case TK_SLASH: {
if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
/* Fall thru into the next case */
}
case TK_SPAN:
case TK_COLLATE:
case TK_UPLUS:
case TK_UMINUS: {
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
}
case TK_TRUTH: {
if( seenNot ) return 0;
if( p->op2!=TK_IS ) return 0;
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
case TK_BITNOT:
case TK_NOT: {
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
}
return 0;
}
/*
** Return true if we can prove the pE2 will always be true if pE1 is
** true. Return false if we cannot complete the proof or if pE2 might
** be false. Examples:
**
** pE1: x==5 pE2: x==5 Result: true
** pE1: x>0 pE2: x==5 Result: false
** pE1: x=21 pE2: x=21 OR y=43 Result: true
** pE1: x!=123 pE2: x IS NOT NULL Result: true
** pE1: x!=?1 pE2: x IS NOT NULL Result: true
** pE1: x IS NULL pE2: x IS NOT NULL Result: false
** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
**
** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
** Expr.iTable<0 then assume a table number given by iTab.
**
** If pParse is not NULL, then the values of bound variables in pE1 are
** compared against literal values in pE2 and pParse->pVdbe->expmask is
** modified to record which bound variables are referenced. If pParse
** is NULL, then false will be returned if pE1 contains any bound variables.
**
** When in doubt, return false. Returning true might give a performance
** improvement. Returning false might cause a performance reduction, but
** it will always give the correct answer and is hence always safe.
*/
int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
return 1;
}
if( pE2->op==TK_OR
&& (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
|| sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
){
return 1;
}
if( pE2->op==TK_NOTNULL
&& exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
){
return 1;
}
return 0;
}
/*
** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
** If the expression node requires that the table at pWalker->iCur
** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
**
** This routine controls an optimization. False positives (setting
** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
** (never setting pWalker->eCode) is a harmless missed optimization.
*/
static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
testcase( pExpr->op==TK_AGG_COLUMN );
testcase( pExpr->op==TK_AGG_FUNCTION );
if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
switch( pExpr->op ){
case TK_ISNOT:
case TK_ISNULL:
case TK_NOTNULL:
case TK_IS:
case TK_OR:
case TK_VECTOR:
case TK_CASE:
case TK_IN:
case TK_FUNCTION:
case TK_TRUTH:
testcase( pExpr->op==TK_ISNOT );
testcase( pExpr->op==TK_ISNULL );
testcase( pExpr->op==TK_NOTNULL );
testcase( pExpr->op==TK_IS );
testcase( pExpr->op==TK_OR );
testcase( pExpr->op==TK_VECTOR );
testcase( pExpr->op==TK_CASE );
testcase( pExpr->op==TK_IN );
testcase( pExpr->op==TK_FUNCTION );
testcase( pExpr->op==TK_TRUTH );
return WRC_Prune;
case TK_COLUMN:
if( pWalker->u.iCur==pExpr->iTable ){
pWalker->eCode = 1;
return WRC_Abort;
}
return WRC_Prune;
case TK_AND:
assert( pWalker->eCode==0 );
sqlite3WalkExpr(pWalker, pExpr->pLeft);
if( pWalker->eCode ){
pWalker->eCode = 0;
sqlite3WalkExpr(pWalker, pExpr->pRight);
}
return WRC_Prune;
case TK_BETWEEN:
sqlite3WalkExpr(pWalker, pExpr->pLeft);
return WRC_Prune;
/* Virtual tables are allowed to use constraints like x=NULL. So
** a term of the form x=y does not prove that y is not null if x
** is the column of a virtual table */
case TK_EQ:
case TK_NE:
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
testcase( pExpr->op==TK_EQ );
testcase( pExpr->op==TK_NE );
testcase( pExpr->op==TK_LT );
testcase( pExpr->op==TK_LE );
testcase( pExpr->op==TK_GT );
testcase( pExpr->op==TK_GE );
if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
|| (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
){
return WRC_Prune;
}
default:
return WRC_Continue;
}
}
/*
** Return true (non-zero) if expression p can only be true if at least
** one column of table iTab is non-null. In other words, return true
** if expression p will always be NULL or false if every column of iTab
** is NULL.
**
** False negatives are acceptable. In other words, it is ok to return
** zero even if expression p will never be true of every column of iTab
** is NULL. A false negative is merely a missed optimization opportunity.
**
** False positives are not allowed, however. A false positive may result
** in an incorrect answer.
**
** Terms of p that are marked with EP_FromJoin (and hence that come from
** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
**
** This routine is used to check if a LEFT JOIN can be converted into
** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
** clause requires that some column of the right table of the LEFT JOIN
** be non-NULL, then the LEFT JOIN can be safely converted into an
** ordinary join.
*/
int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
Walker w;
p = sqlite3ExprSkipCollateAndLikely(p);
if( p==0 ) return 0;
if( p->op==TK_NOTNULL ){
p = p->pLeft;
}else{
while( p->op==TK_AND ){
if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
p = p->pRight;
}
}
w.xExprCallback = impliesNotNullRow;
w.xSelectCallback = 0;
w.xSelectCallback2 = 0;
w.eCode = 0;
w.u.iCur = iTab;
sqlite3WalkExpr(&w, p);
return w.eCode;
}
/*
** An instance of the following structure is used by the tree walker
** to determine if an expression can be evaluated by reference to the
** index only, without having to do a search for the corresponding
** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
** is the cursor for the table.
*/
struct IdxCover {
Index *pIdx; /* The index to be tested for coverage */
int iCur; /* Cursor number for the table corresponding to the index */
};
/*
** Check to see if there are references to columns in table
** pWalker->u.pIdxCover->iCur can be satisfied using the index
** pWalker->u.pIdxCover->pIdx.
*/
static int exprIdxCover(Walker *pWalker, Expr *pExpr){
if( pExpr->op==TK_COLUMN
&& pExpr->iTable==pWalker->u.pIdxCover->iCur
&& sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
){
pWalker->eCode = 1;
return WRC_Abort;
}
return WRC_Continue;
}
/*
** Determine if an index pIdx on table with cursor iCur contains will
** the expression pExpr. Return true if the index does cover the
** expression and false if the pExpr expression references table columns
** that are not found in the index pIdx.
**
** An index covering an expression means that the expression can be
** evaluated using only the index and without having to lookup the
** corresponding table entry.
*/
int sqlite3ExprCoveredByIndex(
Expr *pExpr, /* The index to be tested */
int iCur, /* The cursor number for the corresponding table */
Index *pIdx /* The index that might be used for coverage */
){
Walker w;
struct IdxCover xcov;
memset(&w, 0, sizeof(w));
xcov.iCur = iCur;
xcov.pIdx = pIdx;
w.xExprCallback = exprIdxCover;
w.u.pIdxCover = &xcov;
sqlite3WalkExpr(&w, pExpr);
return !w.eCode;
}
/*
** An instance of the following structure is used by the tree walker
** to count references to table columns in the arguments of an
** aggregate function, in order to implement the
** sqlite3FunctionThisSrc() routine.
*/
struct SrcCount {
SrcList *pSrc; /* One particular FROM clause in a nested query */
int nThis; /* Number of references to columns in pSrcList */
int nOther; /* Number of references to columns in other FROM clauses */
};
/*
** Count the number of references to columns.
*/
static int exprSrcCount(Walker *pWalker, Expr *pExpr){
/* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
** is always called before sqlite3ExprAnalyzeAggregates() and so the
** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
** sqlite3FunctionUsesThisSrc() is used differently in the future, the
** NEVER() will need to be removed. */
if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
int i;
struct SrcCount *p = pWalker->u.pSrcCount;
SrcList *pSrc = p->pSrc;
int nSrc = pSrc ? pSrc->nSrc : 0;
for(i=0; i<nSrc; i++){
if( pExpr->iTable==pSrc->a[i].iCursor ) break;
}
if( i<nSrc ){
p->nThis++;
}else if( nSrc==0 || pExpr->iTable<pSrc->a[0].iCursor ){
/* In a well-formed parse tree (no name resolution errors),
** TK_COLUMN nodes with smaller Expr.iTable values are in an
** outer context. Those are the only ones to count as "other" */
p->nOther++;
}
}
return WRC_Continue;
}
/*
** Determine if any of the arguments to the pExpr Function reference
** pSrcList. Return true if they do. Also return true if the function
** has no arguments or has only constant arguments. Return false if pExpr
** references columns but not columns of tables found in pSrcList.
*/
int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
Walker w;
struct SrcCount cnt;
assert( pExpr->op==TK_AGG_FUNCTION );
memset(&w, 0, sizeof(w));
w.xExprCallback = exprSrcCount;
w.xSelectCallback = sqlite3SelectWalkNoop;
w.u.pSrcCount = &cnt;
cnt.pSrc = pSrcList;
cnt.nThis = 0;
cnt.nOther = 0;
sqlite3WalkExprList(&w, pExpr->x.pList);
return cnt.nThis>0 || cnt.nOther==0;
}
/*
** Add a new element to the pAggInfo->aCol[] array. Return the index of
** the new element. Return a negative number if malloc fails.
*/
static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
int i;
pInfo->aCol = sqlite3ArrayAllocate(
db,
pInfo->aCol,
sizeof(pInfo->aCol[0]),
&pInfo->nColumn,
&i
);
return i;
}
/*
** Add a new element to the pAggInfo->aFunc[] array. Return the index of
** the new element. Return a negative number if malloc fails.
*/
static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
int i;
pInfo->aFunc = sqlite3ArrayAllocate(
db,
pInfo->aFunc,
sizeof(pInfo->aFunc[0]),
&pInfo->nFunc,
&i
);
return i;
}
/*
** This is the xExprCallback for a tree walker. It is used to
** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
** for additional information.
*/
static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
int i;
NameContext *pNC = pWalker->u.pNC;
Parse *pParse = pNC->pParse;
SrcList *pSrcList = pNC->pSrcList;
AggInfo *pAggInfo = pNC->uNC.pAggInfo;
assert( pNC->ncFlags & NC_UAggInfo );
switch( pExpr->op ){
case TK_AGG_COLUMN:
case TK_COLUMN: {
testcase( pExpr->op==TK_AGG_COLUMN );
testcase( pExpr->op==TK_COLUMN );
/* Check to see if the column is in one of the tables in the FROM
** clause of the aggregate query */
if( ALWAYS(pSrcList!=0) ){
struct SrcList_item *pItem = pSrcList->a;
for(i=0; i<pSrcList->nSrc; i++, pItem++){
struct AggInfo_col *pCol;
assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
if( pExpr->iTable==pItem->iCursor ){
/* If we reach this point, it means that pExpr refers to a table
** that is in the FROM clause of the aggregate query.
**
** Make an entry for the column in pAggInfo->aCol[] if there
** is not an entry there already.
*/
int k;
pCol = pAggInfo->aCol;
for(k=0; k<pAggInfo->nColumn; k++, pCol++){
if( pCol->iTable==pExpr->iTable &&
pCol->iColumn==pExpr->iColumn ){
break;
}
}
if( (k>=pAggInfo->nColumn)
&& (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
){
pCol = &pAggInfo->aCol[k];
pCol->pTab = pExpr->y.pTab;
pCol->iTable = pExpr->iTable;
pCol->iColumn = pExpr->iColumn;
pCol->iMem = ++pParse->nMem;
pCol->iSorterColumn = -1;
pCol->pExpr = pExpr;
if( pAggInfo->pGroupBy ){
int j, n;
ExprList *pGB = pAggInfo->pGroupBy;
struct ExprList_item *pTerm = pGB->a;
n = pGB->nExpr;
for(j=0; j<n; j++, pTerm++){
Expr *pE = pTerm->pExpr;
if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
pE->iColumn==pExpr->iColumn ){
pCol->iSorterColumn = j;
break;
}
}
}
if( pCol->iSorterColumn<0 ){
pCol->iSorterColumn = pAggInfo->nSortingColumn++;
}
}
/* There is now an entry for pExpr in pAggInfo->aCol[] (either
** because it was there before or because we just created it).
** Convert the pExpr to be a TK_AGG_COLUMN referring to that
** pAggInfo->aCol[] entry.
*/
ExprSetVVAProperty(pExpr, EP_NoReduce);
pExpr->pAggInfo = pAggInfo;
pExpr->op = TK_AGG_COLUMN;
pExpr->iAgg = (i16)k;
break;
} /* endif pExpr->iTable==pItem->iCursor */
} /* end loop over pSrcList */
}
return WRC_Prune;
}
case TK_AGG_FUNCTION: {
if( (pNC->ncFlags & NC_InAggFunc)==0
&& pWalker->walkerDepth==pExpr->op2
){
/* Check to see if pExpr is a duplicate of another aggregate
** function that is already in the pAggInfo structure
*/
struct AggInfo_func *pItem = pAggInfo->aFunc;
for(i=0; i<pAggInfo->nFunc; i++, pItem++){
if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
break;
}
}
if( i>=pAggInfo->nFunc ){
/* pExpr is original. Make a new entry in pAggInfo->aFunc[]
*/
u8 enc = ENC(pParse->db);
i = addAggInfoFunc(pParse->db, pAggInfo);
if( i>=0 ){
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
pItem = &pAggInfo->aFunc[i];
pItem->pExpr = pExpr;
pItem->iMem = ++pParse->nMem;
assert( !ExprHasProperty(pExpr, EP_IntValue) );
pItem->pFunc = sqlite3FindFunction(pParse->db,
pExpr->u.zToken,
pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
if( pExpr->flags & EP_Distinct ){
pItem->iDistinct = pParse->nTab++;
}else{
pItem->iDistinct = -1;
}
}
}
/* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
*/
assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
ExprSetVVAProperty(pExpr, EP_NoReduce);
pExpr->iAgg = (i16)i;
pExpr->pAggInfo = pAggInfo;
return WRC_Prune;
}else{
return WRC_Continue;
}
}
}
return WRC_Continue;
}
static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
UNUSED_PARAMETER(pSelect);
pWalker->walkerDepth++;
return WRC_Continue;
}
static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
UNUSED_PARAMETER(pSelect);
pWalker->walkerDepth--;
}
/*
** Analyze the pExpr expression looking for aggregate functions and
** for variables that need to be added to AggInfo object that pNC->pAggInfo
** points to. Additional entries are made on the AggInfo object as
** necessary.
**
** This routine should only be called after the expression has been
** analyzed by sqlite3ResolveExprNames().
*/
void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
Walker w;
w.xExprCallback = analyzeAggregate;
w.xSelectCallback = analyzeAggregatesInSelect;
w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
w.walkerDepth = 0;
w.u.pNC = pNC;
w.pParse = 0;
assert( pNC->pSrcList!=0 );
sqlite3WalkExpr(&w, pExpr);
}
/*
** Call sqlite3ExprAnalyzeAggregates() for every expression in an
** expression list. Return the number of errors.
**
** If an error is found, the analysis is cut short.
*/
void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
struct ExprList_item *pItem;
int i;
if( pList ){
for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
}
}
}
/*
** Allocate a single new register for use to hold some intermediate result.
*/
int sqlite3GetTempReg(Parse *pParse){
if( pParse->nTempReg==0 ){
return ++pParse->nMem;
}
return pParse->aTempReg[--pParse->nTempReg];
}
/*
** Deallocate a register, making available for reuse for some other
** purpose.
*/
void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
pParse->aTempReg[pParse->nTempReg++] = iReg;
}
}
/*
** Allocate or deallocate a block of nReg consecutive registers.
*/
int sqlite3GetTempRange(Parse *pParse, int nReg){
int i, n;
if( nReg==1 ) return sqlite3GetTempReg(pParse);
i = pParse->iRangeReg;
n = pParse->nRangeReg;
if( nReg<=n ){
pParse->iRangeReg += nReg;
pParse->nRangeReg -= nReg;
}else{
i = pParse->nMem+1;
pParse->nMem += nReg;
}
return i;
}
void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
if( nReg==1 ){
sqlite3ReleaseTempReg(pParse, iReg);
return;
}
if( nReg>pParse->nRangeReg ){
pParse->nRangeReg = nReg;
pParse->iRangeReg = iReg;
}
}
/*
** Mark all temporary registers as being unavailable for reuse.
**
** Always invoke this procedure after coding a subroutine or co-routine
** that might be invoked from other parts of the code, to ensure that
** the sub/co-routine does not use registers in common with the code that
** invokes the sub/co-routine.
*/
void sqlite3ClearTempRegCache(Parse *pParse){
pParse->nTempReg = 0;
pParse->nRangeReg = 0;
}
/*
** Validate that no temporary register falls within the range of
** iFirst..iLast, inclusive. This routine is only call from within assert()
** statements.
*/
#ifdef SQLITE_DEBUG
int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
int i;
if( pParse->nRangeReg>0
&& pParse->iRangeReg+pParse->nRangeReg > iFirst
&& pParse->iRangeReg <= iLast
){
return 0;
}
for(i=0; i<pParse->nTempReg; i++){
if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
return 0;
}
}
return 1;
}
#endif /* SQLITE_DEBUG */
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_1275_2 |
crossvul-cpp_data_good_5363_0 | /*
* 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 <jasper/jasper.h>
/******************************************************************************\
*
\******************************************************************************/
typedef enum {
OPT_HELP,
OPT_VERSION,
OPT_VERBOSE,
OPT_INFILE,
OPT_DEBUG
} 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},
{-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;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
debug = 0;
/* 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_HELP:
default:
usage();
break;
}
}
jas_setdbglevel(debug);
/* 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);
numcmpts = jas_image_numcmpts(image);
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 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-476/c/good_5363_0 |
crossvul-cpp_data_good_655_1 | /* foreign file formats base class
*
* 7/2/12
* - add support for sequential reads
* 18/6/12
* - flatten alpha with vips_flatten()
* 28/5/13
* - auto rshift down to 8 bits during save
* 19/1/14
* - pack and unpack rad to scrgb
* 18/8/14
* - fix conversion to 16-bit RGB, thanks John
* 18/6/15
* - forward progress signals from load
* 23/5/16
* - remove max-alpha stuff, this is now automatic
* 12/6/17
* - transform cmyk->rgb if there's an embedded profile
* 16/6/17
* - add page_height
* 5/3/18
* - block _start if one start fails, see #893
*/
/*
This file is part of VIPS.
VIPS 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 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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
*/
/*
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
*/
/*
#define DEBUG
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <stdio.h>
#include <stdlib.h>
#include <vips/vips.h>
#include <vips/internal.h>
#include <vips/debug.h>
#include "pforeign.h"
/**
* SECTION: foreign
* @short_description: load and save images in a variety of formats
* @stability: Stable
* @see_also: <link linkend="libvips-image">image</link>
* @include: vips/vips.h
*
* This set of operations load and save images in a variety of formats.
*
* The operations share a base class that offers a simple way to search for a
* subclass of #VipsForeign which can load a certain file (see
* vips_foreign_find_load()) or buffer (see vips_foreign_find_load_buffer()),
* or which could be used to save an image to a
* certain file type (see vips_foreign_find_save() and
* vips_foreign_find_save_buffer()). You can then run these
* operations using vips_call() and friends to perform the load or save.
*
* vips_image_write_to_file() and vips_image_new_from_file() and friends use
* these functions to automate file load and save.
*
* You can also invoke the operations directly, for example:
*
* |[
* vips_tiffsave (my_image, "frank.anything",
* "compression", VIPS_FOREIGN_TIFF_COMPRESSION_JPEG,
* NULL);
* ]|
*
* To add support for a new file format to vips, simply define a new subclass
* of #VipsForeignLoad or #VipsForeignSave.
*
* If you define a new operation which is a subclass of #VipsForeign, support
* for it automatically appears in all VIPS user-interfaces. It will also be
* transparently supported by vips_image_new_from_file() and friends.
*
* VIPS comes with VipsForeign for TIFF, JPEG, PNG, Analyze, PPM, OpenEXR, CSV,
* Matlab, Radiance, RAW, FITS, WebP, SVG, PDF, GIF and VIPS. It also includes
* import filters which can load with libMagick and with OpenSlide.
*
* ## Writing a new loader
*
* Add a new loader to VIPS by subclassing #VipsForeignLoad. Subclasses need to
* implement at least @header().
*
* @header() must set at least the header fields of @out. @load(), if defined,
* must load the pixels to @real.
*
* The suffix list is used to select a format to save a file in, and to pick a
* loader if you don't define is_a().
*
* You should also define @nickname and @description in #VipsObject.
*
* As a complete example, here's code for a PNG loader, minus the actual
* calls to libpng.
*
* |[
* typedef struct _VipsForeignLoadPng {
* VipsForeignLoad parent_object;
*
* char *filename;
* } VipsForeignLoadPng;
*
* typedef VipsForeignLoadClass VipsForeignLoadPngClass;
*
* G_DEFINE_TYPE( VipsForeignLoadPng, vips_foreign_load_png,
* VIPS_TYPE_FOREIGN_LOAD );
*
* static VipsForeignFlags
* vips_foreign_load_png_get_flags_filename( const char *filename )
* {
* VipsForeignFlags flags;
*
* flags = 0;
* if( vips__png_isinterlaced( filename ) )
* flags = VIPS_FOREIGN_PARTIAL;
* else
* flags = VIPS_FOREIGN_SEQUENTIAL;
*
* return( flags );
* }
*
* static VipsForeignFlags
* vips_foreign_load_png_get_flags( VipsForeignLoad *load )
* {
* VipsForeignLoadPng *png = (VipsForeignLoadPng *) load;
*
* return( vips_foreign_load_png_get_flags_filename( png->filename ) );
* }
*
* static int
* vips_foreign_load_png_header( VipsForeignLoad *load )
* {
* VipsForeignLoadPng *png = (VipsForeignLoadPng *) load;
*
* if( vips__png_header( png->filename, load->out ) )
* return( -1 );
*
* return( 0 );
* }
*
* static int
* vips_foreign_load_png_load( VipsForeignLoad *load )
* {
* VipsForeignLoadPng *png = (VipsForeignLoadPng *) load;
*
* if( vips__png_read( png->filename, load->real ) )
* return( -1 );
*
* return( 0 );
* }
*
* static void
* vips_foreign_load_png_class_init( VipsForeignLoadPngClass *class )
* {
* GObjectClass *gobject_class = G_OBJECT_CLASS( class );
* VipsObjectClass *object_class = (VipsObjectClass *) class;
* VipsForeignClass *foreign_class = (VipsForeignClass *) class;
* VipsForeignLoadClass *load_class = (VipsForeignLoadClass *) class;
*
* gobject_class->set_property = vips_object_set_property;
* gobject_class->get_property = vips_object_get_property;
*
* object_class->nickname = "pngload";
* object_class->description = _( "load png from file" );
*
* foreign_class->suffs = vips__png_suffs;
*
* load_class->is_a = vips__png_ispng;
* load_class->get_flags_filename =
* vips_foreign_load_png_get_flags_filename;
* load_class->get_flags = vips_foreign_load_png_get_flags;
* load_class->header = vips_foreign_load_png_header;
* load_class->load = vips_foreign_load_png_load;
*
* VIPS_ARG_STRING( class, "filename", 1,
* _( "Filename" ),
* _( "Filename to load from" ),
* VIPS_ARGUMENT_REQUIRED_INPUT,
* G_STRUCT_OFFSET( VipsForeignLoadPng, filename ),
* NULL );
* }
*
* static void
* vips_foreign_load_png_init( VipsForeignLoadPng *png )
* {
* }
* ]|
*
* ## Writing a new saver
*
* Call your saver in the class' @build() method after chaining up. The
* prepared image should be ready for you to save in @ready.
*
* As a complete example, here's the code for the CSV saver, minus the calls
* to the actual save routines.
*
* |[
* typedef struct _VipsForeignSaveCsv {
* VipsForeignSave parent_object;
*
* char *filename;
* const char *separator;
* } VipsForeignSaveCsv;
*
* typedef VipsForeignSaveClass VipsForeignSaveCsvClass;
*
* G_DEFINE_TYPE( VipsForeignSaveCsv, vips_foreign_save_csv,
* VIPS_TYPE_FOREIGN_SAVE );
*
* static int
* vips_foreign_save_csv_build( VipsObject *object )
* {
* VipsForeignSave *save = (VipsForeignSave *) object;
* VipsForeignSaveCsv *csv = (VipsForeignSaveCsv *) object;
*
* if( VIPS_OBJECT_CLASS( vips_foreign_save_csv_parent_class )->
* build( object ) )
* return( -1 );
*
* if( vips__csv_write( save->ready, csv->filename, csv->separator ) )
* return( -1 );
*
* return( 0 );
* }
*
* static void
* vips_foreign_save_csv_class_init( VipsForeignSaveCsvClass *class )
* {
* GObjectClass *gobject_class = G_OBJECT_CLASS( class );
* VipsObjectClass *object_class = (VipsObjectClass *) class;
* VipsForeignClass *foreign_class = (VipsForeignClass *) class;
* VipsForeignSaveClass *save_class = (VipsForeignSaveClass *) class;
*
* gobject_class->set_property = vips_object_set_property;
* gobject_class->get_property = vips_object_get_property;
*
* object_class->nickname = "csvsave";
* object_class->description = _( "save image to csv file" );
* object_class->build = vips_foreign_save_csv_build;
*
* foreign_class->suffs = vips__foreign_csv_suffs;
*
* save_class->saveable = VIPS_SAVEABLE_MONO;
* // no need to define ->format_table, we don't want the input
* // cast for us
*
* VIPS_ARG_STRING( class, "filename", 1,
* _( "Filename" ),
* _( "Filename to save to" ),
* VIPS_ARGUMENT_REQUIRED_INPUT,
* G_STRUCT_OFFSET( VipsForeignSaveCsv, filename ),
* NULL );
*
* VIPS_ARG_STRING( class, "separator", 13,
* _( "Separator" ),
* _( "Separator characters" ),
* VIPS_ARGUMENT_OPTIONAL_INPUT,
* G_STRUCT_OFFSET( VipsForeignSaveCsv, separator ),
* "\t" );
* }
*
* static void
* vips_foreign_save_csv_init( VipsForeignSaveCsv *csv )
* {
* csv->separator = g_strdup( "\t" );
* }
* ]|
*/
/* Use this to link images to the load operation that made them.
*/
static GQuark vips__foreign_load_operation = 0;
/**
* VipsForeignFlags:
* @VIPS_FOREIGN_NONE: no flags set
* @VIPS_FOREIGN_PARTIAL: the image may be read lazilly
* @VIPS_FOREIGN_BIGENDIAN: image pixels are most-significant byte first
* @VIPS_FOREIGN_SEQUENTIAL: top-to-bottom lazy reading
*
* Some hints about the image loader.
*
* #VIPS_FOREIGN_PARTIAL means that the image can be read directly from the
* file without needing to be unpacked to a temporary image first.
*
* #VIPS_FOREIGN_SEQUENTIAL means that the loader supports lazy reading, but
* only top-to-bottom (sequential) access. Formats like PNG can read sets of
* scanlines, for example, but only in order.
*
* If neither PARTIAL or SEQUENTIAL is set, the loader only supports whole
* image read. Setting both PARTIAL and SEQUENTIAL is an error.
*
* #VIPS_FOREIGN_BIGENDIAN means that image pixels are most-significant byte
* first. Depending on the native byte order of the host machine, you may
* need to swap bytes. See vips_copy().
*/
G_DEFINE_ABSTRACT_TYPE( VipsForeign, vips_foreign, VIPS_TYPE_OPERATION );
static void
vips_foreign_summary_class( VipsObjectClass *object_class, VipsBuf *buf )
{
VipsForeignClass *class = VIPS_FOREIGN_CLASS( object_class );
VIPS_OBJECT_CLASS( vips_foreign_parent_class )->
summary_class( object_class, buf );
if( class->suffs ) {
const char **p;
vips_buf_appends( buf, " (" );
for( p = class->suffs; *p; p++ ) {
vips_buf_appendf( buf, "%s", *p );
if( p[1] )
vips_buf_appends( buf, ", " );
}
vips_buf_appends( buf, ")" );
}
vips_buf_appendf( buf, ", priority=%d", class->priority );
}
static void
vips_foreign_class_init( VipsForeignClass *class )
{
GObjectClass *gobject_class = G_OBJECT_CLASS( class );
VipsObjectClass *object_class = (VipsObjectClass *) class;
gobject_class->set_property = vips_object_set_property;
gobject_class->get_property = vips_object_get_property;
object_class->nickname = "foreign";
object_class->description = _( "load and save image files" );
object_class->summary_class = vips_foreign_summary_class;
}
static void
vips_foreign_init( VipsForeign *object )
{
}
/* To iterate over supported files we build a temp list of subclasses of
* VipsForeign, sort by priority, iterate, and free.
*/
static void *
file_add_class( VipsForeignClass *class, GSList **files )
{
/* Append so we don't reverse the list of files. Sort will not reorder
* items of equal priority.
*/
*files = g_slist_append( *files, class );
return( NULL );
}
static gint
file_compare( VipsForeignClass *a, VipsForeignClass *b )
{
return( b->priority - a->priority );
}
/**
* vips_foreign_map:
* @base: base class to search below (eg. "VipsForeignLoad")
* @fn: (scope call): function to apply to each #VipsForeignClass
* @a: user data
* @b: user data
*
* Apply a function to every #VipsForeignClass that VIPS knows about. Foreigns
* are presented to the function in priority order.
*
* Like all VIPS map functions, if @fn returns %NULL, iteration continues. If
* it returns non-%NULL, iteration terminates and that value is returned. The
* map function returns %NULL if all calls return %NULL.
*
* See also: vips_slist_map().
*
* Returns: (transfer none): the result of iteration
*/
void *
vips_foreign_map( const char *base, VipsSListMap2Fn fn, void *a, void *b )
{
GSList *files;
void *result;
files = NULL;
(void) vips_class_map_all( g_type_from_name( base ),
(VipsClassMapFn) file_add_class, (void *) &files );
files = g_slist_sort( files, (GCompareFunc) file_compare );
result = vips_slist_map2( files, fn, a, b );
g_slist_free( files );
return( result );
}
/* Abstract base class for image load.
*/
G_DEFINE_ABSTRACT_TYPE( VipsForeignLoad, vips_foreign_load, VIPS_TYPE_FOREIGN );
static void
vips_foreign_load_dispose( GObject *gobject )
{
VipsForeignLoad *load = VIPS_FOREIGN_LOAD( gobject );
VIPS_UNREF( load->real );
G_OBJECT_CLASS( vips_foreign_load_parent_class )->dispose( gobject );
}
static void
vips_foreign_load_summary_class( VipsObjectClass *object_class, VipsBuf *buf )
{
VipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_CLASS( object_class );
VIPS_OBJECT_CLASS( vips_foreign_load_parent_class )->
summary_class( object_class, buf );
if( !G_TYPE_IS_ABSTRACT( G_TYPE_FROM_CLASS( class ) ) ) {
if( class->is_a )
vips_buf_appends( buf, ", is_a" );
if( class->is_a_buffer )
vips_buf_appends( buf, ", is_a_buffer" );
if( class->get_flags )
vips_buf_appends( buf, ", get_flags" );
if( class->get_flags_filename )
vips_buf_appends( buf, ", get_flags_filename" );
if( class->header )
vips_buf_appends( buf, ", header" );
if( class->load )
vips_buf_appends( buf, ", load" );
/* You can omit ->load(), you must not omit ->header().
*/
g_assert( class->header );
}
}
/* Can this VipsForeign open this file?
*/
static void *
vips_foreign_find_load_sub( VipsForeignLoadClass *load_class,
const char *filename )
{
VipsForeignClass *class = VIPS_FOREIGN_CLASS( load_class );
#ifdef DEBUG
printf( "vips_foreign_find_load_sub: %s\n",
VIPS_OBJECT_CLASS( class )->nickname );
#endif /*DEBUG*/
if( load_class->is_a ) {
if( load_class->is_a( filename ) )
return( load_class );
#ifdef DEBUG
printf( "vips_foreign_find_load_sub: is_a failed\n" );
#endif /*DEBUG*/
}
else if( class->suffs &&
vips_filename_suffix_match( filename, class->suffs ) )
return( load_class );
else {
#ifdef DEBUG
printf( "vips_foreign_find_load_sub: suffix match failed\n" );
#endif /*DEBUG*/
}
return( NULL );
}
/**
* vips_foreign_find_load:
* @filename: file to find a loader for
*
* Searches for an operation you could use to load @filename. Any trailing
* options on @filename are stripped and ignored.
*
* See also: vips_foreign_find_load_buffer(), vips_image_new_from_file().
*
* Returns: the name of an operation on success, %NULL on error
*/
const char *
vips_foreign_find_load( const char *name )
{
char filename[VIPS_PATH_MAX];
char option_string[VIPS_PATH_MAX];
VipsForeignLoadClass *load_class;
vips__filename_split8( name, filename, option_string );
if( !vips_existsf( "%s", filename ) ) {
vips_error( "VipsForeignLoad",
_( "file \"%s\" not found" ), name );
return( NULL );
}
if( !(load_class = (VipsForeignLoadClass *) vips_foreign_map(
"VipsForeignLoad",
(VipsSListMap2Fn) vips_foreign_find_load_sub,
(void *) filename, NULL )) ) {
vips_error( "VipsForeignLoad",
_( "\"%s\" is not a known file format" ), name );
return( NULL );
}
#ifdef DEBUG
printf( "vips_foreign_find_load: selected %s\n",
VIPS_OBJECT_CLASS( load_class )->nickname );
#endif /*DEBUG*/
return( G_OBJECT_CLASS_NAME( load_class ) );
}
/* Kept for compat with earlier version of the vip8 API. Use
* vips_image_new_from_file() now.
*/
int
vips_foreign_load( const char *name, VipsImage **out, ... )
{
char filename[VIPS_PATH_MAX];
char option_string[VIPS_PATH_MAX];
const char *operation_name;
va_list ap;
int result;
vips__filename_split8( name, filename, option_string );
if( !(operation_name = vips_foreign_find_load( filename )) )
return( -1 );
va_start( ap, out );
result = vips_call_split_option_string( operation_name, option_string,
ap, filename, out );
va_end( ap );
return( result );
}
/* Can this VipsForeign open this buffer?
*/
static void *
vips_foreign_find_load_buffer_sub( VipsForeignLoadClass *load_class,
const void **buf, size_t *len )
{
if( load_class->is_a_buffer &&
load_class->is_a_buffer( *buf, *len ) )
return( load_class );
return( NULL );
}
/**
* vips_foreign_find_load_buffer:
* @data: (array length=size) (element-type guint8) (transfer none): start of
* memory buffer
* @size: (type gsize): number of bytes in @data
*
* Searches for an operation you could use to load a memory buffer. To see the
* range of buffer loaders supported by your vips, try something like:
*
* vips -l | grep load_buffer
*
* See also: vips_image_new_from_buffer().
*
* Returns: (transfer none): the name of an operation on success, %NULL on
* error.
*/
const char *
vips_foreign_find_load_buffer( const void *data, size_t size )
{
VipsForeignLoadClass *load_class;
if( !(load_class = (VipsForeignLoadClass *) vips_foreign_map(
"VipsForeignLoad",
(VipsSListMap2Fn) vips_foreign_find_load_buffer_sub,
&data, &size )) ) {
vips_error( "VipsForeignLoad",
"%s", _( "buffer is not in a known format" ) );
return( NULL );
}
return( G_OBJECT_CLASS_NAME( load_class ) );
}
/**
* vips_foreign_is_a:
* @loader: name of loader to use for test
* @filename: file to test
*
* Return %TRUE if @filename can be loaded by @loader. @loader is something
* like "tiffload" or "VipsForeignLoadTiff".
*
* Returns: %TRUE if @filename can be loaded by @loader.
*/
gboolean
vips_foreign_is_a( const char *loader, const char *filename )
{
const VipsObjectClass *class;
VipsForeignLoadClass *load_class;
if( !(class = vips_class_find( "VipsForeignLoad", loader )) )
return( FALSE );
load_class = VIPS_FOREIGN_LOAD_CLASS( class );
if( load_class->is_a &&
load_class->is_a( filename ) )
return( TRUE );
return( FALSE );
}
/**
* vips_foreign_is_a_buffer:
* @loader: name of loader to use for test
* @data: (array length=size) (element-type guint8): pointer to the buffer to test
* @size: (type gsize): size of the buffer to test
*
* Return %TRUE if @data can be loaded by @loader. @loader is something
* like "tiffload_buffer" or "VipsForeignLoadTiffBuffer".
*
* Returns: %TRUE if @data can be loaded by @loader.
*/
gboolean
vips_foreign_is_a_buffer( const char *loader, const void *data, size_t size )
{
const VipsObjectClass *class;
VipsForeignLoadClass *load_class;
if( !(class = vips_class_find( "VipsForeignLoad", loader )) )
return( FALSE );
load_class = VIPS_FOREIGN_LOAD_CLASS( class );
if( load_class->is_a_buffer &&
load_class->is_a_buffer( data, size ) )
return( TRUE );
return( FALSE );
}
/**
* vips_foreign_flags:
* @loader: name of loader to use for test
* @filename: file to test
*
* Return the flags for @filename using @loader.
* @loader is something like "tiffload" or "VipsForeignLoadTiff".
*
* Returns: the flags for @filename.
*/
VipsForeignFlags
vips_foreign_flags( const char *loader, const char *filename )
{
const VipsObjectClass *class;
if( (class = vips_class_find( "VipsForeignLoad", loader )) ) {
VipsForeignLoadClass *load_class =
VIPS_FOREIGN_LOAD_CLASS( class );
if( load_class->get_flags_filename )
return( load_class->get_flags_filename( filename ) );
}
return( 0 );
}
static VipsObject *
vips_foreign_load_new_from_string( const char *string )
{
const char *file_op;
GType type;
VipsForeignLoad *load;
if( !(file_op = vips_foreign_find_load( string )) )
return( NULL );
type = g_type_from_name( file_op );
g_assert( type );
load = VIPS_FOREIGN_LOAD( g_object_new( type, NULL ) );
g_object_set( load,
"filename", string,
NULL );
return( VIPS_OBJECT( load ) );
}
static VipsImage *
vips_foreign_load_temp( VipsForeignLoad *load )
{
const guint64 disc_threshold = vips_get_disc_threshold();
const guint64 image_size = VIPS_IMAGE_SIZEOF_IMAGE( load->out );
/* If this is a partial operation, we can open directly.
*/
if( load->flags & VIPS_FOREIGN_PARTIAL ) {
#ifdef DEBUG
printf( "vips_foreign_load_temp: partial temp\n" );
#endif /*DEBUG*/
return( vips_image_new() );
}
/* If it can do sequential access and it's been requested, we can open
* directly.
*/
if( (load->flags & VIPS_FOREIGN_SEQUENTIAL) &&
load->access != VIPS_ACCESS_RANDOM ) {
#ifdef DEBUG
printf( "vips_foreign_load_temp: partial sequential temp\n" );
#endif /*DEBUG*/
return( vips_image_new() );
}
/* ->memory used to be called ->disc and default TRUE. If it's been
* forced FALSE, set memory TRUE.
*/
if( !load->disc )
load->memory = TRUE;
/* We open via disc if:
* - 'memory' is off
* - the uncompressed image will be larger than
* vips_get_disc_threshold()
*/
if( !load->memory &&
image_size > disc_threshold ) {
#ifdef DEBUG
printf( "vips_foreign_load_temp: disc temp\n" );
#endif /*DEBUG*/
return( vips_image_new_temp_file( "%s.v" ) );
}
#ifdef DEBUG
printf( "vips_foreign_load_temp: memory temp\n" );
#endif /*DEBUG*/
/* Otherwise, fall back to a memory buffer.
*/
return( vips_image_new_memory() );
}
/* Check two images for compatibility: their geometries need to match.
*/
static gboolean
vips_foreign_load_iscompat( VipsImage *a, VipsImage *b )
{
if( a->Xsize != b->Xsize ||
a->Ysize != b->Ysize ||
a->Bands != b->Bands ||
a->Coding != b->Coding ||
a->BandFmt != b->BandFmt ) {
vips_error( "VipsForeignLoad",
"%s", _( "images do not match" ) );
return( FALSE );
}
return( TRUE );
}
/* Our start function ... do the lazy open, if necessary, and return a region
* on the new image.
*/
static void *
vips_foreign_load_start( VipsImage *out, void *a, void *b )
{
VipsForeignLoad *load = VIPS_FOREIGN_LOAD( b );
VipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load );
/* If this start has failed before in another thread, we can fail now.
*/
if( load->error )
return( NULL );
if( !load->real ) {
if( !(load->real = vips_foreign_load_temp( load )) )
return( NULL );
#ifdef DEBUG
printf( "vips_foreign_load_start: triggering ->load()\n" );
#endif /*DEBUG*/
/* Read the image in. This may involve a long computation and
* will finish with load->real holding the decompressed image.
*
* We want our caller to be able to see this computation on
* @out, so eval signals on ->real need to appear on ->out.
*/
load->real->progress_signal = load->out;
/* Note the load object on the image. Loaders can use
* this to signal invalidate if they hit a load error. See
* vips_foreign_load_invalidate() below.
*/
g_object_set_qdata( G_OBJECT( load->real ),
vips__foreign_load_operation, load );
/* Load the image and check the result.
*
* ->header() read the header into @out, load has read the
* image into @real. They must match exactly in size, bands,
* format and coding for the copy to work.
*
* Some versions of ImageMagick give different results between
* Ping and Load for some formats, for example.
*
* If the load fails, we need to stop
*/
if( class->load( load ) ||
vips_image_pio_input( load->real ) ||
vips_foreign_load_iscompat( load->real, out ) ) {
vips_operation_invalidate( VIPS_OPERATION( load ) );
load->error = TRUE;
return( NULL );
}
/* We have to tell vips that out depends on real. We've set
* the demand hint below, but not given an input there.
*/
vips_image_pipelinev( load->out, load->out->dhint,
load->real, NULL );
}
return( vips_region_new( load->real ) );
}
/* Just pointer-copy.
*/
static int
vips_foreign_load_generate( VipsRegion *or,
void *seq, void *a, void *b, gboolean *stop )
{
VipsRegion *ir = (VipsRegion *) seq;
VipsRect *r = &or->valid;
/* Ask for input we need.
*/
if( vips_region_prepare( ir, r ) )
return( -1 );
/* Attach output region to that.
*/
if( vips_region_region( or, ir, r, r->left, r->top ) )
return( -1 );
return( 0 );
}
static int
vips_foreign_load_build( VipsObject *object )
{
VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( object );
VipsForeignLoad *load = VIPS_FOREIGN_LOAD( object );
VipsForeignLoadClass *fclass = VIPS_FOREIGN_LOAD_GET_CLASS( object );
VipsForeignFlags flags;
#ifdef DEBUG
printf( "vips_foreign_load_build:\n" );
#endif /*DEBUG*/
flags = 0;
if( fclass->get_flags )
flags |= fclass->get_flags( load );
if( (flags & VIPS_FOREIGN_PARTIAL) &&
(flags & VIPS_FOREIGN_SEQUENTIAL) ) {
g_warning( "%s",
_( "VIPS_FOREIGN_PARTIAL and VIPS_FOREIGN_SEQUENTIAL "
"both set -- using SEQUENTIAL" ) );
flags ^= VIPS_FOREIGN_PARTIAL;
}
g_object_set( load, "flags", flags, NULL );
/* If the loader can do sequential mode and sequential has been
* requested, we need to block caching.
*/
if( (load->flags & VIPS_FOREIGN_SEQUENTIAL) &&
load->access != VIPS_ACCESS_RANDOM )
load->nocache = TRUE;
if( VIPS_OBJECT_CLASS( vips_foreign_load_parent_class )->
build( object ) )
return( -1 );
if( load->sequential )
g_warning( "%s",
_( "ignoring deprecated \"sequential\" mode -- "
"please use \"access\" instead" ) );
g_object_set( object, "out", vips_image_new(), NULL );
vips_image_set_string( load->out,
VIPS_META_LOADER, class->nickname );
#ifdef DEBUG
printf( "vips_foreign_load_build: triggering ->header()\n" );
#endif /*DEBUG*/
/* Read the header into @out.
*/
if( fclass->header &&
fclass->header( load ) )
return( -1 );
/* If there's no ->load() method then the header read has done
* everything. Otherwise, it's just set fields and we must also
* load pixels.
*
* Delay the load until the first pixel is requested by doing the work
* in the start function of the copy.
*/
if( fclass->load ) {
#ifdef DEBUG
printf( "vips_foreign_load_build: delaying read ...\n" );
#endif /*DEBUG*/
/* ->header() should set the dhint. It'll default to the safe
* SMALLTILE if header() did not set it.
*/
vips_image_pipelinev( load->out, load->out->dhint, NULL );
/* Then 'start' creates the real image and 'gen' fetches
* pixels for @out from @real on demand.
*/
if( vips_image_generate( load->out,
vips_foreign_load_start,
vips_foreign_load_generate,
vips_stop_one,
NULL, load ) )
return( -1 );
}
/* If random access has been requested, make sure that we don't have a
* SEQ tag left from a sequential loader.
*/
if( load->access == VIPS_ACCESS_RANDOM )
(void) vips_image_remove( load->out, VIPS_META_SEQUENTIAL );
return( 0 );
}
static VipsOperationFlags
vips_foreign_load_operation_get_flags( VipsOperation *operation )
{
VipsForeignLoad *load = VIPS_FOREIGN_LOAD( operation );
VipsOperationFlags flags;
flags = VIPS_OPERATION_CLASS( vips_foreign_load_parent_class )->
get_flags( operation );
if( load->nocache )
flags |= VIPS_OPERATION_NOCACHE;
return( flags );
}
static void
vips_foreign_load_class_init( VipsForeignLoadClass *class )
{
GObjectClass *gobject_class = G_OBJECT_CLASS( class );
VipsObjectClass *object_class = (VipsObjectClass *) class;
VipsOperationClass *operation_class = (VipsOperationClass *) class;
gobject_class->dispose = vips_foreign_load_dispose;
gobject_class->set_property = vips_object_set_property;
gobject_class->get_property = vips_object_get_property;
object_class->build = vips_foreign_load_build;
object_class->summary_class = vips_foreign_load_summary_class;
object_class->new_from_string = vips_foreign_load_new_from_string;
object_class->nickname = "fileload";
object_class->description = _( "file loaders" );
operation_class->get_flags = vips_foreign_load_operation_get_flags;
VIPS_ARG_IMAGE( class, "out", 2,
_( "Output" ),
_( "Output image" ),
VIPS_ARGUMENT_REQUIRED_OUTPUT,
G_STRUCT_OFFSET( VipsForeignLoad, out ) );
VIPS_ARG_FLAGS( class, "flags", 6,
_( "Flags" ),
_( "Flags for this file" ),
VIPS_ARGUMENT_OPTIONAL_OUTPUT,
G_STRUCT_OFFSET( VipsForeignLoad, flags ),
VIPS_TYPE_FOREIGN_FLAGS, VIPS_FOREIGN_NONE );
VIPS_ARG_BOOL( class, "memory", 7,
_( "Memory" ),
_( "Force open via memory" ),
VIPS_ARGUMENT_OPTIONAL_INPUT,
G_STRUCT_OFFSET( VipsForeignLoad, memory ),
FALSE );
VIPS_ARG_ENUM( class, "access", 8,
_( "Access" ),
_( "Required access pattern for this file" ),
VIPS_ARGUMENT_OPTIONAL_INPUT,
G_STRUCT_OFFSET( VipsForeignLoad, access ),
VIPS_TYPE_ACCESS, VIPS_ACCESS_RANDOM );
VIPS_ARG_BOOL( class, "sequential", 10,
_( "Sequential" ),
_( "Sequential read only" ),
VIPS_ARGUMENT_OPTIONAL_INPUT | VIPS_ARGUMENT_DEPRECATED,
G_STRUCT_OFFSET( VipsForeignLoad, sequential ),
FALSE );
VIPS_ARG_BOOL( class, "fail", 11,
_( "Fail" ),
_( "Fail on first error" ),
VIPS_ARGUMENT_OPTIONAL_INPUT,
G_STRUCT_OFFSET( VipsForeignLoad, fail ),
FALSE );
VIPS_ARG_BOOL( class, "disc", 12,
_( "Disc" ),
_( "Open to disc" ),
VIPS_ARGUMENT_OPTIONAL_INPUT | VIPS_ARGUMENT_DEPRECATED,
G_STRUCT_OFFSET( VipsForeignLoad, disc ),
TRUE );
}
static void
vips_foreign_load_init( VipsForeignLoad *load )
{
load->disc = TRUE;
load->access = VIPS_ACCESS_RANDOM;
}
/*
* Loaders can call this
*/
/**
* vips_foreign_load_invalidate: (method)
* @image: image to invalidate
*
* Loaders can call this on the image they are making if they see a read error
* from the load library. It signals "invalidate" on the load operation and
* will cause it to be dropped from cache.
*
* If we know a file will cause a read error, we don't want to cache the
* failing operation, we want to make sure the image will really be opened
* again if our caller tries again. For example, a broken file might be
* replaced by a working one.
*/
void
vips_foreign_load_invalidate( VipsImage *image )
{
VipsOperation *operation;
#ifdef DEBUG
printf( "vips_foreign_load_invalidate: %p\n", image );
#endif /*DEBUG*/
if( (operation = g_object_get_qdata( G_OBJECT( image ),
vips__foreign_load_operation )) ) {
vips_operation_invalidate( operation );
}
}
/* Abstract base class for image savers.
*/
G_DEFINE_ABSTRACT_TYPE( VipsForeignSave, vips_foreign_save, VIPS_TYPE_FOREIGN );
static void
vips_foreign_save_dispose( GObject *gobject )
{
VipsForeignSave *save = VIPS_FOREIGN_SAVE( gobject );
VIPS_UNREF( save->ready );
G_OBJECT_CLASS( vips_foreign_save_parent_class )->dispose( gobject );
}
static void
vips_foreign_save_summary_class( VipsObjectClass *object_class, VipsBuf *buf )
{
VipsForeignSaveClass *class = VIPS_FOREIGN_SAVE_CLASS( object_class );
VIPS_OBJECT_CLASS( vips_foreign_save_parent_class )->
summary_class( object_class, buf );
vips_buf_appendf( buf, ", %s",
vips_enum_nick( VIPS_TYPE_SAVEABLE, class->saveable ) );
}
static VipsObject *
vips_foreign_save_new_from_string( const char *string )
{
const char *file_op;
GType type;
VipsForeignSave *save;
if( !(file_op = vips_foreign_find_save( string )) )
return( NULL );
type = g_type_from_name( file_op );
g_assert( type );
save = VIPS_FOREIGN_SAVE( g_object_new( type, NULL ) );
g_object_set( save,
"filename", string,
NULL );
return( VIPS_OBJECT( save ) );
}
/* Convert an image for saving.
*/
int
vips__foreign_convert_saveable( VipsImage *in, VipsImage **ready,
VipsSaveable saveable, VipsBandFormat *format, VipsCoding *coding,
VipsArrayDouble *background )
{
/* in holds a reference to the output of our chain as we build it.
*/
g_object_ref( in );
/* For coded images, can this class save the coding we are in now?
* Nothing to do.
*/
if( in->Coding != VIPS_CODING_NONE &&
coding[in->Coding] ) {
*ready = in;
return( 0 );
}
/* For uncoded images, if this saver supports ANY bands and this
* format we have nothing to do.
*/
if( in->Coding == VIPS_CODING_NONE &&
saveable == VIPS_SAVEABLE_ANY &&
format[in->BandFmt] == in->BandFmt ) {
*ready = in;
return( 0 );
}
/* Otherwise ... we need to decode and then (possibly) recode at the
* end.
*/
/* If this is an VIPS_CODING_LABQ, we can go straight to RGB.
*/
if( in->Coding == VIPS_CODING_LABQ ) {
VipsImage *out;
if( vips_LabQ2sRGB( in, &out, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
/* If this is an VIPS_CODING_RAD, we unpack to float. This could be
* scRGB or XYZ.
*/
if( in->Coding == VIPS_CODING_RAD ) {
VipsImage *out;
if( vips_rad2float( in, &out, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
/* If the saver supports RAD, we need to go to scRGB or XYZ.
*/
if( coding[VIPS_CODING_RAD] ) {
if( in->Type != VIPS_INTERPRETATION_scRGB &&
in->Type != VIPS_INTERPRETATION_XYZ ) {
VipsImage *out;
if( vips_colourspace( in, &out,
VIPS_INTERPRETATION_scRGB, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
}
/* If this image is CMYK and the saver is RGB-only, use lcms to try to
* import to XYZ. This will only work if the image has an embedded
* profile.
*/
if( in->Type == VIPS_INTERPRETATION_CMYK &&
in->Bands >= 4 &&
(saveable == VIPS_SAVEABLE_RGB ||
saveable == VIPS_SAVEABLE_RGBA ||
saveable == VIPS_SAVEABLE_RGBA_ONLY) ) {
VipsImage *out;
if( vips_icc_import( in, &out,
"pcs", VIPS_PCS_XYZ,
NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
/* We've imported to PCS, we must remove the embedded profile,
* since it no longer matches the image.
*
* For example, when converting CMYK JPG to RGB PNG, we need
* to remove the CMYK profile on import, or the png writer will
* try to attach it when we write the image as RGB.
*/
vips_image_remove( in, VIPS_META_ICC_NAME );
}
/* If this is something other than CMYK or RAD, eg. maybe a LAB image,
* we need to transform to RGB.
*/
if( !coding[VIPS_CODING_RAD] &&
in->Bands >= 3 &&
in->Type != VIPS_INTERPRETATION_CMYK &&
vips_colourspace_issupported( in ) &&
(saveable == VIPS_SAVEABLE_RGB ||
saveable == VIPS_SAVEABLE_RGBA ||
saveable == VIPS_SAVEABLE_RGBA_ONLY ||
saveable == VIPS_SAVEABLE_RGB_CMYK) ) {
VipsImage *out;
VipsInterpretation interpretation;
/* Do we make RGB or RGB16? We don't want to squash a 16-bit
* RGB down to 8 bits if the saver supports 16.
*/
if( vips_band_format_is8bit( format[in->BandFmt] ) )
interpretation = VIPS_INTERPRETATION_sRGB;
else
interpretation = VIPS_INTERPRETATION_RGB16;
if( vips_colourspace( in, &out, interpretation, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
/* VIPS_SAVEABLE_RGBA_ONLY does not support 1 or 2 bands ... convert
* to sRGB.
*/
if( !coding[VIPS_CODING_RAD] &&
in->Bands < 3 &&
vips_colourspace_issupported( in ) &&
saveable == VIPS_SAVEABLE_RGBA_ONLY ) {
VipsImage *out;
VipsInterpretation interpretation;
/* Do we make RGB or RGB16? We don't want to squash a 16-bit
* RGB down to 8 bits if the saver supports 16.
*/
if( vips_band_format_is8bit( format[in->BandFmt] ) )
interpretation = VIPS_INTERPRETATION_sRGB;
else
interpretation = VIPS_INTERPRETATION_RGB16;
if( vips_colourspace( in, &out, interpretation, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
/* Get the bands right. We must do this after all colourspace
* transforms, since they can change the number of bands.
*/
if( in->Coding == VIPS_CODING_NONE ) {
/* Do we need to flatten out an alpha channel? There needs to
* be an alpha there now, and this writer needs to not support
* alpha.
*/
if( (in->Bands == 2 ||
(in->Bands == 4 &&
in->Type != VIPS_INTERPRETATION_CMYK)) &&
(saveable == VIPS_SAVEABLE_MONO ||
saveable == VIPS_SAVEABLE_RGB ||
saveable == VIPS_SAVEABLE_RGB_CMYK) ) {
VipsImage *out;
if( vips_flatten( in, &out,
"background", background,
NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
/* Other alpha removal strategies ... just drop the extra
* bands.
*/
else if( in->Bands > 3 &&
(saveable == VIPS_SAVEABLE_RGB ||
(saveable == VIPS_SAVEABLE_RGB_CMYK &&
in->Type != VIPS_INTERPRETATION_CMYK)) ) {
VipsImage *out;
/* Don't let 4 bands though unless the image really is
* a CMYK.
*
* Consider a RGBA png being saved as JPG. We can
* write CMYK jpg, but we mustn't do that for RGBA
* images.
*/
if( vips_extract_band( in, &out, 0,
"n", 3,
NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
else if( in->Bands > 4 &&
((saveable == VIPS_SAVEABLE_RGB_CMYK &&
in->Type == VIPS_INTERPRETATION_CMYK) ||
saveable == VIPS_SAVEABLE_RGBA ||
saveable == VIPS_SAVEABLE_RGBA_ONLY) ) {
VipsImage *out;
if( vips_extract_band( in, &out, 0,
"n", 4,
NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
else if( in->Bands > 1 &&
saveable == VIPS_SAVEABLE_MONO ) {
VipsImage *out;
if( vips_extract_band( in, &out, 0, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
/* Else we have VIPS_SAVEABLE_ANY and we don't chop bands down.
*/
}
/* Handle the ushort interpretations.
*
* RGB16 and GREY16 use 0-65535 for black-white. If we have an image
* tagged like this, and it has more than 8 bits (we leave crazy uchar
* images tagged as RGB16 alone), we'll need to get it ready for the
* saver.
*/
if( (in->Type == VIPS_INTERPRETATION_RGB16 ||
in->Type == VIPS_INTERPRETATION_GREY16) &&
!vips_band_format_is8bit( in->BandFmt ) ) {
/* If the saver supports ushort, cast to ushort. It may be
* float at the moment, for example.
*
* If the saver does not support ushort, automatically shift
* it down. This is the behaviour we want for saving an RGB16
* image as JPG, for example.
*/
if( format[VIPS_FORMAT_USHORT] == VIPS_FORMAT_USHORT ) {
VipsImage *out;
if( vips_cast( in, &out, VIPS_FORMAT_USHORT, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
else {
VipsImage *out;
if( vips_rshift_const1( in, &out, 8, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
/* That could have produced an int image ... make sure
* we are now uchar.
*/
if( vips_cast( in, &out, VIPS_FORMAT_UCHAR, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
}
/* Cast to the output format.
*/
{
VipsImage *out;
if( vips_cast( in, &out, format[in->BandFmt], NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
/* Does this class want a coded image? Search the coding table for the
* first one.
*/
if( coding[VIPS_CODING_NONE] ) {
/* Already NONE, nothing to do.
*/
}
else if( coding[VIPS_CODING_LABQ] ) {
VipsImage *out;
if( vips_Lab2LabQ( in, &out, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
else if( coding[VIPS_CODING_RAD] ) {
VipsImage *out;
if( vips_float2rad( in, &out, NULL ) ) {
g_object_unref( in );
return( -1 );
}
g_object_unref( in );
in = out;
}
*ready = in;
return( 0 );
}
static int
vips_foreign_save_build( VipsObject *object )
{
VipsForeignSave *save = VIPS_FOREIGN_SAVE( object );
if( save->in ) {
VipsForeignSaveClass *class =
VIPS_FOREIGN_SAVE_GET_CLASS( save );
VipsImage *ready;
if( vips__foreign_convert_saveable( save->in, &ready,
class->saveable, class->format_table, class->coding,
save->background ) )
return( -1 );
if( save->page_height )
vips_image_set_int( ready,
VIPS_META_PAGE_HEIGHT, save->page_height );
VIPS_UNREF( save->ready );
save->ready = ready;
}
if( VIPS_OBJECT_CLASS( vips_foreign_save_parent_class )->
build( object ) )
return( -1 );
return( 0 );
}
#define UC VIPS_FORMAT_UCHAR
#define C VIPS_FORMAT_CHAR
#define US VIPS_FORMAT_USHORT
#define S VIPS_FORMAT_SHORT
#define UI VIPS_FORMAT_UINT
#define I VIPS_FORMAT_INT
#define F VIPS_FORMAT_FLOAT
#define X VIPS_FORMAT_COMPLEX
#define D VIPS_FORMAT_DOUBLE
#define DX VIPS_FORMAT_DPCOMPLEX
static int vips_foreign_save_format_table[10] = {
// UC C US S UI I F X D DX
UC, C, US, S, UI, I, F, X, D, DX
};
static void
vips_foreign_save_class_init( VipsForeignSaveClass *class )
{
GObjectClass *gobject_class = G_OBJECT_CLASS( class );
VipsObjectClass *object_class = (VipsObjectClass *) class;
VipsOperationClass *operation_class = (VipsOperationClass *) class;
int i;
gobject_class->dispose = vips_foreign_save_dispose;
gobject_class->set_property = vips_object_set_property;
gobject_class->get_property = vips_object_get_property;
object_class->build = vips_foreign_save_build;
object_class->summary_class = vips_foreign_save_summary_class;
object_class->new_from_string = vips_foreign_save_new_from_string;
object_class->nickname = "filesave";
object_class->description = _( "file savers" );
/* All savers are sequential by definition. Things like tiled tiff
* write and interlaced png write, which are not, add extra caches
* on their input.
*/
operation_class->flags |= VIPS_OPERATION_SEQUENTIAL;
/* Must not cache savers.
*/
operation_class->flags |= VIPS_OPERATION_NOCACHE;
/* Default to no coding allowed.
*/
for( i = 0; i < VIPS_CODING_LAST; i++ )
class->coding[i] = FALSE;
class->coding[VIPS_CODING_NONE] = TRUE;
/* Default to no cast on save.
*/
class->format_table = vips_foreign_save_format_table;
VIPS_ARG_IMAGE( class, "in", 0,
_( "Input" ),
_( "Image to save" ),
VIPS_ARGUMENT_REQUIRED_INPUT,
G_STRUCT_OFFSET( VipsForeignSave, in ) );
VIPS_ARG_BOOL( class, "strip", 100,
_( "Strip" ),
_( "Strip all metadata from image" ),
VIPS_ARGUMENT_OPTIONAL_INPUT,
G_STRUCT_OFFSET( VipsForeignSave, strip ),
FALSE );
VIPS_ARG_BOXED( class, "background", 101,
_( "Background" ),
_( "Background value" ),
VIPS_ARGUMENT_OPTIONAL_INPUT,
G_STRUCT_OFFSET( VipsForeignSave, background ),
VIPS_TYPE_ARRAY_DOUBLE );
VIPS_ARG_INT( class, "page_height", 8,
_( "Page height" ),
_( "Set page height for multipage save" ),
VIPS_ARGUMENT_OPTIONAL_INPUT,
G_STRUCT_OFFSET( VipsForeignSave, page_height ),
0, VIPS_MAX_COORD, 0 );
}
static void
vips_foreign_save_init( VipsForeignSave *save )
{
save->background = vips_array_double_newv( 1, 0.0 );
}
/* Can we write this filename with this file?
*/
static void *
vips_foreign_find_save_sub( VipsForeignSaveClass *save_class,
const char *filename )
{
VipsForeignClass *class = VIPS_FOREIGN_CLASS( save_class );
/* The suffs might be defined on an abstract base class, make sure we
* don't pick that.
*/
if( !G_TYPE_IS_ABSTRACT( G_TYPE_FROM_CLASS( class ) ) &&
class->suffs &&
vips_filename_suffix_match( filename, class->suffs ) )
return( save_class );
return( NULL );
}
/**
* vips_foreign_find_save:
* @filename: name to find a saver for
*
* Searches for an operation you could use to write to @filename.
* Any trailing options on @filename are stripped and ignored.
*
* See also: vips_foreign_find_save_buffer(), vips_image_write_to_file().
*
* Returns: the name of an operation on success, %NULL on error
*/
const char *
vips_foreign_find_save( const char *name )
{
char filename[VIPS_PATH_MAX];
char option_string[VIPS_PATH_MAX];
VipsForeignSaveClass *save_class;
vips__filename_split8( name, filename, option_string );
if( !(save_class = (VipsForeignSaveClass *) vips_foreign_map(
"VipsForeignSave",
(VipsSListMap2Fn) vips_foreign_find_save_sub,
(void *) filename, NULL )) ) {
vips_error( "VipsForeignSave",
_( "\"%s\" is not a known file format" ), name );
return( NULL );
}
return( G_OBJECT_CLASS_NAME( save_class ) );
}
/* Kept for early vips8 API compat.
*/
int
vips_foreign_save( VipsImage *in, const char *name, ... )
{
char filename[VIPS_PATH_MAX];
char option_string[VIPS_PATH_MAX];
const char *operation_name;
va_list ap;
int result;
vips__filename_split8( name, filename, option_string );
if( !(operation_name = vips_foreign_find_save( filename )) )
return( -1 );
va_start( ap, name );
result = vips_call_split_option_string( operation_name, option_string,
ap, in, filename );
va_end( ap );
return( result );
}
/* Can we write this buffer with this file type?
*/
static void *
vips_foreign_find_save_buffer_sub( VipsForeignSaveClass *save_class,
const char *suffix )
{
VipsObjectClass *object_class = VIPS_OBJECT_CLASS( save_class );
VipsForeignClass *class = VIPS_FOREIGN_CLASS( save_class );
if( class->suffs &&
vips_ispostfix( object_class->nickname, "_buffer" ) &&
vips_filename_suffix_match( suffix, class->suffs ) )
return( save_class );
return( NULL );
}
/**
* vips_foreign_find_save_buffer:
* @suffix: name to find a saver for
*
* Searches for an operation you could use to write to a buffer in @suffix
* format.
*
* See also: vips_image_write_to_buffer().
*
* Returns: the name of an operation on success, %NULL on error
*/
const char *
vips_foreign_find_save_buffer( const char *name )
{
char suffix[VIPS_PATH_MAX];
char option_string[VIPS_PATH_MAX];
VipsForeignSaveClass *save_class;
vips__filename_split8( name, suffix, option_string );
if( !(save_class = (VipsForeignSaveClass *) vips_foreign_map(
"VipsForeignSave",
(VipsSListMap2Fn) vips_foreign_find_save_buffer_sub,
(void *) suffix, NULL )) ) {
vips_error( "VipsForeignSave",
_( "\"%s\" is not a known buffer format" ), name );
return( NULL );
}
return( G_OBJECT_CLASS_NAME( save_class ) );
}
/* Called from iofuncs to init all operations in this dir. Use a plugin system
* instead?
*/
void
vips_foreign_operation_init( void )
{
extern GType vips_foreign_load_rad_get_type( void );
extern GType vips_foreign_save_rad_file_get_type( void );
extern GType vips_foreign_save_rad_buffer_get_type( void );
extern GType vips_foreign_load_mat_get_type( void );
extern GType vips_foreign_load_ppm_get_type( void );
extern GType vips_foreign_save_ppm_get_type( void );
extern GType vips_foreign_load_png_get_type( void );
extern GType vips_foreign_load_png_buffer_get_type( void );
extern GType vips_foreign_save_png_file_get_type( void );
extern GType vips_foreign_save_png_buffer_get_type( void );
extern GType vips_foreign_load_csv_get_type( void );
extern GType vips_foreign_save_csv_get_type( void );
extern GType vips_foreign_load_matrix_get_type( void );
extern GType vips_foreign_save_matrix_get_type( void );
extern GType vips_foreign_print_matrix_get_type( void );
extern GType vips_foreign_load_fits_get_type( void );
extern GType vips_foreign_save_fits_get_type( void );
extern GType vips_foreign_load_analyze_get_type( void );
extern GType vips_foreign_load_openexr_get_type( void );
extern GType vips_foreign_load_openslide_get_type( void );
extern GType vips_foreign_load_jpeg_file_get_type( void );
extern GType vips_foreign_load_jpeg_buffer_get_type( void );
extern GType vips_foreign_save_jpeg_file_get_type( void );
extern GType vips_foreign_save_jpeg_buffer_get_type( void );
extern GType vips_foreign_save_jpeg_mime_get_type( void );
extern GType vips_foreign_load_tiff_file_get_type( void );
extern GType vips_foreign_load_tiff_buffer_get_type( void );
extern GType vips_foreign_save_tiff_file_get_type( void );
extern GType vips_foreign_save_tiff_buffer_get_type( void );
extern GType vips_foreign_load_vips_get_type( void );
extern GType vips_foreign_save_vips_get_type( void );
extern GType vips_foreign_load_raw_get_type( void );
extern GType vips_foreign_save_raw_get_type( void );
extern GType vips_foreign_save_raw_fd_get_type( void );
extern GType vips_foreign_load_magick_file_get_type( void );
extern GType vips_foreign_load_magick_buffer_get_type( void );
extern GType vips_foreign_load_magick7_file_get_type( void );
extern GType vips_foreign_load_magick7_buffer_get_type( void );
extern GType vips_foreign_save_dz_file_get_type( void );
extern GType vips_foreign_save_dz_buffer_get_type( void );
extern GType vips_foreign_load_webp_file_get_type( void );
extern GType vips_foreign_load_webp_buffer_get_type( void );
extern GType vips_foreign_save_webp_file_get_type( void );
extern GType vips_foreign_save_webp_buffer_get_type( void );
extern GType vips_foreign_load_pdf_get_type( void );
extern GType vips_foreign_load_pdf_file_get_type( void );
extern GType vips_foreign_load_pdf_buffer_get_type( void );
extern GType vips_foreign_load_svg_get_type( void );
extern GType vips_foreign_load_svg_file_get_type( void );
extern GType vips_foreign_load_svg_buffer_get_type( void );
extern GType vips_foreign_load_gif_get_type( void );
extern GType vips_foreign_load_gif_file_get_type( void );
extern GType vips_foreign_load_gif_buffer_get_type( void );
vips_foreign_load_csv_get_type();
vips_foreign_save_csv_get_type();
vips_foreign_load_matrix_get_type();
vips_foreign_save_matrix_get_type();
vips_foreign_print_matrix_get_type();
vips_foreign_load_raw_get_type();
vips_foreign_save_raw_get_type();
vips_foreign_save_raw_fd_get_type();
vips_foreign_load_vips_get_type();
vips_foreign_save_vips_get_type();
#ifdef HAVE_ANALYZE
vips_foreign_load_analyze_get_type();
#endif /*HAVE_ANALYZE*/
#ifdef HAVE_PPM
vips_foreign_load_ppm_get_type();
vips_foreign_save_ppm_get_type();
#endif /*HAVE_PPM*/
#ifdef HAVE_RADIANCE
vips_foreign_load_rad_get_type();
vips_foreign_save_rad_file_get_type();
vips_foreign_save_rad_buffer_get_type();
#endif /*HAVE_RADIANCE*/
#ifdef HAVE_POPPLER
vips_foreign_load_pdf_get_type();
vips_foreign_load_pdf_file_get_type();
vips_foreign_load_pdf_buffer_get_type();
#endif /*HAVE_POPPLER*/
#ifdef HAVE_RSVG
vips_foreign_load_svg_get_type();
vips_foreign_load_svg_file_get_type();
vips_foreign_load_svg_buffer_get_type();
#endif /*HAVE_RSVG*/
#ifdef HAVE_GIFLIB
vips_foreign_load_gif_get_type();
vips_foreign_load_gif_file_get_type();
vips_foreign_load_gif_buffer_get_type();
#endif /*HAVE_GIFLIB*/
#ifdef HAVE_GSF
vips_foreign_save_dz_file_get_type();
vips_foreign_save_dz_buffer_get_type();
#endif /*HAVE_GSF*/
#ifdef HAVE_PNG
vips_foreign_load_png_get_type();
vips_foreign_load_png_buffer_get_type();
vips_foreign_save_png_file_get_type();
vips_foreign_save_png_buffer_get_type();
#endif /*HAVE_PNG*/
#ifdef HAVE_MATIO
vips_foreign_load_mat_get_type();
#endif /*HAVE_MATIO*/
#ifdef HAVE_JPEG
vips_foreign_load_jpeg_file_get_type();
vips_foreign_load_jpeg_buffer_get_type();
vips_foreign_save_jpeg_file_get_type();
vips_foreign_save_jpeg_buffer_get_type();
vips_foreign_save_jpeg_mime_get_type();
#endif /*HAVE_JPEG*/
#ifdef HAVE_LIBWEBP
vips_foreign_load_webp_file_get_type();
vips_foreign_load_webp_buffer_get_type();
vips_foreign_save_webp_file_get_type();
vips_foreign_save_webp_buffer_get_type();
#endif /*HAVE_LIBWEBP*/
#ifdef HAVE_TIFF
vips_foreign_load_tiff_file_get_type();
vips_foreign_load_tiff_buffer_get_type();
vips_foreign_save_tiff_file_get_type();
vips_foreign_save_tiff_buffer_get_type();
#endif /*HAVE_TIFF*/
#ifdef HAVE_OPENSLIDE
vips_foreign_load_openslide_get_type();
#endif /*HAVE_OPENSLIDE*/
#ifdef HAVE_MAGICK
vips_foreign_load_magick_file_get_type();
vips_foreign_load_magick_buffer_get_type();
#endif /*HAVE_MAGICK*/
#ifdef HAVE_MAGICK7
vips_foreign_load_magick7_file_get_type();
vips_foreign_load_magick7_buffer_get_type();
#endif /*HAVE_MAGICK7*/
#ifdef HAVE_CFITSIO
vips_foreign_load_fits_get_type();
vips_foreign_save_fits_get_type();
#endif /*HAVE_CFITSIO*/
#ifdef HAVE_OPENEXR
vips_foreign_load_openexr_get_type();
#endif /*HAVE_OPENEXR*/
vips__foreign_load_operation =
g_quark_from_static_string( "vips-foreign-load-operation" );
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_655_1 |
crossvul-cpp_data_bad_4808_1 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2.h"
#include "git2/odb_backend.h"
#include "smart.h"
#include "refs.h"
#include "repository.h"
#include "push.h"
#include "pack-objects.h"
#include "remote.h"
#include "util.h"
#define NETWORK_XFER_THRESHOLD (100*1024)
/* The minimal interval between progress updates (in seconds). */
#define MIN_PROGRESS_UPDATE_INTERVAL 0.5
int git_smart__store_refs(transport_smart *t, int flushes)
{
gitno_buffer *buf = &t->buffer;
git_vector *refs = &t->refs;
int error, flush = 0, recvd;
const char *line_end = NULL;
git_pkt *pkt = NULL;
size_t i;
/* Clear existing refs in case git_remote_connect() is called again
* after git_remote_disconnect().
*/
git_vector_foreach(refs, i, pkt) {
git_pkt_free(pkt);
}
git_vector_clear(refs);
pkt = NULL;
do {
if (buf->offset > 0)
error = git_pkt_parse_line(&pkt, buf->data, &line_end, buf->offset);
else
error = GIT_EBUFS;
if (error < 0 && error != GIT_EBUFS)
return error;
if (error == GIT_EBUFS) {
if ((recvd = gitno_recv(buf)) < 0)
return recvd;
if (recvd == 0) {
giterr_set(GITERR_NET, "early EOF");
return GIT_EEOF;
}
continue;
}
gitno_consume(buf, line_end);
if (pkt->type == GIT_PKT_ERR) {
giterr_set(GITERR_NET, "Remote error: %s", ((git_pkt_err *)pkt)->error);
git__free(pkt);
return -1;
}
if (pkt->type != GIT_PKT_FLUSH && git_vector_insert(refs, pkt) < 0)
return -1;
if (pkt->type == GIT_PKT_FLUSH) {
flush++;
git_pkt_free(pkt);
}
} while (flush < flushes);
return flush;
}
static int append_symref(const char **out, git_vector *symrefs, const char *ptr)
{
int error;
const char *end;
git_buf buf = GIT_BUF_INIT;
git_refspec *mapping = NULL;
ptr += strlen(GIT_CAP_SYMREF);
if (*ptr != '=')
goto on_invalid;
ptr++;
if (!(end = strchr(ptr, ' ')) &&
!(end = strchr(ptr, '\0')))
goto on_invalid;
if ((error = git_buf_put(&buf, ptr, end - ptr)) < 0)
return error;
/* symref mapping has refspec format */
mapping = git__calloc(1, sizeof(git_refspec));
GITERR_CHECK_ALLOC(mapping);
error = git_refspec__parse(mapping, git_buf_cstr(&buf), true);
git_buf_free(&buf);
/* if the error isn't OOM, then it's a parse error; let's use a nicer message */
if (error < 0) {
if (giterr_last()->klass != GITERR_NOMEMORY)
goto on_invalid;
git__free(mapping);
return error;
}
if ((error = git_vector_insert(symrefs, mapping)) < 0)
return error;
*out = end;
return 0;
on_invalid:
giterr_set(GITERR_NET, "remote sent invalid symref");
git_refspec__free(mapping);
git__free(mapping);
return -1;
}
int git_smart__detect_caps(git_pkt_ref *pkt, transport_smart_caps *caps, git_vector *symrefs)
{
const char *ptr;
/* No refs or capabilites, odd but not a problem */
if (pkt == NULL || pkt->capabilities == NULL)
return 0;
ptr = pkt->capabilities;
while (ptr != NULL && *ptr != '\0') {
if (*ptr == ' ')
ptr++;
if (!git__prefixcmp(ptr, GIT_CAP_OFS_DELTA)) {
caps->common = caps->ofs_delta = 1;
ptr += strlen(GIT_CAP_OFS_DELTA);
continue;
}
/* Keep multi_ack_detailed before multi_ack */
if (!git__prefixcmp(ptr, GIT_CAP_MULTI_ACK_DETAILED)) {
caps->common = caps->multi_ack_detailed = 1;
ptr += strlen(GIT_CAP_MULTI_ACK_DETAILED);
continue;
}
if (!git__prefixcmp(ptr, GIT_CAP_MULTI_ACK)) {
caps->common = caps->multi_ack = 1;
ptr += strlen(GIT_CAP_MULTI_ACK);
continue;
}
if (!git__prefixcmp(ptr, GIT_CAP_INCLUDE_TAG)) {
caps->common = caps->include_tag = 1;
ptr += strlen(GIT_CAP_INCLUDE_TAG);
continue;
}
/* Keep side-band check after side-band-64k */
if (!git__prefixcmp(ptr, GIT_CAP_SIDE_BAND_64K)) {
caps->common = caps->side_band_64k = 1;
ptr += strlen(GIT_CAP_SIDE_BAND_64K);
continue;
}
if (!git__prefixcmp(ptr, GIT_CAP_SIDE_BAND)) {
caps->common = caps->side_band = 1;
ptr += strlen(GIT_CAP_SIDE_BAND);
continue;
}
if (!git__prefixcmp(ptr, GIT_CAP_DELETE_REFS)) {
caps->common = caps->delete_refs = 1;
ptr += strlen(GIT_CAP_DELETE_REFS);
continue;
}
if (!git__prefixcmp(ptr, GIT_CAP_THIN_PACK)) {
caps->common = caps->thin_pack = 1;
ptr += strlen(GIT_CAP_THIN_PACK);
continue;
}
if (!git__prefixcmp(ptr, GIT_CAP_SYMREF)) {
int error;
if ((error = append_symref(&ptr, symrefs, ptr)) < 0)
return error;
continue;
}
/* We don't know this capability, so skip it */
ptr = strchr(ptr, ' ');
}
return 0;
}
static int recv_pkt(git_pkt **out, gitno_buffer *buf)
{
const char *ptr = buf->data, *line_end = ptr;
git_pkt *pkt = NULL;
int pkt_type, error = 0, ret;
do {
if (buf->offset > 0)
error = git_pkt_parse_line(&pkt, ptr, &line_end, buf->offset);
else
error = GIT_EBUFS;
if (error == 0)
break; /* return the pkt */
if (error < 0 && error != GIT_EBUFS)
return error;
if ((ret = gitno_recv(buf)) < 0) {
return ret;
} else if (ret == 0) {
giterr_set(GITERR_NET, "early EOF");
return GIT_EEOF;
}
} while (error);
gitno_consume(buf, line_end);
pkt_type = pkt->type;
if (out != NULL)
*out = pkt;
else
git__free(pkt);
return pkt_type;
}
static int store_common(transport_smart *t)
{
git_pkt *pkt = NULL;
gitno_buffer *buf = &t->buffer;
int error;
do {
if ((error = recv_pkt(&pkt, buf)) < 0)
return error;
if (pkt->type == GIT_PKT_ACK) {
if (git_vector_insert(&t->common, pkt) < 0)
return -1;
} else {
git__free(pkt);
return 0;
}
} while (1);
return 0;
}
static int fetch_setup_walk(git_revwalk **out, git_repository *repo)
{
git_revwalk *walk = NULL;
git_strarray refs;
unsigned int i;
git_reference *ref;
int error;
if ((error = git_reference_list(&refs, repo)) < 0)
return error;
if ((error = git_revwalk_new(&walk, repo)) < 0)
return error;
git_revwalk_sorting(walk, GIT_SORT_TIME);
for (i = 0; i < refs.count; ++i) {
/* No tags */
if (!git__prefixcmp(refs.strings[i], GIT_REFS_TAGS_DIR))
continue;
if ((error = git_reference_lookup(&ref, repo, refs.strings[i])) < 0)
goto on_error;
if (git_reference_type(ref) == GIT_REF_SYMBOLIC)
continue;
if ((error = git_revwalk_push(walk, git_reference_target(ref))) < 0)
goto on_error;
git_reference_free(ref);
}
git_strarray_free(&refs);
*out = walk;
return 0;
on_error:
git_revwalk_free(walk);
git_reference_free(ref);
git_strarray_free(&refs);
return error;
}
static int wait_while_ack(gitno_buffer *buf)
{
int error;
git_pkt_ack *pkt = NULL;
while (1) {
git__free(pkt);
if ((error = recv_pkt((git_pkt **)&pkt, buf)) < 0)
return error;
if (pkt->type == GIT_PKT_NAK)
break;
if (pkt->type == GIT_PKT_ACK &&
(pkt->status != GIT_ACK_CONTINUE &&
pkt->status != GIT_ACK_COMMON)) {
git__free(pkt);
return 0;
}
}
git__free(pkt);
return 0;
}
int git_smart__negotiate_fetch(git_transport *transport, git_repository *repo, const git_remote_head * const *wants, size_t count)
{
transport_smart *t = (transport_smart *)transport;
gitno_buffer *buf = &t->buffer;
git_buf data = GIT_BUF_INIT;
git_revwalk *walk = NULL;
int error = -1, pkt_type;
unsigned int i;
git_oid oid;
if ((error = git_pkt_buffer_wants(wants, count, &t->caps, &data)) < 0)
return error;
if ((error = fetch_setup_walk(&walk, repo)) < 0)
goto on_error;
/*
* Our support for ACK extensions is simply to parse them. On
* the first ACK we will accept that as enough common
* objects. We give up if we haven't found an answer in the
* first 256 we send.
*/
i = 0;
while (i < 256) {
error = git_revwalk_next(&oid, walk);
if (error < 0) {
if (GIT_ITEROVER == error)
break;
goto on_error;
}
git_pkt_buffer_have(&oid, &data);
i++;
if (i % 20 == 0) {
if (t->cancelled.val) {
giterr_set(GITERR_NET, "The fetch was cancelled by the user");
error = GIT_EUSER;
goto on_error;
}
git_pkt_buffer_flush(&data);
if (git_buf_oom(&data)) {
error = -1;
goto on_error;
}
if ((error = git_smart__negotiation_step(&t->parent, data.ptr, data.size)) < 0)
goto on_error;
git_buf_clear(&data);
if (t->caps.multi_ack || t->caps.multi_ack_detailed) {
if ((error = store_common(t)) < 0)
goto on_error;
} else {
pkt_type = recv_pkt(NULL, buf);
if (pkt_type == GIT_PKT_ACK) {
break;
} else if (pkt_type == GIT_PKT_NAK) {
continue;
} else if (pkt_type < 0) {
/* recv_pkt returned an error */
error = pkt_type;
goto on_error;
} else {
giterr_set(GITERR_NET, "Unexpected pkt type");
error = -1;
goto on_error;
}
}
}
if (t->common.length > 0)
break;
if (i % 20 == 0 && t->rpc) {
git_pkt_ack *pkt;
unsigned int j;
if ((error = git_pkt_buffer_wants(wants, count, &t->caps, &data)) < 0)
goto on_error;
git_vector_foreach(&t->common, j, pkt) {
if ((error = git_pkt_buffer_have(&pkt->oid, &data)) < 0)
goto on_error;
}
if (git_buf_oom(&data)) {
error = -1;
goto on_error;
}
}
}
/* Tell the other end that we're done negotiating */
if (t->rpc && t->common.length > 0) {
git_pkt_ack *pkt;
unsigned int j;
if ((error = git_pkt_buffer_wants(wants, count, &t->caps, &data)) < 0)
goto on_error;
git_vector_foreach(&t->common, j, pkt) {
if ((error = git_pkt_buffer_have(&pkt->oid, &data)) < 0)
goto on_error;
}
if (git_buf_oom(&data)) {
error = -1;
goto on_error;
}
}
if ((error = git_pkt_buffer_done(&data)) < 0)
goto on_error;
if (t->cancelled.val) {
giterr_set(GITERR_NET, "The fetch was cancelled by the user");
error = GIT_EUSER;
goto on_error;
}
if ((error = git_smart__negotiation_step(&t->parent, data.ptr, data.size)) < 0)
goto on_error;
git_buf_free(&data);
git_revwalk_free(walk);
/* Now let's eat up whatever the server gives us */
if (!t->caps.multi_ack && !t->caps.multi_ack_detailed) {
pkt_type = recv_pkt(NULL, buf);
if (pkt_type < 0) {
return pkt_type;
} else if (pkt_type != GIT_PKT_ACK && pkt_type != GIT_PKT_NAK) {
giterr_set(GITERR_NET, "Unexpected pkt type");
return -1;
}
} else {
error = wait_while_ack(buf);
}
return error;
on_error:
git_revwalk_free(walk);
git_buf_free(&data);
return error;
}
static int no_sideband(transport_smart *t, struct git_odb_writepack *writepack, gitno_buffer *buf, git_transfer_progress *stats)
{
int recvd;
do {
if (t->cancelled.val) {
giterr_set(GITERR_NET, "The fetch was cancelled by the user");
return GIT_EUSER;
}
if (writepack->append(writepack, buf->data, buf->offset, stats) < 0)
return -1;
gitno_consume_n(buf, buf->offset);
if ((recvd = gitno_recv(buf)) < 0)
return recvd;
} while(recvd > 0);
if (writepack->commit(writepack, stats) < 0)
return -1;
return 0;
}
struct network_packetsize_payload
{
git_transfer_progress_cb callback;
void *payload;
git_transfer_progress *stats;
size_t last_fired_bytes;
};
static int network_packetsize(size_t received, void *payload)
{
struct network_packetsize_payload *npp = (struct network_packetsize_payload*)payload;
/* Accumulate bytes */
npp->stats->received_bytes += received;
/* Fire notification if the threshold is reached */
if ((npp->stats->received_bytes - npp->last_fired_bytes) > NETWORK_XFER_THRESHOLD) {
npp->last_fired_bytes = npp->stats->received_bytes;
if (npp->callback(npp->stats, npp->payload))
return GIT_EUSER;
}
return 0;
}
int git_smart__download_pack(
git_transport *transport,
git_repository *repo,
git_transfer_progress *stats,
git_transfer_progress_cb transfer_progress_cb,
void *progress_payload)
{
transport_smart *t = (transport_smart *)transport;
gitno_buffer *buf = &t->buffer;
git_odb *odb;
struct git_odb_writepack *writepack = NULL;
int error = 0;
struct network_packetsize_payload npp = {0};
memset(stats, 0, sizeof(git_transfer_progress));
if (transfer_progress_cb) {
npp.callback = transfer_progress_cb;
npp.payload = progress_payload;
npp.stats = stats;
t->packetsize_cb = &network_packetsize;
t->packetsize_payload = &npp;
/* We might have something in the buffer already from negotiate_fetch */
if (t->buffer.offset > 0 && !t->cancelled.val)
if (t->packetsize_cb(t->buffer.offset, t->packetsize_payload))
git_atomic_set(&t->cancelled, 1);
}
if ((error = git_repository_odb__weakptr(&odb, repo)) < 0 ||
((error = git_odb_write_pack(&writepack, odb, transfer_progress_cb, progress_payload)) != 0))
goto done;
/*
* If the remote doesn't support the side-band, we can feed
* the data directly to the pack writer. Otherwise, we need to
* check which one belongs there.
*/
if (!t->caps.side_band && !t->caps.side_band_64k) {
error = no_sideband(t, writepack, buf, stats);
goto done;
}
do {
git_pkt *pkt = NULL;
/* Check cancellation before network call */
if (t->cancelled.val) {
giterr_clear();
error = GIT_EUSER;
goto done;
}
if ((error = recv_pkt(&pkt, buf)) >= 0) {
/* Check cancellation after network call */
if (t->cancelled.val) {
giterr_clear();
error = GIT_EUSER;
} else if (pkt->type == GIT_PKT_PROGRESS) {
if (t->progress_cb) {
git_pkt_progress *p = (git_pkt_progress *) pkt;
error = t->progress_cb(p->data, p->len, t->message_cb_payload);
}
} else if (pkt->type == GIT_PKT_DATA) {
git_pkt_data *p = (git_pkt_data *) pkt;
if (p->len)
error = writepack->append(writepack, p->data, p->len, stats);
} else if (pkt->type == GIT_PKT_FLUSH) {
/* A flush indicates the end of the packfile */
git__free(pkt);
break;
}
}
git__free(pkt);
if (error < 0)
goto done;
} while (1);
/*
* Trailing execution of transfer_progress_cb, if necessary...
* Only the callback through the npp datastructure currently
* updates the last_fired_bytes value. It is possible that
* progress has already been reported with the correct
* "received_bytes" value, but until (if?) this is unified
* then we will report progress again to be sure that the
* correct last received_bytes value is reported.
*/
if (npp.callback && npp.stats->received_bytes > npp.last_fired_bytes) {
error = npp.callback(npp.stats, npp.payload);
if (error != 0)
goto done;
}
error = writepack->commit(writepack, stats);
done:
if (writepack)
writepack->free(writepack);
if (transfer_progress_cb) {
t->packetsize_cb = NULL;
t->packetsize_payload = NULL;
}
return error;
}
static int gen_pktline(git_buf *buf, git_push *push)
{
push_spec *spec;
size_t i, len;
char old_id[GIT_OID_HEXSZ+1], new_id[GIT_OID_HEXSZ+1];
old_id[GIT_OID_HEXSZ] = '\0'; new_id[GIT_OID_HEXSZ] = '\0';
git_vector_foreach(&push->specs, i, spec) {
len = 2*GIT_OID_HEXSZ + 7 + strlen(spec->refspec.dst);
if (i == 0) {
++len; /* '\0' */
if (push->report_status)
len += strlen(GIT_CAP_REPORT_STATUS) + 1;
len += strlen(GIT_CAP_SIDE_BAND_64K) + 1;
}
git_oid_fmt(old_id, &spec->roid);
git_oid_fmt(new_id, &spec->loid);
git_buf_printf(buf, "%04"PRIxZ"%s %s %s", len, old_id, new_id, spec->refspec.dst);
if (i == 0) {
git_buf_putc(buf, '\0');
/* Core git always starts their capabilities string with a space */
if (push->report_status) {
git_buf_putc(buf, ' ');
git_buf_printf(buf, GIT_CAP_REPORT_STATUS);
}
git_buf_putc(buf, ' ');
git_buf_printf(buf, GIT_CAP_SIDE_BAND_64K);
}
git_buf_putc(buf, '\n');
}
git_buf_puts(buf, "0000");
return git_buf_oom(buf) ? -1 : 0;
}
static int add_push_report_pkt(git_push *push, git_pkt *pkt)
{
push_status *status;
switch (pkt->type) {
case GIT_PKT_OK:
status = git__calloc(1, sizeof(push_status));
GITERR_CHECK_ALLOC(status);
status->msg = NULL;
status->ref = git__strdup(((git_pkt_ok *)pkt)->ref);
if (!status->ref ||
git_vector_insert(&push->status, status) < 0) {
git_push_status_free(status);
return -1;
}
break;
case GIT_PKT_NG:
status = git__calloc(1, sizeof(push_status));
GITERR_CHECK_ALLOC(status);
status->ref = git__strdup(((git_pkt_ng *)pkt)->ref);
status->msg = git__strdup(((git_pkt_ng *)pkt)->msg);
if (!status->ref || !status->msg ||
git_vector_insert(&push->status, status) < 0) {
git_push_status_free(status);
return -1;
}
break;
case GIT_PKT_UNPACK:
push->unpack_ok = ((git_pkt_unpack *)pkt)->unpack_ok;
break;
case GIT_PKT_FLUSH:
return GIT_ITEROVER;
default:
giterr_set(GITERR_NET, "report-status: protocol error");
return -1;
}
return 0;
}
static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf)
{
git_pkt *pkt;
const char *line, *line_end = NULL;
size_t line_len;
int error;
int reading_from_buf = data_pkt_buf->size > 0;
if (reading_from_buf) {
/* We had an existing partial packet, so add the new
* packet to the buffer and parse the whole thing */
git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len);
line = data_pkt_buf->ptr;
line_len = data_pkt_buf->size;
}
else {
line = data_pkt->data;
line_len = data_pkt->len;
}
while (line_len > 0) {
error = git_pkt_parse_line(&pkt, line, &line_end, line_len);
if (error == GIT_EBUFS) {
/* Buffer the data when the inner packet is split
* across multiple sideband packets */
if (!reading_from_buf)
git_buf_put(data_pkt_buf, line, line_len);
error = 0;
goto done;
}
else if (error < 0)
goto done;
/* Advance in the buffer */
line_len -= (line_end - line);
line = line_end;
/* When a valid packet with no content has been
* read, git_pkt_parse_line does not report an
* error, but the pkt pointer has not been set.
* Handle this by skipping over empty packets.
*/
if (pkt == NULL)
continue;
error = add_push_report_pkt(push, pkt);
git_pkt_free(pkt);
if (error < 0 && error != GIT_ITEROVER)
goto done;
}
error = 0;
done:
if (reading_from_buf)
git_buf_consume(data_pkt_buf, line_end);
return error;
}
static int parse_report(transport_smart *transport, git_push *push)
{
git_pkt *pkt = NULL;
const char *line_end = NULL;
gitno_buffer *buf = &transport->buffer;
int error, recvd;
git_buf data_pkt_buf = GIT_BUF_INIT;
for (;;) {
if (buf->offset > 0)
error = git_pkt_parse_line(&pkt, buf->data,
&line_end, buf->offset);
else
error = GIT_EBUFS;
if (error < 0 && error != GIT_EBUFS) {
error = -1;
goto done;
}
if (error == GIT_EBUFS) {
if ((recvd = gitno_recv(buf)) < 0) {
error = recvd;
goto done;
}
if (recvd == 0) {
giterr_set(GITERR_NET, "early EOF");
error = GIT_EEOF;
goto done;
}
continue;
}
gitno_consume(buf, line_end);
error = 0;
if (pkt == NULL)
continue;
switch (pkt->type) {
case GIT_PKT_DATA:
/* This is a sideband packet which contains other packets */
error = add_push_report_sideband_pkt(push, (git_pkt_data *)pkt, &data_pkt_buf);
break;
case GIT_PKT_ERR:
giterr_set(GITERR_NET, "report-status: Error reported: %s",
((git_pkt_err *)pkt)->error);
error = -1;
break;
case GIT_PKT_PROGRESS:
if (transport->progress_cb) {
git_pkt_progress *p = (git_pkt_progress *) pkt;
error = transport->progress_cb(p->data, p->len, transport->message_cb_payload);
}
break;
default:
error = add_push_report_pkt(push, pkt);
break;
}
git_pkt_free(pkt);
/* add_push_report_pkt returns GIT_ITEROVER when it receives a flush */
if (error == GIT_ITEROVER) {
error = 0;
if (data_pkt_buf.size > 0) {
/* If there was data remaining in the pack data buffer,
* then the server sent a partial pkt-line */
giterr_set(GITERR_NET, "Incomplete pack data pkt-line");
error = GIT_ERROR;
}
goto done;
}
if (error < 0) {
goto done;
}
}
done:
git_buf_free(&data_pkt_buf);
return error;
}
static int add_ref_from_push_spec(git_vector *refs, push_spec *push_spec)
{
git_pkt_ref *added = git__calloc(1, sizeof(git_pkt_ref));
GITERR_CHECK_ALLOC(added);
added->type = GIT_PKT_REF;
git_oid_cpy(&added->head.oid, &push_spec->loid);
added->head.name = git__strdup(push_spec->refspec.dst);
if (!added->head.name ||
git_vector_insert(refs, added) < 0) {
git_pkt_free((git_pkt *)added);
return -1;
}
return 0;
}
static int update_refs_from_report(
git_vector *refs,
git_vector *push_specs,
git_vector *push_report)
{
git_pkt_ref *ref;
push_spec *push_spec;
push_status *push_status;
size_t i, j, refs_len;
int cmp;
/* For each push spec we sent to the server, we should have
* gotten back a status packet in the push report */
if (push_specs->length != push_report->length) {
giterr_set(GITERR_NET, "report-status: protocol error");
return -1;
}
/* We require that push_specs be sorted with push_spec_rref_cmp,
* and that push_report be sorted with push_status_ref_cmp */
git_vector_sort(push_specs);
git_vector_sort(push_report);
git_vector_foreach(push_specs, i, push_spec) {
push_status = git_vector_get(push_report, i);
/* For each push spec we sent to the server, we should have
* gotten back a status packet in the push report which matches */
if (strcmp(push_spec->refspec.dst, push_status->ref)) {
giterr_set(GITERR_NET, "report-status: protocol error");
return -1;
}
}
/* We require that refs be sorted with ref_name_cmp */
git_vector_sort(refs);
i = j = 0;
refs_len = refs->length;
/* Merge join push_specs with refs */
while (i < push_specs->length && j < refs_len) {
push_spec = git_vector_get(push_specs, i);
push_status = git_vector_get(push_report, i);
ref = git_vector_get(refs, j);
cmp = strcmp(push_spec->refspec.dst, ref->head.name);
/* Iterate appropriately */
if (cmp <= 0) i++;
if (cmp >= 0) j++;
/* Add case */
if (cmp < 0 &&
!push_status->msg &&
add_ref_from_push_spec(refs, push_spec) < 0)
return -1;
/* Update case, delete case */
if (cmp == 0 &&
!push_status->msg)
git_oid_cpy(&ref->head.oid, &push_spec->loid);
}
for (; i < push_specs->length; i++) {
push_spec = git_vector_get(push_specs, i);
push_status = git_vector_get(push_report, i);
/* Add case */
if (!push_status->msg &&
add_ref_from_push_spec(refs, push_spec) < 0)
return -1;
}
/* Remove any refs which we updated to have a zero OID. */
git_vector_rforeach(refs, i, ref) {
if (git_oid_iszero(&ref->head.oid)) {
git_vector_remove(refs, i);
git_pkt_free((git_pkt *)ref);
}
}
git_vector_sort(refs);
return 0;
}
struct push_packbuilder_payload
{
git_smart_subtransport_stream *stream;
git_packbuilder *pb;
git_push_transfer_progress cb;
void *cb_payload;
size_t last_bytes;
double last_progress_report_time;
};
static int stream_thunk(void *buf, size_t size, void *data)
{
int error = 0;
struct push_packbuilder_payload *payload = data;
if ((error = payload->stream->write(payload->stream, (const char *)buf, size)) < 0)
return error;
if (payload->cb) {
double current_time = git__timer();
payload->last_bytes += size;
if ((current_time - payload->last_progress_report_time) >= MIN_PROGRESS_UPDATE_INTERVAL) {
payload->last_progress_report_time = current_time;
error = payload->cb(payload->pb->nr_written, payload->pb->nr_objects, payload->last_bytes, payload->cb_payload);
}
}
return error;
}
int git_smart__push(git_transport *transport, git_push *push, const git_remote_callbacks *cbs)
{
transport_smart *t = (transport_smart *)transport;
struct push_packbuilder_payload packbuilder_payload = {0};
git_buf pktline = GIT_BUF_INIT;
int error = 0, need_pack = 0;
push_spec *spec;
unsigned int i;
packbuilder_payload.pb = push->pb;
if (cbs && cbs->push_transfer_progress) {
packbuilder_payload.cb = cbs->push_transfer_progress;
packbuilder_payload.cb_payload = cbs->payload;
}
#ifdef PUSH_DEBUG
{
git_remote_head *head;
char hex[GIT_OID_HEXSZ+1]; hex[GIT_OID_HEXSZ] = '\0';
git_vector_foreach(&push->remote->refs, i, head) {
git_oid_fmt(hex, &head->oid);
fprintf(stderr, "%s (%s)\n", hex, head->name);
}
git_vector_foreach(&push->specs, i, spec) {
git_oid_fmt(hex, &spec->roid);
fprintf(stderr, "%s (%s) -> ", hex, spec->lref);
git_oid_fmt(hex, &spec->loid);
fprintf(stderr, "%s (%s)\n", hex, spec->rref ?
spec->rref : spec->lref);
}
}
#endif
/*
* Figure out if we need to send a packfile; which is in all
* cases except when we only send delete commands
*/
git_vector_foreach(&push->specs, i, spec) {
if (spec->refspec.src && spec->refspec.src[0] != '\0') {
need_pack = 1;
break;
}
}
if ((error = git_smart__get_push_stream(t, &packbuilder_payload.stream)) < 0 ||
(error = gen_pktline(&pktline, push)) < 0 ||
(error = packbuilder_payload.stream->write(packbuilder_payload.stream, git_buf_cstr(&pktline), git_buf_len(&pktline))) < 0)
goto done;
if (need_pack &&
(error = git_packbuilder_foreach(push->pb, &stream_thunk, &packbuilder_payload)) < 0)
goto done;
/* If we sent nothing or the server doesn't support report-status, then
* we consider the pack to have been unpacked successfully */
if (!push->specs.length || !push->report_status)
push->unpack_ok = 1;
else if ((error = parse_report(t, push)) < 0)
goto done;
/* If progress is being reported write the final report */
if (cbs && cbs->push_transfer_progress) {
error = cbs->push_transfer_progress(
push->pb->nr_written,
push->pb->nr_objects,
packbuilder_payload.last_bytes,
cbs->payload);
if (error < 0)
goto done;
}
if (push->status.length) {
error = update_refs_from_report(&t->refs, &push->specs, &push->status);
if (error < 0)
goto done;
error = git_smart__update_heads(t, NULL);
}
done:
git_buf_free(&pktline);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_4808_1 |
crossvul-cpp_data_bad_861_0 | /* $Id: upnpsoap.c,v 1.151 2018/03/13 10:32:53 nanard Exp $ */
/* vim: tabstop=4 shiftwidth=4 noexpandtab
* MiniUPnP project
* http://miniupnp.free.fr/ or https://miniupnp.tuxfamily.org/
* (c) 2006-2018 Thomas Bernard
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <unistd.h>
#include <syslog.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <ctype.h>
#include "macros.h"
#include "config.h"
#include "upnpglobalvars.h"
#include "upnphttp.h"
#include "upnpsoap.h"
#include "upnpreplyparse.h"
#include "upnpredirect.h"
#include "upnppinhole.h"
#include "getifaddr.h"
#include "getifstats.h"
#include "getconnstatus.h"
#include "upnpurns.h"
#include "upnputils.h"
/* utility function */
static int is_numeric(const char * s)
{
while(*s) {
if(*s < '0' || *s > '9') return 0;
s++;
}
return 1;
}
static void
BuildSendAndCloseSoapResp(struct upnphttp * h,
const char * body, int bodylen)
{
static const char beforebody[] =
"<?xml version=\"1.0\"?>\r\n"
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body>";
static const char afterbody[] =
"</s:Body>"
"</s:Envelope>\r\n";
int r = BuildHeader_upnphttp(h, 200, "OK", sizeof(beforebody) - 1
+ sizeof(afterbody) - 1 + bodylen );
if(r >= 0) {
memcpy(h->res_buf + h->res_buflen, beforebody, sizeof(beforebody) - 1);
h->res_buflen += sizeof(beforebody) - 1;
memcpy(h->res_buf + h->res_buflen, body, bodylen);
h->res_buflen += bodylen;
memcpy(h->res_buf + h->res_buflen, afterbody, sizeof(afterbody) - 1);
h->res_buflen += sizeof(afterbody) - 1;
} else {
BuildResp2_upnphttp(h, 500, "Internal Server Error", NULL, 0);
}
SendRespAndClose_upnphttp(h);
}
static void
GetConnectionTypeInfo(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:GetConnectionTypeInfoResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"<NewConnectionType>IP_Routed</NewConnectionType>"
"<NewPossibleConnectionTypes>IP_Routed</NewPossibleConnectionTypes>"
"</u:GetConnectionTypeInfoResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewConnectionType>IP_Routed</NewConnectionType>"
"<NewPossibleConnectionTypes>IP_Routed</NewPossibleConnectionTypes>"
"</u:%sResponse>";
char body[512];
int bodylen;
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
/* maximum value for a UPNP ui4 type variable */
#define UPNP_UI4_MAX (4294967295ul)
static void
GetTotalBytesSent(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalBytesSent>%lu</NewTotalBytesSent>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.obytes & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.obytes, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalBytesReceived(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalBytesReceived>%lu</NewTotalBytesReceived>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
/* TotalBytesReceived
* This variable represents the cumulative counter for total number of
* bytes received downstream across all connection service instances on
* WANDevice. The count rolls over to 0 after it reaching the maximum
* value (2^32)-1. */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.ibytes & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.ibytes, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalPacketsSent(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalPacketsSent>%lu</NewTotalPacketsSent>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1",*/
#ifdef UPNP_STRICT
r<0?0:(data.opackets & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.opackets, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalPacketsReceived(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalPacketsReceived>%lu</NewTotalPacketsReceived>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.ipackets & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.ipackets, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetCommonLinkProperties(struct upnphttp * h, const char * action, const char * ns)
{
/* WANAccessType : set depending on the hardware :
* DSL, POTS (plain old Telephone service), Cable, Ethernet */
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewWANAccessType>%s</NewWANAccessType>"
"<NewLayer1UpstreamMaxBitRate>%lu</NewLayer1UpstreamMaxBitRate>"
"<NewLayer1DownstreamMaxBitRate>%lu</NewLayer1DownstreamMaxBitRate>"
"<NewPhysicalLinkStatus>%s</NewPhysicalLinkStatus>"
"</u:%sResponse>";
char body[2048];
int bodylen;
struct ifdata data;
const char * status = "Up"; /* Up, Down (Required),
* Initializing, Unavailable (Optional) */
const char * wan_access_type = "Cable"; /* DSL, POTS, Cable, Ethernet */
char ext_ip_addr[INET_ADDRSTRLEN];
if((downstream_bitrate == 0) || (upstream_bitrate == 0))
{
if(getifstats(ext_if_name, &data) >= 0)
{
if(downstream_bitrate == 0) downstream_bitrate = data.baudrate;
if(upstream_bitrate == 0) upstream_bitrate = data.baudrate;
}
}
if(getifaddr(ext_if_name, ext_ip_addr, INET_ADDRSTRLEN, NULL, NULL) < 0) {
status = "Down";
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
wan_access_type,
upstream_bitrate, downstream_bitrate,
status, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetStatusInfo(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewConnectionStatus>%s</NewConnectionStatus>"
"<NewLastConnectionError>ERROR_NONE</NewLastConnectionError>"
"<NewUptime>%ld</NewUptime>"
"</u:%sResponse>";
char body[512];
int bodylen;
time_t uptime;
const char * status;
/* ConnectionStatus possible values :
* Unconfigured, Connecting, Connected, PendingDisconnect,
* Disconnecting, Disconnected */
status = get_wan_connection_status_str(ext_if_name);
uptime = upnp_get_uptime();
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
status, (long)uptime, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetNATRSIPStatus(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:GetNATRSIPStatusResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"<NewRSIPAvailable>0</NewRSIPAvailable>"
"<NewNATEnabled>1</NewNATEnabled>"
"</u:GetNATRSIPStatusResponse>";
UNUSED(action);
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewRSIPAvailable>0</NewRSIPAvailable>"
"<NewNATEnabled>1</NewNATEnabled>"
"</u:%sResponse>";
char body[512];
int bodylen;
/* 2.2.9. RSIPAvailable
* This variable indicates if Realm-specific IP (RSIP) is available
* as a feature on the InternetGatewayDevice. RSIP is being defined
* in the NAT working group in the IETF to allow host-NATing using
* a standard set of message exchanges. It also allows end-to-end
* applications that otherwise break if NAT is introduced
* (e.g. IPsec-based VPNs).
* A gateway that does not support RSIP should set this variable to 0. */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetExternalIPAddress(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewExternalIPAddress>%s</NewExternalIPAddress>"
"</u:%sResponse>";
char body[512];
int bodylen;
char ext_ip_addr[INET_ADDRSTRLEN];
/* Does that method need to work with IPv6 ?
* There is usually no NAT with IPv6 */
#ifndef MULTIPLE_EXTERNAL_IP
struct in_addr addr;
if(use_ext_ip_addr)
{
strncpy(ext_ip_addr, use_ext_ip_addr, INET_ADDRSTRLEN);
ext_ip_addr[INET_ADDRSTRLEN - 1] = '\0';
}
else if(getifaddr(ext_if_name, ext_ip_addr, INET_ADDRSTRLEN, &addr, NULL) < 0)
{
syslog(LOG_ERR, "Failed to get ip address for interface %s",
ext_if_name);
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
}
if (addr_is_reserved(&addr))
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
#else
struct lan_addr_s * lan_addr;
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
for(lan_addr = lan_addrs.lh_first; lan_addr != NULL; lan_addr = lan_addr->list.le_next)
{
if( (h->clientaddr.s_addr & lan_addr->mask.s_addr)
== (lan_addr->addr.s_addr & lan_addr->mask.s_addr))
{
strncpy(ext_ip_addr, lan_addr->ext_ip_str, INET_ADDRSTRLEN);
break;
}
}
#endif
if (strcmp(ext_ip_addr, "0.0.0.0") == 0)
{
SoapError(h, 501, "Action Failed");
return;
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
ext_ip_addr, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
/* AddPortMapping method of WANIPConnection Service
* Ignored argument : NewEnabled */
static void
AddPortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
/*static const char resp[] =
"<u:AddPortMappingResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\"/>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\"/>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * ext_port, * protocol, * desc;
char * leaseduration_str;
unsigned int leaseduration;
char * r_host;
unsigned short iport, eport;
struct hostent *hp; /* getbyhostname() */
char ** ptr; /* getbyhostname() */
struct in_addr result_ip;/*unsigned char result_ip[16];*/ /* inet_pton() */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "NewInternalClient");
if (int_ip) {
/* trim */
while(int_ip[0] == ' ')
int_ip++;
}
#ifdef UPNP_STRICT
if (!int_ip || int_ip[0] == '\0')
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#endif
/* IGD 2 MUST support both wildcard and specific IP address values
* for RemoteHost (only the wildcard value was REQUIRED in release 1.0) */
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
#ifndef UPNP_STRICT
/* if <NewInternalClient> arg is empty, use client address
* see https://github.com/miniupnp/miniupnp/issues/236 */
if (!int_ip || int_ip[0] == '\0')
{
int_ip = h->clientaddr_str;
memcpy(&result_ip, &(h->clientaddr), sizeof(struct in_addr));
}
else
#endif
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET, int_ip, &result_ip) <= 0)
{
hp = gethostbyname(int_ip);
if(hp && hp->h_addrtype == AF_INET)
{
for(ptr = hp->h_addr_list; ptr && *ptr; ptr++)
{
int_ip = inet_ntoa(*((struct in_addr *) *ptr));
result_ip = *((struct in_addr *) *ptr);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
}
/* check if NewInternalAddress is the client address */
if(GETFLAG(SECUREMODEMASK))
{
if(h->clientaddr.s_addr != result_ip.s_addr)
{
syslog(LOG_INFO, "Client %s tried to redirect port to %s",
inet_ntoa(h->clientaddr), int_ip);
ClearNameValueList(&data);
SoapError(h, 718, "ConflictInMappingEntry");
return;
}
}
int_port = GetValueFromNameValueList(&data, "NewInternalPort");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
desc = GetValueFromNameValueList(&data, "NewPortMappingDescription");
leaseduration_str = GetValueFromNameValueList(&data, "NewLeaseDuration");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
eport = (unsigned short)atoi(ext_port);
iport = (unsigned short)atoi(int_port);
if (strcmp(ext_port, "*") == 0 || eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 716, "Wildcard not permited in ExtPort");
return;
}
leaseduration = leaseduration_str ? atoi(leaseduration_str) : 0;
#ifdef IGD_V2
/* PortMappingLeaseDuration can be either a value between 1 and
* 604800 seconds or the zero value (for infinite lease time).
* Note that an infinite lease time can be only set by out-of-band
* mechanisms like WWW-administration, remote management or local
* management.
* If a control point uses the value 0 to indicate an infinite lease
* time mapping, it is REQUIRED that gateway uses the maximum value
* instead (e.g. 604800 seconds) */
if(leaseduration == 0 || leaseduration > 604800)
leaseduration = 604800;
#endif
syslog(LOG_INFO, "%s: ext port %hu to %s:%hu protocol %s for: %s leaseduration=%u rhost=%s",
action, eport, int_ip, iport, protocol, desc, leaseduration,
r_host ? r_host : "NULL");
r = upnp_redirect(r_host, eport, int_ip, iport, protocol, desc, leaseduration);
ClearNameValueList(&data);
/* possible error codes for AddPortMapping :
* 402 - Invalid Args
* 501 - Action Failed
* 715 - Wildcard not permited in SrcAddr
* 716 - Wildcard not permited in ExtPort
* 718 - ConflictInMappingEntry
* 724 - SamePortValuesRequired (deprecated in IGD v2)
* 725 - OnlyPermanentLeasesSupported
The NAT implementation only supports permanent lease times on
port mappings (deprecated in IGD v2)
* 726 - RemoteHostOnlySupportsWildcard
RemoteHost must be a wildcard and cannot be a specific IP
address or DNS name (deprecated in IGD v2)
* 727 - ExternalPortOnlySupportsWildcard
ExternalPort must be a wildcard and cannot be a specific port
value (deprecated in IGD v2)
* 728 - NoPortMapsAvailable
There are not enough free ports available to complete the mapping
(added in IGD v2)
* 729 - ConflictWithOtherMechanisms (added in IGD v2) */
switch(r)
{
case 0: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*SERVICE_TYPE_WANIPC*/);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -4:
#ifdef IGD_V2
SoapError(h, 729, "ConflictWithOtherMechanisms");
break;
#endif /* IGD_V2 */
case -2: /* already redirected */
case -3: /* not permitted */
SoapError(h, 718, "ConflictInMappingEntry");
break;
default:
SoapError(h, 501, "ActionFailed");
}
}
/* AddAnyPortMapping was added in WANIPConnection v2 */
static void
AddAnyPortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewReservedPort>%hu</NewReservedPort>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * int_ip, * int_port, * ext_port, * protocol, * desc;
const char * r_host;
unsigned short iport, eport;
const char * leaseduration_str;
unsigned int leaseduration;
struct hostent *hp; /* getbyhostname() */
char ** ptr; /* getbyhostname() */
struct in_addr result_ip;/*unsigned char result_ip[16];*/ /* inet_pton() */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
int_port = GetValueFromNameValueList(&data, "NewInternalPort");
int_ip = GetValueFromNameValueList(&data, "NewInternalClient");
/* NewEnabled */
desc = GetValueFromNameValueList(&data, "NewPortMappingDescription");
leaseduration_str = GetValueFromNameValueList(&data, "NewLeaseDuration");
leaseduration = leaseduration_str ? atoi(leaseduration_str) : 0;
if(leaseduration == 0)
leaseduration = 604800;
if (!int_ip || !ext_port || !int_port)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
eport = (unsigned short)atoi(ext_port);
iport = (unsigned short)atoi(int_port);
if(iport == 0 || !is_numeric(ext_port)) {
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET, int_ip, &result_ip) <= 0)
{
hp = gethostbyname(int_ip);
if(hp && hp->h_addrtype == AF_INET)
{
for(ptr = hp->h_addr_list; ptr && *ptr; ptr++)
{
int_ip = inet_ntoa(*((struct in_addr *) *ptr));
result_ip = *((struct in_addr *) *ptr);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
}
/* check if NewInternalAddress is the client address */
if(GETFLAG(SECUREMODEMASK))
{
if(h->clientaddr.s_addr != result_ip.s_addr)
{
syslog(LOG_INFO, "Client %s tried to redirect port to %s",
inet_ntoa(h->clientaddr), int_ip);
ClearNameValueList(&data);
SoapError(h, 606, "Action not authorized");
return;
}
}
/* TODO : accept a different external port
* have some smart strategy to choose the port */
for(;;) {
r = upnp_redirect(r_host, eport, int_ip, iport, protocol, desc, leaseduration);
if(r==-2 && eport < 65535) {
eport++;
} else {
break;
}
}
ClearNameValueList(&data);
switch(r)
{
case 0: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
eport, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -2: /* already redirected */
SoapError(h, 718, "ConflictInMappingEntry");
break;
case -3: /* not permitted */
SoapError(h, 606, "Action not authorized");
break;
default:
SoapError(h, 501, "ActionFailed");
}
}
static void
GetSpecificPortMappingEntry(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewInternalPort>%u</NewInternalPort>"
"<NewInternalClient>%s</NewInternalClient>"
"<NewEnabled>1</NewEnabled>"
"<NewPortMappingDescription>%s</NewPortMappingDescription>"
"<NewLeaseDuration>%u</NewLeaseDuration>"
"</u:%sResponse>";
char body[1024];
int bodylen;
struct NameValueParserData data;
const char * r_host, * ext_port, * protocol;
unsigned short eport, iport;
char int_ip[32];
char desc[64];
unsigned int leaseduration = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
#ifdef UPNP_STRICT
if(!ext_port || !protocol || !r_host)
#else
if(!ext_port || !protocol)
#endif
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
eport = (unsigned short)atoi(ext_port);
if(eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
/* TODO : add r_host as an input parameter ...
* We prevent several Port Mapping with same external port
* but different remoteHost to be set up, so that is not
* a priority. */
r = upnp_get_redirection_infos(eport, protocol, &iport,
int_ip, sizeof(int_ip),
desc, sizeof(desc),
NULL, 0,
&leaseduration);
if(r < 0)
{
SoapError(h, 714, "NoSuchEntryInArray");
}
else
{
syslog(LOG_INFO, "%s: rhost='%s' %s %s found => %s:%u desc='%s'",
action,
r_host ? r_host : "NULL", ext_port, protocol, int_ip,
(unsigned int)iport, desc);
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*SERVICE_TYPE_WANIPC*/,
(unsigned int)iport, int_ip, desc, leaseduration,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
static void
DeletePortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
/*static const char resp[] =
"<u:DeletePortMappingResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"</u:DeletePortMappingResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * ext_port, * protocol;
unsigned short eport;
#ifdef UPNP_STRICT
const char * r_host;
#endif /* UPNP_STRICT */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
#ifdef UPNP_STRICT
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
#endif /* UPNP_STRICT */
#ifdef UPNP_STRICT
if(!ext_port || !protocol || !r_host)
#else
if(!ext_port || !protocol)
#endif /* UPNP_STRICT */
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif /* UPNP_STRICT */
#endif /* SUPPORT_REMOTEHOST */
eport = (unsigned short)atoi(ext_port);
if(eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
syslog(LOG_INFO, "%s: external port: %hu, protocol: %s",
action, eport, protocol);
/* if in secure mode, check the IP
* Removing a redirection is not a security threat,
* just an annoyance for the user using it. So this is not
* a priority. */
if(GETFLAG(SECUREMODEMASK))
{
char int_ip[32];
struct in_addr int_ip_addr;
unsigned short iport;
unsigned int leaseduration = 0;
r = upnp_get_redirection_infos(eport, protocol, &iport,
int_ip, sizeof(int_ip),
NULL, 0, NULL, 0,
&leaseduration);
if(r >= 0)
{
if(inet_pton(AF_INET, int_ip, &int_ip_addr) > 0)
{
if(h->clientaddr.s_addr != int_ip_addr.s_addr)
{
SoapError(h, 606, "Action not authorized");
/*SoapError(h, 714, "NoSuchEntryInArray");*/
ClearNameValueList(&data);
return;
}
}
}
}
r = upnp_delete_redirection(eport, protocol);
if(r < 0)
{
SoapError(h, 714, "NoSuchEntryInArray");
}
else
{
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
/* DeletePortMappingRange was added in IGD spec v2 */
static void
DeletePortMappingRange(struct upnphttp * h, const char * action, const char * ns)
{
int r = -1;
/*static const char resp[] =
"<u:DeletePortMappingRangeResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"</u:DeletePortMappingRangeResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * protocol;
const char * startport_s, * endport_s;
unsigned short startport, endport;
/*int manage;*/
unsigned short * port_list;
unsigned int i, number = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
startport_s = GetValueFromNameValueList(&data, "NewStartPort");
endport_s = GetValueFromNameValueList(&data, "NewEndPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
/*manage = atoi(GetValueFromNameValueList(&data, "NewManage"));*/
if(startport_s == NULL || endport_s == NULL || protocol == NULL ||
!is_numeric(startport_s) || !is_numeric(endport_s)) {
SoapError(h, 402, "Invalid Args");
ClearNameValueList(&data);
return;
}
startport = (unsigned short)atoi(startport_s);
endport = (unsigned short)atoi(endport_s);
/* possible errors :
606 - Action not authorized
730 - PortMappingNotFound
733 - InconsistentParameter
*/
if(startport > endport)
{
SoapError(h, 733, "InconsistentParameter");
ClearNameValueList(&data);
return;
}
syslog(LOG_INFO, "%s: deleting external ports: %hu-%hu, protocol: %s",
action, startport, endport, protocol);
port_list = upnp_get_portmappings_in_range(startport, endport,
protocol, &number);
if(number == 0)
{
SoapError(h, 730, "PortMappingNotFound");
ClearNameValueList(&data);
free(port_list);
return;
}
for(i = 0; i < number; i++)
{
r = upnp_delete_redirection(port_list[i], protocol);
syslog(LOG_INFO, "%s: deleting external port: %hu, protocol: %s: %s",
action, port_list[i], protocol, r < 0 ? "failed" : "ok");
}
free(port_list);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
ClearNameValueList(&data);
}
static void
GetGenericPortMappingEntry(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewRemoteHost>%s</NewRemoteHost>"
"<NewExternalPort>%u</NewExternalPort>"
"<NewProtocol>%s</NewProtocol>"
"<NewInternalPort>%u</NewInternalPort>"
"<NewInternalClient>%s</NewInternalClient>"
"<NewEnabled>1</NewEnabled>"
"<NewPortMappingDescription>%s</NewPortMappingDescription>"
"<NewLeaseDuration>%u</NewLeaseDuration>"
"</u:%sResponse>";
long int index = 0;
unsigned short eport, iport;
const char * m_index;
char * endptr;
char protocol[8], iaddr[32];
char desc[64];
char rhost[40];
unsigned int leaseduration = 0;
struct NameValueParserData data;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
m_index = GetValueFromNameValueList(&data, "NewPortMappingIndex");
if(!m_index)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
errno = 0; /* To distinguish success/failure after call */
index = strtol(m_index, &endptr, 10);
if((errno == ERANGE && (index == LONG_MAX || index == LONG_MIN))
|| (errno != 0 && index == 0) || (m_index == endptr))
{
/* should condition (*endptr != '\0') be also an error ? */
if(m_index == endptr)
syslog(LOG_WARNING, "%s: no digits were found in <%s>",
"GetGenericPortMappingEntry", "NewPortMappingIndex");
else
syslog(LOG_WARNING, "%s: strtol('%s'): %m",
"GetGenericPortMappingEntry", m_index);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
syslog(LOG_INFO, "%s: index=%d", action, (int)index);
rhost[0] = '\0';
r = upnp_get_redirection_infos_by_index((int)index, &eport, protocol, &iport,
iaddr, sizeof(iaddr),
desc, sizeof(desc),
rhost, sizeof(rhost),
&leaseduration);
if(r < 0)
{
SoapError(h, 713, "SpecifiedArrayIndexInvalid");
}
else
{
int bodylen;
char body[2048];
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/ rhost,
(unsigned int)eport, protocol, (unsigned int)iport, iaddr, desc,
leaseduration, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
/* GetListOfPortMappings was added in the IGD v2 specification */
static void
GetListOfPortMappings(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp_start[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewPortListing><![CDATA[";
static const char resp_end[] =
"]]></NewPortListing>"
"</u:%sResponse>";
static const char list_start[] =
"<p:PortMappingList xmlns:p=\"urn:schemas-upnp-org:gw:WANIPConnection\""
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
" xsi:schemaLocation=\"urn:schemas-upnp-org:gw:WANIPConnection"
" http://www.upnp.org/schemas/gw/WANIPConnection-v2.xsd\">";
static const char list_end[] =
"</p:PortMappingList>";
static const char entry[] =
"<p:PortMappingEntry>"
"<p:NewRemoteHost>%s</p:NewRemoteHost>"
"<p:NewExternalPort>%hu</p:NewExternalPort>"
"<p:NewProtocol>%s</p:NewProtocol>"
"<p:NewInternalPort>%hu</p:NewInternalPort>"
"<p:NewInternalClient>%s</p:NewInternalClient>"
"<p:NewEnabled>1</p:NewEnabled>"
"<p:NewDescription>%s</p:NewDescription>"
"<p:NewLeaseTime>%u</p:NewLeaseTime>"
"</p:PortMappingEntry>";
char * body;
size_t bodyalloc;
int bodylen;
int r = -1;
unsigned short iport;
char int_ip[32];
char desc[64];
char rhost[64];
unsigned int leaseduration = 0;
struct NameValueParserData data;
const char * startport_s, * endport_s;
unsigned short startport, endport;
const char * protocol;
/*int manage;*/
const char * number_s;
int number;
unsigned short * port_list;
unsigned int i, list_size = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
startport_s = GetValueFromNameValueList(&data, "NewStartPort");
endport_s = GetValueFromNameValueList(&data, "NewEndPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
/*manage_s = GetValueFromNameValueList(&data, "NewManage");*/
number_s = GetValueFromNameValueList(&data, "NewNumberOfPorts");
if(startport_s == NULL || endport_s == NULL || protocol == NULL ||
number_s == NULL || !is_numeric(number_s) ||
!is_numeric(startport_s) || !is_numeric(endport_s)) {
SoapError(h, 402, "Invalid Args");
ClearNameValueList(&data);
return;
}
startport = (unsigned short)atoi(startport_s);
endport = (unsigned short)atoi(endport_s);
/*manage = atoi(manage_s);*/
number = atoi(number_s);
if(number == 0) number = 1000; /* return up to 1000 mappings by default */
if(startport > endport)
{
SoapError(h, 733, "InconsistentParameter");
ClearNameValueList(&data);
return;
}
/*
build the PortMappingList xml document :
<p:PortMappingList xmlns:p="urn:schemas-upnp-org:gw:WANIPConnection"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:schemas-upnp-org:gw:WANIPConnection
http://www.upnp.org/schemas/gw/WANIPConnection-v2.xsd">
<p:PortMappingEntry>
<p:NewRemoteHost>202.233.2.1</p:NewRemoteHost>
<p:NewExternalPort>2345</p:NewExternalPort>
<p:NewProtocol>TCP</p:NewProtocol>
<p:NewInternalPort>2345</p:NewInternalPort>
<p:NewInternalClient>192.168.1.137</p:NewInternalClient>
<p:NewEnabled>1</p:NewEnabled>
<p:NewDescription>dooom</p:NewDescription>
<p:NewLeaseTime>345</p:NewLeaseTime>
</p:PortMappingEntry>
</p:PortMappingList>
*/
bodyalloc = 4096;
body = malloc(bodyalloc);
if(!body)
{
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
return;
}
bodylen = snprintf(body, bodyalloc, resp_start,
action, ns/*SERVICE_TYPE_WANIPC*/);
if(bodylen < 0)
{
SoapError(h, 501, "ActionFailed");
free(body);
return;
}
memcpy(body+bodylen, list_start, sizeof(list_start));
bodylen += (sizeof(list_start) - 1);
port_list = upnp_get_portmappings_in_range(startport, endport,
protocol, &list_size);
/* loop through port mappings */
for(i = 0; number > 0 && i < list_size; i++)
{
/* have a margin of 1024 bytes to store the new entry */
if((unsigned int)bodylen + 1024 > bodyalloc)
{
char * body_sav = body;
bodyalloc += 4096;
body = realloc(body, bodyalloc);
if(!body)
{
syslog(LOG_CRIT, "realloc(%p, %u) FAILED", body_sav, (unsigned)bodyalloc);
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
free(body_sav);
free(port_list);
return;
}
}
rhost[0] = '\0';
r = upnp_get_redirection_infos(port_list[i], protocol, &iport,
int_ip, sizeof(int_ip),
desc, sizeof(desc),
rhost, sizeof(rhost),
&leaseduration);
if(r == 0)
{
bodylen += snprintf(body+bodylen, bodyalloc-bodylen, entry,
rhost, port_list[i], protocol,
iport, int_ip, desc, leaseduration);
number--;
}
}
free(port_list);
port_list = NULL;
if((bodylen + sizeof(list_end) + 1024) > bodyalloc)
{
char * body_sav = body;
bodyalloc += (sizeof(list_end) + 1024);
body = realloc(body, bodyalloc);
if(!body)
{
syslog(LOG_CRIT, "realloc(%p, %u) FAILED", body_sav, (unsigned)bodyalloc);
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
free(body_sav);
return;
}
}
memcpy(body+bodylen, list_end, sizeof(list_end));
bodylen += (sizeof(list_end) - 1);
bodylen += snprintf(body+bodylen, bodyalloc-bodylen, resp_end,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
free(body);
ClearNameValueList(&data);
}
#ifdef ENABLE_L3F_SERVICE
static void
SetDefaultConnectionService(struct upnphttp * h, const char * action, const char * ns)
{
/*static const char resp[] =
"<u:SetDefaultConnectionServiceResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:Layer3Forwarding:1\">"
"</u:SetDefaultConnectionServiceResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * p;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
p = GetValueFromNameValueList(&data, "NewDefaultConnectionService");
if(p) {
/* 720 InvalidDeviceUUID
* 721 InvalidServiceID
* 723 InvalidConnServiceSelection */
#ifdef UPNP_STRICT
char * service;
service = strchr(p, ',');
if(0 != memcmp(uuidvalue_wcd, p, sizeof("uuid:00000000-0000-0000-0000-000000000000") - 1)) {
SoapError(h, 720, "InvalidDeviceUUID");
} else if(service == NULL || 0 != strcmp(service+1, SERVICE_ID_WANIPC)) {
SoapError(h, 721, "InvalidServiceID");
} else
#endif
{
syslog(LOG_INFO, "%s(%s) : Ignored", action, p);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
} else {
/* missing argument */
SoapError(h, 402, "Invalid Args");
}
ClearNameValueList(&data);
}
static void
GetDefaultConnectionService(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
#ifdef IGD_V2
"<NewDefaultConnectionService>%s:WANConnectionDevice:2,"
#else
"<NewDefaultConnectionService>%s:WANConnectionDevice:1,"
#endif
SERVICE_ID_WANIPC "</NewDefaultConnectionService>"
"</u:%sResponse>";
/* example from UPnP_IGD_Layer3Forwarding 1.0.pdf :
* uuid:44f5824f-c57d-418c-a131-f22b34e14111:WANConnectionDevice:1,
* urn:upnp-org:serviceId:WANPPPConn1 */
char body[1024];
int bodylen;
/* namespace : urn:schemas-upnp-org:service:Layer3Forwarding:1 */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, uuidvalue_wcd, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
/* Added for compliance with WANIPConnection v2 */
static void
SetConnectionType(struct upnphttp * h, const char * action, const char * ns)
{
#ifdef UPNP_STRICT
const char * connection_type;
#endif /* UPNP_STRICT */
struct NameValueParserData data;
UNUSED(action);
UNUSED(ns);
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
#ifdef UPNP_STRICT
connection_type = GetValueFromNameValueList(&data, "NewConnectionType");
if(!connection_type) {
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#endif /* UPNP_STRICT */
/* Unconfigured, IP_Routed, IP_Bridged */
ClearNameValueList(&data);
/* always return a ReadOnly error */
SoapError(h, 731, "ReadOnly");
}
/* Added for compliance with WANIPConnection v2 */
static void
RequestConnection(struct upnphttp * h, const char * action, const char * ns)
{
UNUSED(action);
UNUSED(ns);
SoapError(h, 606, "Action not authorized");
}
/* Added for compliance with WANIPConnection v2 */
static void
ForceTermination(struct upnphttp * h, const char * action, const char * ns)
{
UNUSED(action);
UNUSED(ns);
SoapError(h, 606, "Action not authorized");
}
/*
If a control point calls QueryStateVariable on a state variable that is not
buffered in memory within (or otherwise available from) the service,
the service must return a SOAP fault with an errorCode of 404 Invalid Var.
QueryStateVariable remains useful as a limited test tool but may not be
part of some future versions of UPnP.
*/
static void
QueryStateVariable(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<return>%s</return>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * var_name;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
/*var_name = GetValueFromNameValueList(&data, "QueryStateVariable"); */
/*var_name = GetValueFromNameValueListIgnoreNS(&data, "varName");*/
var_name = GetValueFromNameValueList(&data, "varName");
/*syslog(LOG_INFO, "QueryStateVariable(%.40s)", var_name); */
if(!var_name)
{
SoapError(h, 402, "Invalid Args");
}
else if(strcmp(var_name, "ConnectionStatus") == 0)
{
const char * status;
status = get_wan_connection_status_str(ext_if_name);
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:control-1-0",*/
status, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#if 0
/* not useful */
else if(strcmp(var_name, "ConnectionType") == 0)
{
bodylen = snprintf(body, sizeof(body), resp, "IP_Routed");
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else if(strcmp(var_name, "LastConnectionError") == 0)
{
bodylen = snprintf(body, sizeof(body), resp, "ERROR_NONE");
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
else if(strcmp(var_name, "PortMappingNumberOfEntries") == 0)
{
char strn[10];
snprintf(strn, sizeof(strn), "%i",
upnp_get_portmapping_number_of_entries());
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:control-1-0",*/
strn, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else
{
syslog(LOG_NOTICE, "%s: Unknown: %s", action, var_name?var_name:"");
SoapError(h, 404, "Invalid Var");
}
ClearNameValueList(&data);
}
#ifdef ENABLE_6FC_SERVICE
#ifndef ENABLE_IPV6
#error "ENABLE_6FC_SERVICE needs ENABLE_IPV6"
#endif
/* WANIPv6FirewallControl actions */
static void
GetFirewallStatus(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<FirewallEnabled>%d</FirewallEnabled>"
"<InboundPinholeAllowed>%d</InboundPinholeAllowed>"
"</u:%sResponse>";
char body[512];
int bodylen;
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1",*/
GETFLAG(IPV6FCFWDISABLEDMASK) ? 0 : 1,
GETFLAG(IPV6FCINBOUNDDISALLOWEDMASK) ? 0 : 1,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static int
CheckStatus(struct upnphttp * h)
{
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return 0;
}
else if(GETFLAG(IPV6FCINBOUNDDISALLOWEDMASK))
{
SoapError(h, 703, "InboundPinholeNotAllowed");
return 0;
}
else
return 1;
}
#if 0
static int connecthostport(const char * host, unsigned short port, char * result)
{
int s, n;
char hostname[INET6_ADDRSTRLEN];
char port_str[8], ifname[8], tmp[4];
struct addrinfo *ai, *p;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
/* hints.ai_flags = AI_ADDRCONFIG; */
#ifdef AI_NUMERICSERV
hints.ai_flags = AI_NUMERICSERV;
#endif
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC; /* AF_INET, AF_INET6 or AF_UNSPEC */
/* hints.ai_protocol = IPPROTO_TCP; */
snprintf(port_str, sizeof(port_str), "%hu", port);
strcpy(hostname, host);
if(!strncmp(host, "fe80", 4))
{
printf("Using an linklocal address\n");
strcpy(ifname, "%");
snprintf(tmp, sizeof(tmp), "%d", linklocal_index);
strcat(ifname, tmp);
strcat(hostname, ifname);
printf("host: %s\n", hostname);
}
n = getaddrinfo(hostname, port_str, &hints, &ai);
if(n != 0)
{
fprintf(stderr, "getaddrinfo() error : %s\n", gai_strerror(n));
return -1;
}
s = -1;
for(p = ai; p; p = p->ai_next)
{
#ifdef DEBUG
char tmp_host[256];
char tmp_service[256];
printf("ai_family=%d ai_socktype=%d ai_protocol=%d ai_addrlen=%d\n ",
p->ai_family, p->ai_socktype, p->ai_protocol, p->ai_addrlen);
getnameinfo(p->ai_addr, p->ai_addrlen, tmp_host, sizeof(tmp_host),
tmp_service, sizeof(tmp_service),
NI_NUMERICHOST | NI_NUMERICSERV);
printf(" host=%s service=%s\n", tmp_host, tmp_service);
#endif
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr), result, INET6_ADDRSTRLEN);
return 0;
}
freeaddrinfo(ai);
}
#endif
/* Check the security policy right */
static int
PinholeVerification(struct upnphttp * h, char * int_ip, unsigned short int_port)
{
int n;
char senderAddr[INET6_ADDRSTRLEN]="";
struct addrinfo hints, *ai, *p;
struct in6_addr result_ip;
/* Pinhole InternalClient address must correspond to the action sender */
syslog(LOG_INFO, "Checking internal IP@ and port (Security policy purpose)");
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET6, int_ip, &result_ip) <= 0)
{
n = getaddrinfo(int_ip, NULL, &hints, &ai);
if(!n && ai->ai_family == AF_INET6)
{
for(p = ai; p; p = p->ai_next)
{
inet_ntop(AF_INET6, (struct in6_addr *) p, int_ip, sizeof(struct in6_addr));
result_ip = *((struct in6_addr *) p);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
SoapError(h, 402, "Invalid Args");
return -1;
}
freeaddrinfo(p);
}
if(inet_ntop(AF_INET6, &(h->clientaddr_v6), senderAddr, INET6_ADDRSTRLEN) == NULL)
{
syslog(LOG_ERR, "inet_ntop: %m");
}
#ifdef DEBUG
printf("\tPinholeVerification:\n\t\tCompare sender @: %s\n\t\t to intClient @: %s\n", senderAddr, int_ip);
#endif
if(strcmp(senderAddr, int_ip) != 0)
if(h->clientaddr_v6.s6_addr != result_ip.s6_addr)
{
syslog(LOG_INFO, "Client %s tried to access pinhole for internal %s and is not authorized to do it",
senderAddr, int_ip);
SoapError(h, 606, "Action not authorized");
return 0;
}
/* Pinhole InternalPort must be greater than or equal to 1024 */
if (int_port < 1024)
{
syslog(LOG_INFO, "Client %s tried to access pinhole with port < 1024 and is not authorized to do it",
senderAddr);
SoapError(h, 606, "Action not authorized");
return 0;
}
return 1;
}
static void
AddPinhole(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<UniqueID>%d</UniqueID>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * rem_host, * rem_port, * int_ip, * int_port, * protocol, * leaseTime;
int uid = 0;
unsigned short iport, rport;
int ltime;
long proto;
char rem_ip[INET6_ADDRSTRLEN];
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
protocol = GetValueFromNameValueList(&data, "Protocol");
leaseTime = GetValueFromNameValueList(&data, "LeaseTime");
rport = (unsigned short)(rem_port ? atoi(rem_port) : 0);
iport = (unsigned short)(int_port ? atoi(int_port) : 0);
ltime = leaseTime ? atoi(leaseTime) : -1;
errno = 0;
proto = protocol ? strtol(protocol, NULL, 0) : -1;
if(errno != 0 || proto > 65535 || proto < 0)
{
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
}
if(iport == 0)
{
SoapError(h, 706, "InternalPortWilcardingNotAllowed");
goto clear_and_exit;
}
/* In particular, [IGD2] RECOMMENDS that unauthenticated and
* unauthorized control points are only allowed to invoke
* this action with:
* - InternalPort value greater than or equal to 1024,
* - InternalClient value equals to the control point's IP address.
* It is REQUIRED that InternalClient cannot be one of IPv6
* addresses used by the gateway. */
if(!int_ip || int_ip[0] == '\0' || 0 == strcmp(int_ip, "*"))
{
SoapError(h, 708, "WildCardNotPermittedInSrcIP");
goto clear_and_exit;
}
/* I guess it is useless to convert int_ip to literal ipv6 address */
if(rem_host)
{
/* trim */
while(isspace(rem_host[0]))
rem_host++;
}
/* rem_host should be converted to literal ipv6 : */
if(rem_host && (rem_host[0] != '\0') && (rem_host[0] != '*'))
{
struct addrinfo *ai, *p;
struct addrinfo hints;
int err;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET6;
/*hints.ai_flags = */
/* hints.ai_protocol = proto; */
err = getaddrinfo(rem_host, rem_port, &hints, &ai);
if(err == 0)
{
/* take the 1st IPv6 address */
for(p = ai; p; p = p->ai_next)
{
if(p->ai_family == AF_INET6)
{
inet_ntop(AF_INET6,
&(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr),
rem_ip, sizeof(rem_ip));
syslog(LOG_INFO, "resolved '%s' to '%s'", rem_host, rem_ip);
rem_host = rem_ip;
break;
}
}
freeaddrinfo(ai);
}
else
{
syslog(LOG_WARNING, "AddPinhole : getaddrinfo(%s) : %s",
rem_host, gai_strerror(err));
#if 0
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
#endif
}
}
if(proto == 65535)
{
SoapError(h, 707, "ProtocolWilcardingNotAllowed");
goto clear_and_exit;
}
if(proto != IPPROTO_UDP && proto != IPPROTO_TCP
#ifdef IPPROTO_UDPITE
&& atoi(protocol) != IPPROTO_UDPLITE
#endif
)
{
SoapError(h, 705, "ProtocolNotSupported");
goto clear_and_exit;
}
if(ltime < 1 || ltime > 86400)
{
syslog(LOG_WARNING, "%s: LeaseTime=%d not supported, (ip=%s)",
action, ltime, int_ip);
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
}
if(PinholeVerification(h, int_ip, iport) <= 0)
goto clear_and_exit;
syslog(LOG_INFO, "%s: (inbound) from [%s]:%hu to [%s]:%hu with proto %ld during %d sec",
action, rem_host?rem_host:"any",
rport, int_ip, iport,
proto, ltime);
/* In cases where the RemoteHost, RemotePort, InternalPort,
* InternalClient and Protocol are the same than an existing pinhole,
* but LeaseTime is different, the device MUST extend the existing
* pinhole's lease time and return the UniqueID of the existing pinhole. */
r = upnp_add_inboundpinhole(rem_host, rport, int_ip, iport, proto, "IGD2 pinhole", ltime, &uid);
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body),
resp, action,
ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
uid, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -1: /* not permitted */
SoapError(h, 701, "PinholeSpaceExhausted");
break;
default:
SoapError(h, 501, "ActionFailed");
break;
}
/* 606 Action not authorized
* 701 PinholeSpaceExhausted
* 702 FirewallDisabled
* 703 InboundPinholeNotAllowed
* 705 ProtocolNotSupported
* 706 InternalPortWildcardingNotAllowed
* 707 ProtocolWildcardingNotAllowed
* 708 WildCardNotPermittedInSrcIP */
clear_and_exit:
ClearNameValueList(&data);
}
static void
UpdatePinhole(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:UpdatePinholeResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\">"
"</u:UpdatePinholeResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str, * leaseTime;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
int ltime;
int uid;
int n;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
leaseTime = GetValueFromNameValueList(&data, "NewLeaseTime");
uid = uid_str ? atoi(uid_str) : -1;
ltime = leaseTime ? atoi(leaseTime) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535 || ltime <= 0 || ltime > 86400)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not updating an pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
NULL, /* proto */
NULL, 0, /* desc, desclen */
NULL, NULL);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return;
}
else if(n == -2)
{
SoapError(h, 704, "NoSuchEntry");
return;
}
else
{
SoapError(h, 501, "ActionFailed");
return;
}
syslog(LOG_INFO, "%s: (inbound) updating lease duration to %d for pinhole with ID: %d",
action, ltime, uid);
n = upnp_update_inboundpinhole(uid, ltime);
if(n == -1)
SoapError(h, 704, "NoSuchEntry");
else if(n < 0)
SoapError(h, 501, "ActionFailed");
else {
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
}
static void
GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
static void
DeletePinhole(struct upnphttp * h, const char * action, const char * ns)
{
int n;
#if 0
static const char resp[] =
"<u:DeletePinholeResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\">"
"</u:DeletePinholeResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str;
char iaddr[INET6_ADDRSTRLEN];
int proto;
unsigned short iport;
unsigned int leasetime;
int uid;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not deleting an pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
&proto,
NULL, 0, /* desc, desclen */
&leasetime, NULL);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return;
}
else if(n == -2)
{
SoapError(h, 704, "NoSuchEntry");
return;
}
else
{
SoapError(h, 501, "ActionFailed");
return;
}
n = upnp_delete_inboundpinhole(uid);
if(n < 0)
{
syslog(LOG_INFO, "%s: (inbound) failed to remove pinhole with ID: %d",
action, uid);
SoapError(h, 501, "ActionFailed");
return;
}
syslog(LOG_INFO, "%s: (inbound) pinhole with ID %d successfully removed",
action, uid);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
CheckPinholeWorking(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<IsWorking>%d</IsWorking>"
"</u:%sResponse>";
char body[512];
int bodylen;
int r;
struct NameValueParserData data;
const char * uid_str;
int uid;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
unsigned int packets;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not checking a pinhole
* it doesn't have access to, because of its public access */
r = upnp_get_pinhole_info(uid,
NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
NULL, /* proto */
NULL, 0, /* desc, desclen */
NULL, &packets);
if (r >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return ;
if(packets == 0)
{
SoapError(h, 709, "NoPacketSent");
return;
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
1, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else if(r == -2)
SoapError(h, 704, "NoSuchEntry");
else
SoapError(h, 501, "ActionFailed");
}
static void
GetPinholePackets(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<PinholePackets>%u</PinholePackets>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str;
int n;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
unsigned int packets = 0;
int uid;
int proto;
unsigned int leasetime;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not getting infos of a pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
&proto,
NULL, 0, /* desc, desclen */
&leasetime, &packets);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport)<=0)
return ;
}
#if 0
else if(r == -4 || r == -1)
{
SoapError(h, 704, "NoSuchEntry");
}
#endif
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
packets, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
#ifdef ENABLE_DP_SERVICE
static void
SendSetupMessage(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutMessage>%s</OutMessage>"
"</u:%sResponse>";
char body[1024];
int bodylen;
struct NameValueParserData data;
const char * ProtocolType; /* string */
const char * InMessage; /* base64 */
const char * OutMessage = ""; /* base64 */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
ProtocolType = GetValueFromNameValueList(&data, "ProtocolType"); /* string */
InMessage = GetValueFromNameValueList(&data, "InMessage"); /* base64 */
if(ProtocolType == NULL || InMessage == NULL)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
/*if(strcmp(ProtocolType, "DeviceProtection:1") != 0)*/
if(strcmp(ProtocolType, "WPS") != 0)
{
ClearNameValueList(&data);
SoapError(h, 600, "Argument Value Invalid"); /* 703 ? */
return;
}
/* TODO : put here code for WPS */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
OutMessage, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
ClearNameValueList(&data);
}
static void
GetSupportedProtocols(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<ProtocolList><![CDATA[%s]]></ProtocolList>"
"</u:%sResponse>";
char body[1024];
int bodylen;
const char * ProtocolList =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<SupportedProtocols xmlns=\"urn:schemas-upnp-org:gw:DeviceProtection\""
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
" xsi:schemaLocation=\"urn:schemas-upnp-org:gw:DeviceProtection"
" http://www.upnp.org/schemas/gw/DeviceProtection-v1.xsd\">"
"<Introduction><Name>WPS</Name></Introduction>"
"<Login><Name>PKCS5</Name></Login>"
"</SupportedProtocols>";
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
ProtocolList, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetAssignedRoles(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<RoleList>%s</RoleList>"
"</u:%sResponse>";
char body[1024];
int bodylen;
const char * RoleList = "Public"; /* list of roles separated by spaces */
#ifdef ENABLE_HTTPS
if(h->ssl != NULL) {
/* we should get the Roles of the session (based on client certificate) */
X509 * peercert;
peercert = SSL_get_peer_certificate(h->ssl);
if(peercert != NULL) {
RoleList = "Admin Basic";
X509_free(peercert);
}
}
#endif
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
RoleList, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
/* Windows XP as client send the following requests :
* GetConnectionTypeInfo
* GetNATRSIPStatus
* ? GetTotalBytesSent - WANCommonInterfaceConfig
* ? GetTotalBytesReceived - idem
* ? GetTotalPacketsSent - idem
* ? GetTotalPacketsReceived - idem
* GetCommonLinkProperties - idem
* GetStatusInfo - WANIPConnection
* GetExternalIPAddress
* QueryStateVariable / ConnectionStatus!
*/
static const struct
{
const char * methodName;
void (*methodImpl)(struct upnphttp *, const char *, const char *);
}
soapMethods[] =
{
/* WANCommonInterfaceConfig */
{ "QueryStateVariable", QueryStateVariable},
{ "GetTotalBytesSent", GetTotalBytesSent},
{ "GetTotalBytesReceived", GetTotalBytesReceived},
{ "GetTotalPacketsSent", GetTotalPacketsSent},
{ "GetTotalPacketsReceived", GetTotalPacketsReceived},
{ "GetCommonLinkProperties", GetCommonLinkProperties},
{ "GetStatusInfo", GetStatusInfo},
/* WANIPConnection */
{ "GetConnectionTypeInfo", GetConnectionTypeInfo },
{ "GetNATRSIPStatus", GetNATRSIPStatus},
{ "GetExternalIPAddress", GetExternalIPAddress},
{ "AddPortMapping", AddPortMapping},
{ "DeletePortMapping", DeletePortMapping},
{ "GetGenericPortMappingEntry", GetGenericPortMappingEntry},
{ "GetSpecificPortMappingEntry", GetSpecificPortMappingEntry},
/* Required in WANIPConnection:2 */
{ "SetConnectionType", SetConnectionType},
{ "RequestConnection", RequestConnection},
{ "ForceTermination", ForceTermination},
{ "AddAnyPortMapping", AddAnyPortMapping},
{ "DeletePortMappingRange", DeletePortMappingRange},
{ "GetListOfPortMappings", GetListOfPortMappings},
#ifdef ENABLE_L3F_SERVICE
/* Layer3Forwarding */
{ "SetDefaultConnectionService", SetDefaultConnectionService},
{ "GetDefaultConnectionService", GetDefaultConnectionService},
#endif
#ifdef ENABLE_6FC_SERVICE
/* WANIPv6FirewallControl */
{ "GetFirewallStatus", GetFirewallStatus}, /* Required */
{ "AddPinhole", AddPinhole}, /* Required */
{ "UpdatePinhole", UpdatePinhole}, /* Required */
{ "GetOutboundPinholeTimeout", GetOutboundPinholeTimeout}, /* Optional */
{ "DeletePinhole", DeletePinhole}, /* Required */
{ "CheckPinholeWorking", CheckPinholeWorking}, /* Optional */
{ "GetPinholePackets", GetPinholePackets}, /* Required */
#endif
#ifdef ENABLE_DP_SERVICE
/* DeviceProtection */
{ "SendSetupMessage", SendSetupMessage}, /* Required */
{ "GetSupportedProtocols", GetSupportedProtocols}, /* Required */
{ "GetAssignedRoles", GetAssignedRoles}, /* Required */
#endif
{ 0, 0 }
};
void
ExecuteSoapAction(struct upnphttp * h, const char * action, int n)
{
char * p;
char * p2;
int i, len, methodlen;
char namespace[256];
/* SoapAction example :
* urn:schemas-upnp-org:service:WANIPConnection:1#GetStatusInfo */
p = strchr(action, '#');
if(p && (p - action) < n) {
for(i = 0; i < ((int)sizeof(namespace) - 1) && (action + i) < p; i++)
namespace[i] = action[i];
namespace[i] = '\0';
p++;
p2 = strchr(p, '"');
if(p2 && (p2 - action) <= n)
methodlen = p2 - p;
else
methodlen = n - (p - action);
/*syslog(LOG_DEBUG, "SoapMethod: %.*s %d %d %p %p %d",
methodlen, p, methodlen, n, action, p, (int)(p - action));*/
for(i = 0; soapMethods[i].methodName; i++) {
len = strlen(soapMethods[i].methodName);
if((len == methodlen) && memcmp(p, soapMethods[i].methodName, len) == 0) {
#ifdef DEBUG
syslog(LOG_DEBUG, "Remote Call of SoapMethod '%s' %s",
soapMethods[i].methodName, namespace);
#endif /* DEBUG */
soapMethods[i].methodImpl(h, soapMethods[i].methodName, namespace);
return;
}
}
syslog(LOG_NOTICE, "SoapMethod: Unknown: %.*s %s", methodlen, p, namespace);
} else {
syslog(LOG_NOTICE, "cannot parse SoapAction");
}
SoapError(h, 401, "Invalid Action");
}
/* Standard Errors:
*
* errorCode errorDescription Description
* -------- ---------------- -----------
* 401 Invalid Action No action by that name at this service.
* 402 Invalid Args Could be any of the following: not enough in args,
* too many in args, no in arg by that name,
* one or more in args are of the wrong data type.
* 403 Out of Sync Out of synchronization.
* 501 Action Failed May be returned in current state of service
* prevents invoking that action.
* 600-699 TBD Common action errors. Defined by UPnP Forum
* Technical Committee.
* 700-799 TBD Action-specific errors for standard actions.
* Defined by UPnP Forum working committee.
* 800-899 TBD Action-specific errors for non-standard actions.
* Defined by UPnP vendor.
*/
void
SoapError(struct upnphttp * h, int errCode, const char * errDesc)
{
static const char resp[] =
"<s:Envelope "
"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body>"
"<s:Fault>"
"<faultcode>s:Client</faultcode>"
"<faultstring>UPnPError</faultstring>"
"<detail>"
"<UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">"
"<errorCode>%d</errorCode>"
"<errorDescription>%s</errorDescription>"
"</UPnPError>"
"</detail>"
"</s:Fault>"
"</s:Body>"
"</s:Envelope>";
char body[2048];
int bodylen;
syslog(LOG_INFO, "Returning UPnPError %d: %s", errCode, errDesc);
bodylen = snprintf(body, sizeof(body), resp, errCode, errDesc);
BuildResp2_upnphttp(h, 500, "Internal Server Error", body, bodylen);
SendRespAndClose_upnphttp(h);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_861_0 |
crossvul-cpp_data_bad_323_0 | /************************************************************
* Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of Silicon Graphics not be
* used in advertising or publicity pertaining to distribution
* of the software without specific prior written permission.
* Silicon Graphics makes no representation about the suitability
* of this software for any purpose. It is provided "as is"
* without any express or implied warranty.
*
* SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS BE LIABLE FOR 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.
*
********************************************************/
#include "xkbcomp-priv.h"
#include "text.h"
#include "expr.h"
typedef bool (*IdentLookupFunc)(struct xkb_context *ctx, const void *priv,
xkb_atom_t field, enum expr_value_type type,
unsigned int *val_rtrn);
bool
ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return true;
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return true;
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
}
static bool
SimpleLookup(struct xkb_context *ctx, const void *priv, xkb_atom_t field,
enum expr_value_type type, unsigned int *val_rtrn)
{
const LookupEntry *entry;
const char *str;
if (!priv || field == XKB_ATOM_NONE || type != EXPR_TYPE_INT)
return false;
str = xkb_atom_text(ctx, field);
for (entry = priv; entry && entry->name; entry++) {
if (istreq(str, entry->name)) {
*val_rtrn = entry->value;
return true;
}
}
return false;
}
/* Data passed in the *priv argument for LookupModMask. */
typedef struct {
const struct xkb_mod_set *mods;
enum mod_type mod_type;
} LookupModMaskPriv;
static bool
LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field,
enum expr_value_type type, xkb_mod_mask_t *val_rtrn)
{
const char *str;
xkb_mod_index_t ndx;
const LookupModMaskPriv *arg = priv;
const struct xkb_mod_set *mods = arg->mods;
enum mod_type mod_type = arg->mod_type;
if (type != EXPR_TYPE_INT)
return false;
str = xkb_atom_text(ctx, field);
if (!str)
return false;
if (istreq(str, "all")) {
*val_rtrn = MOD_REAL_MASK_ALL;
return true;
}
if (istreq(str, "none")) {
*val_rtrn = 0;
return true;
}
ndx = XkbModNameToIndex(mods, field, mod_type);
if (ndx == XKB_MOD_INVALID)
return false;
*val_rtrn = (1u << ndx);
return true;
}
bool
ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr,
bool *set_rtrn)
{
bool ok = false;
const char *ident;
switch (expr->expr.op) {
case EXPR_VALUE:
if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) {
log_err(ctx,
"Found constant of type %s where boolean was expected\n",
expr_value_type_to_string(expr->expr.value_type));
return false;
}
*set_rtrn = expr->boolean.set;
return true;
case EXPR_IDENT:
ident = xkb_atom_text(ctx, expr->ident.ident);
if (ident) {
if (istreq(ident, "true") ||
istreq(ident, "yes") ||
istreq(ident, "on")) {
*set_rtrn = true;
return true;
}
else if (istreq(ident, "false") ||
istreq(ident, "no") ||
istreq(ident, "off")) {
*set_rtrn = false;
return true;
}
}
log_err(ctx, "Identifier \"%s\" of type boolean is unknown\n", ident);
return false;
case EXPR_FIELD_REF:
log_err(ctx, "Default \"%s.%s\" of type boolean is unknown\n",
xkb_atom_text(ctx, expr->field_ref.element),
xkb_atom_text(ctx, expr->field_ref.field));
return false;
case EXPR_INVERT:
case EXPR_NOT:
ok = ExprResolveBoolean(ctx, expr->unary.child, set_rtrn);
if (ok)
*set_rtrn = !*set_rtrn;
return ok;
case EXPR_ADD:
case EXPR_SUBTRACT:
case EXPR_MULTIPLY:
case EXPR_DIVIDE:
case EXPR_ASSIGN:
case EXPR_NEGATE:
case EXPR_UNARY_PLUS:
log_err(ctx, "%s of boolean values not permitted\n",
expr_op_type_to_string(expr->expr.op));
break;
default:
log_wsgo(ctx, "Unknown operator %d in ResolveBoolean\n",
expr->expr.op);
break;
}
return false;
}
bool
ExprResolveKeyCode(struct xkb_context *ctx, const ExprDef *expr,
xkb_keycode_t *kc)
{
xkb_keycode_t leftRtrn, rightRtrn;
switch (expr->expr.op) {
case EXPR_VALUE:
if (expr->expr.value_type != EXPR_TYPE_INT) {
log_err(ctx,
"Found constant of type %s where an int was expected\n",
expr_value_type_to_string(expr->expr.value_type));
return false;
}
*kc = (xkb_keycode_t) expr->integer.ival;
return true;
case EXPR_ADD:
case EXPR_SUBTRACT:
case EXPR_MULTIPLY:
case EXPR_DIVIDE:
if (!ExprResolveKeyCode(ctx, expr->binary.left, &leftRtrn) ||
!ExprResolveKeyCode(ctx, expr->binary.right, &rightRtrn))
return false;
switch (expr->expr.op) {
case EXPR_ADD:
*kc = leftRtrn + rightRtrn;
break;
case EXPR_SUBTRACT:
*kc = leftRtrn - rightRtrn;
break;
case EXPR_MULTIPLY:
*kc = leftRtrn * rightRtrn;
break;
case EXPR_DIVIDE:
if (rightRtrn == 0) {
log_err(ctx, "Cannot divide by zero: %d / %d\n",
leftRtrn, rightRtrn);
return false;
}
*kc = leftRtrn / rightRtrn;
break;
default:
break;
}
return true;
case EXPR_NEGATE:
if (!ExprResolveKeyCode(ctx, expr->unary.child, &leftRtrn))
return false;
*kc = ~leftRtrn;
return true;
case EXPR_UNARY_PLUS:
return ExprResolveKeyCode(ctx, expr->unary.child, kc);
default:
log_wsgo(ctx, "Unknown operator %d in ResolveKeyCode\n",
expr->expr.op);
break;
}
return false;
}
/**
* This function returns ... something. It's a bit of a guess, really.
*
* If an integer is given in value ctx, it will be returned in ival.
* If an ident or field reference is given, the lookup function (if given)
* will be called. At the moment, only SimpleLookup use this, and they both
* return the results in uval. And don't support field references.
*
* Cool.
*/
static bool
ExprResolveIntegerLookup(struct xkb_context *ctx, const ExprDef *expr,
int *val_rtrn, IdentLookupFunc lookup,
const void *lookupPriv)
{
bool ok = false;
int l, r;
unsigned u;
ExprDef *left, *right;
switch (expr->expr.op) {
case EXPR_VALUE:
if (expr->expr.value_type != EXPR_TYPE_INT) {
log_err(ctx,
"Found constant of type %s where an int was expected\n",
expr_value_type_to_string(expr->expr.value_type));
return false;
}
*val_rtrn = expr->integer.ival;
return true;
case EXPR_IDENT:
if (lookup)
ok = lookup(ctx, lookupPriv, expr->ident.ident, EXPR_TYPE_INT, &u);
if (!ok)
log_err(ctx, "Identifier \"%s\" of type int is unknown\n",
xkb_atom_text(ctx, expr->ident.ident));
else
*val_rtrn = (int) u;
return ok;
case EXPR_FIELD_REF:
log_err(ctx, "Default \"%s.%s\" of type int is unknown\n",
xkb_atom_text(ctx, expr->field_ref.element),
xkb_atom_text(ctx, expr->field_ref.field));
return false;
case EXPR_ADD:
case EXPR_SUBTRACT:
case EXPR_MULTIPLY:
case EXPR_DIVIDE:
left = expr->binary.left;
right = expr->binary.right;
if (!ExprResolveIntegerLookup(ctx, left, &l, lookup, lookupPriv) ||
!ExprResolveIntegerLookup(ctx, right, &r, lookup, lookupPriv))
return false;
switch (expr->expr.op) {
case EXPR_ADD:
*val_rtrn = l + r;
break;
case EXPR_SUBTRACT:
*val_rtrn = l - r;
break;
case EXPR_MULTIPLY:
*val_rtrn = l * r;
break;
case EXPR_DIVIDE:
if (r == 0) {
log_err(ctx, "Cannot divide by zero: %d / %d\n", l, r);
return false;
}
*val_rtrn = l / r;
break;
default:
log_err(ctx, "%s of integers not permitted\n",
expr_op_type_to_string(expr->expr.op));
return false;
}
return true;
case EXPR_ASSIGN:
log_wsgo(ctx, "Assignment operator not implemented yet\n");
break;
case EXPR_NOT:
log_err(ctx, "The ! operator cannot be applied to an integer\n");
return false;
case EXPR_INVERT:
case EXPR_NEGATE:
left = expr->unary.child;
if (!ExprResolveIntegerLookup(ctx, left, &l, lookup, lookupPriv))
return false;
*val_rtrn = (expr->expr.op == EXPR_NEGATE ? -l : ~l);
return true;
case EXPR_UNARY_PLUS:
left = expr->unary.child;
return ExprResolveIntegerLookup(ctx, left, val_rtrn, lookup,
lookupPriv);
default:
log_wsgo(ctx, "Unknown operator %d in ResolveInteger\n",
expr->expr.op);
break;
}
return false;
}
bool
ExprResolveInteger(struct xkb_context *ctx, const ExprDef *expr,
int *val_rtrn)
{
return ExprResolveIntegerLookup(ctx, expr, val_rtrn, NULL, NULL);
}
bool
ExprResolveGroup(struct xkb_context *ctx, const ExprDef *expr,
xkb_layout_index_t *group_rtrn)
{
bool ok;
int result;
ok = ExprResolveIntegerLookup(ctx, expr, &result, SimpleLookup,
groupNames);
if (!ok)
return false;
if (result <= 0 || result > XKB_MAX_GROUPS) {
log_err(ctx, "Group index %u is out of range (1..%d)\n",
result, XKB_MAX_GROUPS);
return false;
}
*group_rtrn = (xkb_layout_index_t) result;
return true;
}
bool
ExprResolveLevel(struct xkb_context *ctx, const ExprDef *expr,
xkb_level_index_t *level_rtrn)
{
bool ok;
int result;
ok = ExprResolveIntegerLookup(ctx, expr, &result, SimpleLookup,
levelNames);
if (!ok)
return false;
if (result < 1) {
log_err(ctx, "Shift level %d is out of range\n", result);
return false;
}
/* Level is zero-indexed from now on. */
*level_rtrn = (unsigned int) (result - 1);
return true;
}
bool
ExprResolveButton(struct xkb_context *ctx, const ExprDef *expr, int *btn_rtrn)
{
return ExprResolveIntegerLookup(ctx, expr, btn_rtrn, SimpleLookup,
buttonNames);
}
bool
ExprResolveString(struct xkb_context *ctx, const ExprDef *expr,
xkb_atom_t *val_rtrn)
{
switch (expr->expr.op) {
case EXPR_VALUE:
if (expr->expr.value_type != EXPR_TYPE_STRING) {
log_err(ctx, "Found constant of type %s, expected a string\n",
expr_value_type_to_string(expr->expr.value_type));
return false;
}
*val_rtrn = expr->string.str;
return true;
case EXPR_IDENT:
log_err(ctx, "Identifier \"%s\" of type string not found\n",
xkb_atom_text(ctx, expr->ident.ident));
return false;
case EXPR_FIELD_REF:
log_err(ctx, "Default \"%s.%s\" of type string not found\n",
xkb_atom_text(ctx, expr->field_ref.element),
xkb_atom_text(ctx, expr->field_ref.field));
return false;
case EXPR_ADD:
case EXPR_SUBTRACT:
case EXPR_MULTIPLY:
case EXPR_DIVIDE:
case EXPR_ASSIGN:
case EXPR_NEGATE:
case EXPR_INVERT:
case EXPR_NOT:
case EXPR_UNARY_PLUS:
log_err(ctx, "%s of strings not permitted\n",
expr_op_type_to_string(expr->expr.op));
return false;
default:
log_wsgo(ctx, "Unknown operator %d in ResolveString\n",
expr->expr.op);
break;
}
return false;
}
bool
ExprResolveEnum(struct xkb_context *ctx, const ExprDef *expr,
unsigned int *val_rtrn, const LookupEntry *values)
{
if (expr->expr.op != EXPR_IDENT) {
log_err(ctx, "Found a %s where an enumerated value was expected\n",
expr_op_type_to_string(expr->expr.op));
return false;
}
if (!SimpleLookup(ctx, values, expr->ident.ident, EXPR_TYPE_INT,
val_rtrn)) {
log_err(ctx, "Illegal identifier %s; expected one of:\n",
xkb_atom_text(ctx, expr->ident.ident));
while (values && values->name)
{
log_err(ctx, "\t%s\n", values->name);
values++;
}
return false;
}
return true;
}
static bool
ExprResolveMaskLookup(struct xkb_context *ctx, const ExprDef *expr,
unsigned int *val_rtrn, IdentLookupFunc lookup,
const void *lookupPriv)
{
bool ok = false;
unsigned int l = 0, r = 0;
int v;
ExprDef *left, *right;
const char *bogus = NULL;
switch (expr->expr.op) {
case EXPR_VALUE:
if (expr->expr.value_type != EXPR_TYPE_INT) {
log_err(ctx,
"Found constant of type %s where a mask was expected\n",
expr_value_type_to_string(expr->expr.value_type));
return false;
}
*val_rtrn = (unsigned int) expr->integer.ival;
return true;
case EXPR_IDENT:
ok = lookup(ctx, lookupPriv, expr->ident.ident, EXPR_TYPE_INT,
val_rtrn);
if (!ok)
log_err(ctx, "Identifier \"%s\" of type int is unknown\n",
xkb_atom_text(ctx, expr->ident.ident));
return ok;
case EXPR_FIELD_REF:
log_err(ctx, "Default \"%s.%s\" of type int is unknown\n",
xkb_atom_text(ctx, expr->field_ref.element),
xkb_atom_text(ctx, expr->field_ref.field));
return false;
case EXPR_ARRAY_REF:
bogus = "array reference";
/* fallthrough */
case EXPR_ACTION_DECL:
if (bogus == NULL)
bogus = "function use";
log_err(ctx,
"Unexpected %s in mask expression; Expression Ignored\n",
bogus);
return false;
case EXPR_ADD:
case EXPR_SUBTRACT:
case EXPR_MULTIPLY:
case EXPR_DIVIDE:
left = expr->binary.left;
right = expr->binary.right;
if (!ExprResolveMaskLookup(ctx, left, &l, lookup, lookupPriv) ||
!ExprResolveMaskLookup(ctx, right, &r, lookup, lookupPriv))
return false;
switch (expr->expr.op) {
case EXPR_ADD:
*val_rtrn = l | r;
break;
case EXPR_SUBTRACT:
*val_rtrn = l & (~r);
break;
case EXPR_MULTIPLY:
case EXPR_DIVIDE:
log_err(ctx, "Cannot %s masks; Illegal operation ignored\n",
(expr->expr.op == EXPR_DIVIDE ? "divide" : "multiply"));
return false;
default:
break;
}
return true;
case EXPR_ASSIGN:
log_wsgo(ctx, "Assignment operator not implemented yet\n");
break;
case EXPR_INVERT:
left = expr->unary.child;
if (!ExprResolveIntegerLookup(ctx, left, &v, lookup, lookupPriv))
return false;
*val_rtrn = ~v;
return true;
case EXPR_UNARY_PLUS:
case EXPR_NEGATE:
case EXPR_NOT:
left = expr->unary.child;
if (!ExprResolveIntegerLookup(ctx, left, &v, lookup, lookupPriv))
log_err(ctx, "The %s operator cannot be used with a mask\n",
(expr->expr.op == EXPR_NEGATE ? "-" : "!"));
return false;
default:
log_wsgo(ctx, "Unknown operator %d in ResolveMask\n",
expr->expr.op);
break;
}
return false;
}
bool
ExprResolveMask(struct xkb_context *ctx, const ExprDef *expr,
unsigned int *mask_rtrn, const LookupEntry *values)
{
return ExprResolveMaskLookup(ctx, expr, mask_rtrn, SimpleLookup, values);
}
bool
ExprResolveModMask(struct xkb_context *ctx, const ExprDef *expr,
enum mod_type mod_type, const struct xkb_mod_set *mods,
xkb_mod_mask_t *mask_rtrn)
{
LookupModMaskPriv priv = { .mods = mods, .mod_type = mod_type };
return ExprResolveMaskLookup(ctx, expr, mask_rtrn, LookupModMask, &priv);
}
bool
ExprResolveKeySym(struct xkb_context *ctx, const ExprDef *expr,
xkb_keysym_t *sym_rtrn)
{
int val;
if (expr->expr.op == EXPR_IDENT) {
const char *str = xkb_atom_text(ctx, expr->ident.ident);
*sym_rtrn = xkb_keysym_from_name(str, 0);
if (*sym_rtrn != XKB_KEY_NoSymbol)
return true;
}
if (!ExprResolveInteger(ctx, expr, &val))
return false;
if (val < 0 || val >= 10)
return false;
*sym_rtrn = XKB_KEY_0 + (xkb_keysym_t) val;
return true;
}
bool
ExprResolveMod(struct xkb_context *ctx, const ExprDef *def,
enum mod_type mod_type, const struct xkb_mod_set *mods,
xkb_mod_index_t *ndx_rtrn)
{
xkb_mod_index_t ndx;
xkb_atom_t name;
if (def->expr.op != EXPR_IDENT) {
log_err(ctx,
"Cannot resolve virtual modifier: "
"found %s where a virtual modifier name was expected\n",
expr_op_type_to_string(def->expr.op));
return false;
}
name = def->ident.ident;
ndx = XkbModNameToIndex(mods, name, mod_type);
if (ndx == XKB_MOD_INVALID) {
log_err(ctx,
"Cannot resolve virtual modifier: "
"\"%s\" was not previously declared\n",
xkb_atom_text(ctx, name));
return false;
}
*ndx_rtrn = ndx;
return true;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_323_0 |
crossvul-cpp_data_bad_5715_0 | /**
* WinPR: Windows Portable Runtime
* Network Level Authentication (NLA)
*
* Copyright 2010-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <time.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <freerdp/crypto/tls.h>
#include <winpr/crt.h>
#include <winpr/sspi.h>
#include <winpr/print.h>
#include <winpr/tchar.h>
#include <winpr/library.h>
#include <winpr/registry.h>
#include "nla.h"
/**
* TSRequest ::= SEQUENCE {
* version [0] INTEGER,
* negoTokens [1] NegoData OPTIONAL,
* authInfo [2] OCTET STRING OPTIONAL,
* pubKeyAuth [3] OCTET STRING OPTIONAL
* }
*
* NegoData ::= SEQUENCE OF NegoDataItem
*
* NegoDataItem ::= SEQUENCE {
* negoToken [0] OCTET STRING
* }
*
* TSCredentials ::= SEQUENCE {
* credType [0] INTEGER,
* credentials [1] OCTET STRING
* }
*
* TSPasswordCreds ::= SEQUENCE {
* domainName [0] OCTET STRING,
* userName [1] OCTET STRING,
* password [2] OCTET STRING
* }
*
* TSSmartCardCreds ::= SEQUENCE {
* pin [0] OCTET STRING,
* cspData [1] TSCspDataDetail,
* userHint [2] OCTET STRING OPTIONAL,
* domainHint [3] OCTET STRING OPTIONAL
* }
*
* TSCspDataDetail ::= SEQUENCE {
* keySpec [0] INTEGER,
* cardName [1] OCTET STRING OPTIONAL,
* readerName [2] OCTET STRING OPTIONAL,
* containerName [3] OCTET STRING OPTIONAL,
* cspName [4] OCTET STRING OPTIONAL
* }
*
*/
#ifdef WITH_DEBUG_NLA
#define WITH_DEBUG_CREDSSP
#endif
#ifdef WITH_NATIVE_SSPI
#define NLA_PKG_NAME NTLMSP_NAME
#else
#define NLA_PKG_NAME NTLMSP_NAME
#endif
#define TERMSRV_SPN_PREFIX "TERMSRV/"
void credssp_send(rdpCredssp* credssp);
int credssp_recv(rdpCredssp* credssp);
void credssp_buffer_print(rdpCredssp* credssp);
void credssp_buffer_free(rdpCredssp* credssp);
SECURITY_STATUS credssp_encrypt_public_key_echo(rdpCredssp* credssp);
SECURITY_STATUS credssp_decrypt_public_key_echo(rdpCredssp* credssp);
SECURITY_STATUS credssp_encrypt_ts_credentials(rdpCredssp* credssp);
SECURITY_STATUS credssp_decrypt_ts_credentials(rdpCredssp* credssp);
#define ber_sizeof_sequence_octet_string(length) ber_sizeof_contextual_tag(ber_sizeof_octet_string(length)) + ber_sizeof_octet_string(length)
#define ber_write_sequence_octet_string(stream, context, value, length) ber_write_contextual_tag(stream, context, ber_sizeof_octet_string(length), TRUE) + ber_write_octet_string(stream, value, length)
/**
* Initialize NTLMSSP authentication module (client).
* @param credssp
*/
int credssp_ntlm_client_init(rdpCredssp* credssp)
{
char* spn;
int length;
freerdp* instance;
rdpSettings* settings;
settings = credssp->settings;
instance = (freerdp*) settings->instance;
if ((settings->Password == NULL) || (settings->Username == NULL))
{
if (instance->Authenticate)
{
BOOL proceed = instance->Authenticate(instance,
&settings->Username, &settings->Password, &settings->Domain);
if (!proceed)
return 0;
}
}
sspi_SetAuthIdentity(&(credssp->identity), settings->Username, settings->Domain, settings->Password);
#ifdef WITH_DEBUG_NLA
_tprintf(_T("User: %s Domain: %s Password: %s\n"),
(char*) credssp->identity.User, (char*) credssp->identity.Domain, (char*) credssp->identity.Password);
#endif
sspi_SecBufferAlloc(&credssp->PublicKey, credssp->transport->TlsIn->PublicKeyLength);
CopyMemory(credssp->PublicKey.pvBuffer, credssp->transport->TlsIn->PublicKey, credssp->transport->TlsIn->PublicKeyLength);
length = sizeof(TERMSRV_SPN_PREFIX) + strlen(settings->ServerHostname);
spn = (SEC_CHAR*) malloc(length + 1);
sprintf(spn, "%s%s", TERMSRV_SPN_PREFIX, settings->ServerHostname);
#ifdef UNICODE
credssp->ServicePrincipalName = (LPTSTR) malloc(length * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, spn, length,
(LPWSTR) credssp->ServicePrincipalName, length);
free(spn);
#else
credssp->ServicePrincipalName = spn;
#endif
return 1;
}
/**
* Initialize NTLMSSP authentication module (server).
* @param credssp
*/
int credssp_ntlm_server_init(rdpCredssp* credssp)
{
freerdp* instance;
rdpSettings* settings = credssp->settings;
instance = (freerdp*) settings->instance;
sspi_SecBufferAlloc(&credssp->PublicKey, credssp->transport->TlsIn->PublicKeyLength);
CopyMemory(credssp->PublicKey.pvBuffer, credssp->transport->TlsIn->PublicKey, credssp->transport->TlsIn->PublicKeyLength);
return 1;
}
int credssp_client_authenticate(rdpCredssp* credssp)
{
ULONG cbMaxToken;
ULONG fContextReq;
ULONG pfContextAttr;
SECURITY_STATUS status;
CredHandle credentials;
TimeStamp expiration;
PSecPkgInfo pPackageInfo;
SecBuffer input_buffer;
SecBuffer output_buffer;
SecBufferDesc input_buffer_desc;
SecBufferDesc output_buffer_desc;
BOOL have_context;
BOOL have_input_buffer;
BOOL have_pub_key_auth;
sspi_GlobalInit();
if (credssp_ntlm_client_init(credssp) == 0)
return 0;
#ifdef WITH_NATIVE_SSPI
{
HMODULE hSSPI;
INIT_SECURITY_INTERFACE InitSecurityInterface;
PSecurityFunctionTable pSecurityInterface = NULL;
hSSPI = LoadLibrary(_T("secur32.dll"));
#ifdef UNICODE
InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceW");
#else
InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceA");
#endif
credssp->table = (*InitSecurityInterface)();
}
#else
credssp->table = InitSecurityInterface();
#endif
status = credssp->table->QuerySecurityPackageInfo(NLA_PKG_NAME, &pPackageInfo);
if (status != SEC_E_OK)
{
fprintf(stderr, "QuerySecurityPackageInfo status: 0x%08X\n", status);
return 0;
}
cbMaxToken = pPackageInfo->cbMaxToken;
status = credssp->table->AcquireCredentialsHandle(NULL, NLA_PKG_NAME,
SECPKG_CRED_OUTBOUND, NULL, &credssp->identity, NULL, NULL, &credentials, &expiration);
if (status != SEC_E_OK)
{
fprintf(stderr, "AcquireCredentialsHandle status: 0x%08X\n", status);
return 0;
}
have_context = FALSE;
have_input_buffer = FALSE;
have_pub_key_auth = FALSE;
ZeroMemory(&input_buffer, sizeof(SecBuffer));
ZeroMemory(&output_buffer, sizeof(SecBuffer));
ZeroMemory(&credssp->ContextSizes, sizeof(SecPkgContext_Sizes));
/*
* from tspkg.dll: 0x00000132
* ISC_REQ_MUTUAL_AUTH
* ISC_REQ_CONFIDENTIALITY
* ISC_REQ_USE_SESSION_KEY
* ISC_REQ_ALLOCATE_MEMORY
*/
fContextReq = ISC_REQ_MUTUAL_AUTH | ISC_REQ_CONFIDENTIALITY | ISC_REQ_USE_SESSION_KEY;
while (TRUE)
{
output_buffer_desc.ulVersion = SECBUFFER_VERSION;
output_buffer_desc.cBuffers = 1;
output_buffer_desc.pBuffers = &output_buffer;
output_buffer.BufferType = SECBUFFER_TOKEN;
output_buffer.cbBuffer = cbMaxToken;
output_buffer.pvBuffer = malloc(output_buffer.cbBuffer);
status = credssp->table->InitializeSecurityContext(&credentials,
(have_context) ? &credssp->context : NULL,
credssp->ServicePrincipalName, fContextReq, 0,
SECURITY_NATIVE_DREP, (have_input_buffer) ? &input_buffer_desc : NULL,
0, &credssp->context, &output_buffer_desc, &pfContextAttr, &expiration);
if (have_input_buffer && (input_buffer.pvBuffer != NULL))
{
free(input_buffer.pvBuffer);
input_buffer.pvBuffer = NULL;
}
if ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED) || (status == SEC_E_OK))
{
if (credssp->table->CompleteAuthToken != NULL)
credssp->table->CompleteAuthToken(&credssp->context, &output_buffer_desc);
have_pub_key_auth = TRUE;
if (credssp->table->QueryContextAttributes(&credssp->context, SECPKG_ATTR_SIZES, &credssp->ContextSizes) != SEC_E_OK)
{
fprintf(stderr, "QueryContextAttributes SECPKG_ATTR_SIZES failure\n");
return 0;
}
credssp_encrypt_public_key_echo(credssp);
if (status == SEC_I_COMPLETE_NEEDED)
status = SEC_E_OK;
else if (status == SEC_I_COMPLETE_AND_CONTINUE)
status = SEC_I_CONTINUE_NEEDED;
}
/* send authentication token to server */
if (output_buffer.cbBuffer > 0)
{
credssp->negoToken.pvBuffer = output_buffer.pvBuffer;
credssp->negoToken.cbBuffer = output_buffer.cbBuffer;
#ifdef WITH_DEBUG_CREDSSP
fprintf(stderr, "Sending Authentication Token\n");
winpr_HexDump(credssp->negoToken.pvBuffer, credssp->negoToken.cbBuffer);
#endif
credssp_send(credssp);
credssp_buffer_free(credssp);
}
if (status != SEC_I_CONTINUE_NEEDED)
break;
/* receive server response and place in input buffer */
input_buffer_desc.ulVersion = SECBUFFER_VERSION;
input_buffer_desc.cBuffers = 1;
input_buffer_desc.pBuffers = &input_buffer;
input_buffer.BufferType = SECBUFFER_TOKEN;
if (credssp_recv(credssp) < 0)
return -1;
#ifdef WITH_DEBUG_CREDSSP
fprintf(stderr, "Receiving Authentication Token (%d)\n", (int) credssp->negoToken.cbBuffer);
winpr_HexDump(credssp->negoToken.pvBuffer, credssp->negoToken.cbBuffer);
#endif
input_buffer.pvBuffer = credssp->negoToken.pvBuffer;
input_buffer.cbBuffer = credssp->negoToken.cbBuffer;
have_input_buffer = TRUE;
have_context = TRUE;
}
/* Encrypted Public Key +1 */
if (credssp_recv(credssp) < 0)
return -1;
/* Verify Server Public Key Echo */
status = credssp_decrypt_public_key_echo(credssp);
credssp_buffer_free(credssp);
if (status != SEC_E_OK)
{
fprintf(stderr, "Could not verify public key echo!\n");
return -1;
}
/* Send encrypted credentials */
status = credssp_encrypt_ts_credentials(credssp);
if (status != SEC_E_OK)
{
fprintf(stderr, "credssp_encrypt_ts_credentials status: 0x%08X\n", status);
return 0;
}
credssp_send(credssp);
credssp_buffer_free(credssp);
/* Free resources */
credssp->table->FreeCredentialsHandle(&credentials);
credssp->table->FreeContextBuffer(pPackageInfo);
return 1;
}
/**
* Authenticate with client using CredSSP (server).
* @param credssp
* @return 1 if authentication is successful
*/
int credssp_server_authenticate(rdpCredssp* credssp)
{
UINT32 cbMaxToken;
ULONG fContextReq;
ULONG pfContextAttr;
SECURITY_STATUS status;
CredHandle credentials;
TimeStamp expiration;
PSecPkgInfo pPackageInfo;
SecBuffer input_buffer;
SecBuffer output_buffer;
SecBufferDesc input_buffer_desc;
SecBufferDesc output_buffer_desc;
BOOL have_context;
BOOL have_input_buffer;
BOOL have_pub_key_auth;
sspi_GlobalInit();
if (credssp_ntlm_server_init(credssp) == 0)
return 0;
#ifdef WITH_NATIVE_SSPI
if (!credssp->SspiModule)
credssp->SspiModule = _tcsdup(_T("secur32.dll"));
#endif
if (credssp->SspiModule)
{
HMODULE hSSPI;
INIT_SECURITY_INTERFACE pInitSecurityInterface;
hSSPI = LoadLibrary(credssp->SspiModule);
if (!hSSPI)
{
_tprintf(_T("Failed to load SSPI module: %s\n"), credssp->SspiModule);
return 0;
}
#ifdef UNICODE
pInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceW");
#else
pInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceA");
#endif
credssp->table = (*pInitSecurityInterface)();
}
#ifndef WITH_NATIVE_SSPI
else
{
credssp->table = InitSecurityInterface();
}
#endif
status = credssp->table->QuerySecurityPackageInfo(NLA_PKG_NAME, &pPackageInfo);
if (status != SEC_E_OK)
{
fprintf(stderr, "QuerySecurityPackageInfo status: 0x%08X\n", status);
return 0;
}
cbMaxToken = pPackageInfo->cbMaxToken;
status = credssp->table->AcquireCredentialsHandle(NULL, NLA_PKG_NAME,
SECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL, &credentials, &expiration);
if (status != SEC_E_OK)
{
fprintf(stderr, "AcquireCredentialsHandle status: 0x%08X\n", status);
return 0;
}
have_context = FALSE;
have_input_buffer = FALSE;
have_pub_key_auth = FALSE;
ZeroMemory(&input_buffer, sizeof(SecBuffer));
ZeroMemory(&output_buffer, sizeof(SecBuffer));
ZeroMemory(&input_buffer_desc, sizeof(SecBufferDesc));
ZeroMemory(&output_buffer_desc, sizeof(SecBufferDesc));
ZeroMemory(&credssp->ContextSizes, sizeof(SecPkgContext_Sizes));
/*
* from tspkg.dll: 0x00000112
* ASC_REQ_MUTUAL_AUTH
* ASC_REQ_CONFIDENTIALITY
* ASC_REQ_ALLOCATE_MEMORY
*/
fContextReq = 0;
fContextReq |= ASC_REQ_MUTUAL_AUTH;
fContextReq |= ASC_REQ_CONFIDENTIALITY;
fContextReq |= ASC_REQ_CONNECTION;
fContextReq |= ASC_REQ_USE_SESSION_KEY;
fContextReq |= ASC_REQ_REPLAY_DETECT;
fContextReq |= ASC_REQ_SEQUENCE_DETECT;
fContextReq |= ASC_REQ_EXTENDED_ERROR;
while (TRUE)
{
input_buffer_desc.ulVersion = SECBUFFER_VERSION;
input_buffer_desc.cBuffers = 1;
input_buffer_desc.pBuffers = &input_buffer;
input_buffer.BufferType = SECBUFFER_TOKEN;
/* receive authentication token */
input_buffer_desc.ulVersion = SECBUFFER_VERSION;
input_buffer_desc.cBuffers = 1;
input_buffer_desc.pBuffers = &input_buffer;
input_buffer.BufferType = SECBUFFER_TOKEN;
if (credssp_recv(credssp) < 0)
return -1;
#ifdef WITH_DEBUG_CREDSSP
fprintf(stderr, "Receiving Authentication Token\n");
credssp_buffer_print(credssp);
#endif
input_buffer.pvBuffer = credssp->negoToken.pvBuffer;
input_buffer.cbBuffer = credssp->negoToken.cbBuffer;
if (credssp->negoToken.cbBuffer < 1)
{
fprintf(stderr, "CredSSP: invalid negoToken!\n");
return -1;
}
output_buffer_desc.ulVersion = SECBUFFER_VERSION;
output_buffer_desc.cBuffers = 1;
output_buffer_desc.pBuffers = &output_buffer;
output_buffer.BufferType = SECBUFFER_TOKEN;
output_buffer.cbBuffer = cbMaxToken;
output_buffer.pvBuffer = malloc(output_buffer.cbBuffer);
status = credssp->table->AcceptSecurityContext(&credentials,
have_context? &credssp->context: NULL,
&input_buffer_desc, fContextReq, SECURITY_NATIVE_DREP, &credssp->context,
&output_buffer_desc, &pfContextAttr, &expiration);
credssp->negoToken.pvBuffer = output_buffer.pvBuffer;
credssp->negoToken.cbBuffer = output_buffer.cbBuffer;
if ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED))
{
if (credssp->table->CompleteAuthToken != NULL)
credssp->table->CompleteAuthToken(&credssp->context, &output_buffer_desc);
if (status == SEC_I_COMPLETE_NEEDED)
status = SEC_E_OK;
else if (status == SEC_I_COMPLETE_AND_CONTINUE)
status = SEC_I_CONTINUE_NEEDED;
}
if (status == SEC_E_OK)
{
have_pub_key_auth = TRUE;
if (credssp->table->QueryContextAttributes(&credssp->context, SECPKG_ATTR_SIZES, &credssp->ContextSizes) != SEC_E_OK)
{
fprintf(stderr, "QueryContextAttributes SECPKG_ATTR_SIZES failure\n");
return 0;
}
if (credssp_decrypt_public_key_echo(credssp) != SEC_E_OK)
{
fprintf(stderr, "Error: could not verify client's public key echo\n");
return -1;
}
sspi_SecBufferFree(&credssp->negoToken);
credssp->negoToken.pvBuffer = NULL;
credssp->negoToken.cbBuffer = 0;
credssp_encrypt_public_key_echo(credssp);
}
if ((status != SEC_E_OK) && (status != SEC_I_CONTINUE_NEEDED))
{
fprintf(stderr, "AcceptSecurityContext status: 0x%08X\n", status);
return -1;
}
/* send authentication token */
#ifdef WITH_DEBUG_CREDSSP
fprintf(stderr, "Sending Authentication Token\n");
credssp_buffer_print(credssp);
#endif
credssp_send(credssp);
credssp_buffer_free(credssp);
if (status != SEC_I_CONTINUE_NEEDED)
break;
have_context = TRUE;
}
/* Receive encrypted credentials */
if (credssp_recv(credssp) < 0)
return -1;
if (credssp_decrypt_ts_credentials(credssp) != SEC_E_OK)
{
fprintf(stderr, "Could not decrypt TSCredentials status: 0x%08X\n", status);
return 0;
}
if (status != SEC_E_OK)
{
fprintf(stderr, "AcceptSecurityContext status: 0x%08X\n", status);
return 0;
}
status = credssp->table->ImpersonateSecurityContext(&credssp->context);
if (status != SEC_E_OK)
{
fprintf(stderr, "ImpersonateSecurityContext status: 0x%08X\n", status);
return 0;
}
else
{
status = credssp->table->RevertSecurityContext(&credssp->context);
if (status != SEC_E_OK)
{
fprintf(stderr, "RevertSecurityContext status: 0x%08X\n", status);
return 0;
}
}
credssp->table->FreeContextBuffer(pPackageInfo);
return 1;
}
/**
* Authenticate using CredSSP.
* @param credssp
* @return 1 if authentication is successful
*/
int credssp_authenticate(rdpCredssp* credssp)
{
if (credssp->server)
return credssp_server_authenticate(credssp);
else
return credssp_client_authenticate(credssp);
}
void ap_integer_increment_le(BYTE* number, int size)
{
int index;
for (index = 0; index < size; index++)
{
if (number[index] < 0xFF)
{
number[index]++;
break;
}
else
{
number[index] = 0;
continue;
}
}
}
void ap_integer_decrement_le(BYTE* number, int size)
{
int index;
for (index = 0; index < size; index++)
{
if (number[index] > 0)
{
number[index]--;
break;
}
else
{
number[index] = 0xFF;
continue;
}
}
}
SECURITY_STATUS credssp_encrypt_public_key_echo(rdpCredssp* credssp)
{
SecBuffer Buffers[2];
SecBufferDesc Message;
SECURITY_STATUS status;
int public_key_length;
public_key_length = credssp->PublicKey.cbBuffer;
Buffers[0].BufferType = SECBUFFER_TOKEN; /* Signature */
Buffers[1].BufferType = SECBUFFER_DATA; /* TLS Public Key */
sspi_SecBufferAlloc(&credssp->pubKeyAuth, credssp->ContextSizes.cbMaxSignature + public_key_length);
Buffers[0].cbBuffer = credssp->ContextSizes.cbMaxSignature;
Buffers[0].pvBuffer = credssp->pubKeyAuth.pvBuffer;
Buffers[1].cbBuffer = public_key_length;
Buffers[1].pvBuffer = ((BYTE*) credssp->pubKeyAuth.pvBuffer) + credssp->ContextSizes.cbMaxSignature;
CopyMemory(Buffers[1].pvBuffer, credssp->PublicKey.pvBuffer, Buffers[1].cbBuffer);
if (credssp->server)
{
/* server echos the public key +1 */
ap_integer_increment_le((BYTE*) Buffers[1].pvBuffer, Buffers[1].cbBuffer);
}
Message.cBuffers = 2;
Message.ulVersion = SECBUFFER_VERSION;
Message.pBuffers = (PSecBuffer) &Buffers;
status = credssp->table->EncryptMessage(&credssp->context, 0, &Message, credssp->send_seq_num++);
if (status != SEC_E_OK)
{
fprintf(stderr, "EncryptMessage status: 0x%08X\n", status);
return status;
}
return status;
}
SECURITY_STATUS credssp_decrypt_public_key_echo(rdpCredssp* credssp)
{
int length;
BYTE* buffer;
ULONG pfQOP;
BYTE* public_key1;
BYTE* public_key2;
int public_key_length;
SecBuffer Buffers[2];
SecBufferDesc Message;
SECURITY_STATUS status;
if (credssp->PublicKey.cbBuffer + credssp->ContextSizes.cbMaxSignature != credssp->pubKeyAuth.cbBuffer)
{
fprintf(stderr, "unexpected pubKeyAuth buffer size:%d\n", (int) credssp->pubKeyAuth.cbBuffer);
return SEC_E_INVALID_TOKEN;
}
length = credssp->pubKeyAuth.cbBuffer;
buffer = (BYTE*) malloc(length);
CopyMemory(buffer, credssp->pubKeyAuth.pvBuffer, length);
public_key_length = credssp->PublicKey.cbBuffer;
Buffers[0].BufferType = SECBUFFER_TOKEN; /* Signature */
Buffers[1].BufferType = SECBUFFER_DATA; /* Encrypted TLS Public Key */
Buffers[0].cbBuffer = credssp->ContextSizes.cbMaxSignature;
Buffers[0].pvBuffer = buffer;
Buffers[1].cbBuffer = length - credssp->ContextSizes.cbMaxSignature;
Buffers[1].pvBuffer = buffer + credssp->ContextSizes.cbMaxSignature;
Message.cBuffers = 2;
Message.ulVersion = SECBUFFER_VERSION;
Message.pBuffers = (PSecBuffer) &Buffers;
status = credssp->table->DecryptMessage(&credssp->context, &Message, credssp->recv_seq_num++, &pfQOP);
if (status != SEC_E_OK)
{
fprintf(stderr, "DecryptMessage failure: 0x%08X\n", status);
return status;
}
public_key1 = (BYTE*) credssp->PublicKey.pvBuffer;
public_key2 = (BYTE*) Buffers[1].pvBuffer;
if (!credssp->server)
{
/* server echos the public key +1 */
ap_integer_decrement_le(public_key2, public_key_length);
}
if (memcmp(public_key1, public_key2, public_key_length) != 0)
{
fprintf(stderr, "Could not verify server's public key echo\n");
fprintf(stderr, "Expected (length = %d):\n", public_key_length);
winpr_HexDump(public_key1, public_key_length);
fprintf(stderr, "Actual (length = %d):\n", public_key_length);
winpr_HexDump(public_key2, public_key_length);
return SEC_E_MESSAGE_ALTERED; /* DO NOT SEND CREDENTIALS! */
}
free(buffer);
return SEC_E_OK;
}
int credssp_sizeof_ts_password_creds(rdpCredssp* credssp)
{
int length = 0;
length += ber_sizeof_sequence_octet_string(credssp->identity.DomainLength * 2);
length += ber_sizeof_sequence_octet_string(credssp->identity.UserLength * 2);
length += ber_sizeof_sequence_octet_string(credssp->identity.PasswordLength * 2);
return length;
}
void credssp_read_ts_password_creds(rdpCredssp* credssp, wStream* s)
{
int length;
/* TSPasswordCreds (SEQUENCE) */
ber_read_sequence_tag(s, &length);
/* [0] domainName (OCTET STRING) */
ber_read_contextual_tag(s, 0, &length, TRUE);
ber_read_octet_string_tag(s, &length);
credssp->identity.DomainLength = (UINT32) length;
credssp->identity.Domain = (UINT16*) malloc(length);
CopyMemory(credssp->identity.Domain, Stream_Pointer(s), credssp->identity.DomainLength);
Stream_Seek(s, credssp->identity.DomainLength);
credssp->identity.DomainLength /= 2;
/* [1] userName (OCTET STRING) */
ber_read_contextual_tag(s, 1, &length, TRUE);
ber_read_octet_string_tag(s, &length);
credssp->identity.UserLength = (UINT32) length;
credssp->identity.User = (UINT16*) malloc(length);
CopyMemory(credssp->identity.User, Stream_Pointer(s), credssp->identity.UserLength);
Stream_Seek(s, credssp->identity.UserLength);
credssp->identity.UserLength /= 2;
/* [2] password (OCTET STRING) */
ber_read_contextual_tag(s, 2, &length, TRUE);
ber_read_octet_string_tag(s, &length);
credssp->identity.PasswordLength = (UINT32) length;
credssp->identity.Password = (UINT16*) malloc(length);
CopyMemory(credssp->identity.Password, Stream_Pointer(s), credssp->identity.PasswordLength);
Stream_Seek(s, credssp->identity.PasswordLength);
credssp->identity.PasswordLength /= 2;
credssp->identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
}
int credssp_write_ts_password_creds(rdpCredssp* credssp, wStream* s)
{
int size = 0;
int innerSize = credssp_sizeof_ts_password_creds(credssp);
/* TSPasswordCreds (SEQUENCE) */
size += ber_write_sequence_tag(s, innerSize);
/* [0] domainName (OCTET STRING) */
size += ber_write_sequence_octet_string(s, 0, (BYTE*) credssp->identity.Domain, credssp->identity.DomainLength * 2);
/* [1] userName (OCTET STRING) */
size += ber_write_sequence_octet_string(s, 1, (BYTE*) credssp->identity.User, credssp->identity.UserLength * 2);
/* [2] password (OCTET STRING) */
size += ber_write_sequence_octet_string(s, 2, (BYTE*) credssp->identity.Password, credssp->identity.PasswordLength * 2);
return size;
}
int credssp_sizeof_ts_credentials(rdpCredssp* credssp)
{
int size = 0;
size += ber_sizeof_integer(1);
size += ber_sizeof_contextual_tag(ber_sizeof_integer(1));
size += ber_sizeof_sequence_octet_string(ber_sizeof_sequence(credssp_sizeof_ts_password_creds(credssp)));
return size;
}
void credssp_read_ts_credentials(rdpCredssp* credssp, PSecBuffer ts_credentials)
{
wStream* s;
int length;
int ts_password_creds_length;
s = Stream_New(ts_credentials->pvBuffer, ts_credentials->cbBuffer);
/* TSCredentials (SEQUENCE) */
ber_read_sequence_tag(s, &length);
/* [0] credType (INTEGER) */
ber_read_contextual_tag(s, 0, &length, TRUE);
ber_read_integer(s, NULL);
/* [1] credentials (OCTET STRING) */
ber_read_contextual_tag(s, 1, &length, TRUE);
ber_read_octet_string_tag(s, &ts_password_creds_length);
credssp_read_ts_password_creds(credssp, s);
Stream_Free(s, FALSE);
}
int credssp_write_ts_credentials(rdpCredssp* credssp, wStream* s)
{
int size = 0;
int innerSize = credssp_sizeof_ts_credentials(credssp);
int passwordSize;
/* TSCredentials (SEQUENCE) */
size += ber_write_sequence_tag(s, innerSize);
/* [0] credType (INTEGER) */
size += ber_write_contextual_tag(s, 0, ber_sizeof_integer(1), TRUE);
size += ber_write_integer(s, 1);
/* [1] credentials (OCTET STRING) */
passwordSize = ber_sizeof_sequence(credssp_sizeof_ts_password_creds(credssp));
size += ber_write_contextual_tag(s, 1, ber_sizeof_octet_string(passwordSize), TRUE);
size += ber_write_octet_string_tag(s, passwordSize);
size += credssp_write_ts_password_creds(credssp, s);
return size;
}
/**
* Encode TSCredentials structure.
* @param credssp
*/
void credssp_encode_ts_credentials(rdpCredssp* credssp)
{
wStream* s;
int length;
length = ber_sizeof_sequence(credssp_sizeof_ts_credentials(credssp));
sspi_SecBufferAlloc(&credssp->ts_credentials, length);
s = Stream_New(credssp->ts_credentials.pvBuffer, length);
credssp_write_ts_credentials(credssp, s);
Stream_Free(s, FALSE);
}
SECURITY_STATUS credssp_encrypt_ts_credentials(rdpCredssp* credssp)
{
SecBuffer Buffers[2];
SecBufferDesc Message;
SECURITY_STATUS status;
credssp_encode_ts_credentials(credssp);
Buffers[0].BufferType = SECBUFFER_TOKEN; /* Signature */
Buffers[1].BufferType = SECBUFFER_DATA; /* TSCredentials */
sspi_SecBufferAlloc(&credssp->authInfo, credssp->ContextSizes.cbMaxSignature + credssp->ts_credentials.cbBuffer);
Buffers[0].cbBuffer = credssp->ContextSizes.cbMaxSignature;
Buffers[0].pvBuffer = credssp->authInfo.pvBuffer;
ZeroMemory(Buffers[0].pvBuffer, Buffers[0].cbBuffer);
Buffers[1].cbBuffer = credssp->ts_credentials.cbBuffer;
Buffers[1].pvBuffer = &((BYTE*) credssp->authInfo.pvBuffer)[Buffers[0].cbBuffer];
CopyMemory(Buffers[1].pvBuffer, credssp->ts_credentials.pvBuffer, Buffers[1].cbBuffer);
Message.cBuffers = 2;
Message.ulVersion = SECBUFFER_VERSION;
Message.pBuffers = (PSecBuffer) &Buffers;
status = credssp->table->EncryptMessage(&credssp->context, 0, &Message, credssp->send_seq_num++);
if (status != SEC_E_OK)
return status;
return SEC_E_OK;
}
SECURITY_STATUS credssp_decrypt_ts_credentials(rdpCredssp* credssp)
{
int length;
BYTE* buffer;
ULONG pfQOP;
SecBuffer Buffers[2];
SecBufferDesc Message;
SECURITY_STATUS status;
Buffers[0].BufferType = SECBUFFER_TOKEN; /* Signature */
Buffers[1].BufferType = SECBUFFER_DATA; /* TSCredentials */
if (credssp->authInfo.cbBuffer < 1)
{
fprintf(stderr, "credssp_decrypt_ts_credentials missing authInfo buffer\n");
return SEC_E_INVALID_TOKEN;
}
length = credssp->authInfo.cbBuffer;
buffer = (BYTE*) malloc(length);
CopyMemory(buffer, credssp->authInfo.pvBuffer, length);
Buffers[0].cbBuffer = credssp->ContextSizes.cbMaxSignature;
Buffers[0].pvBuffer = buffer;
Buffers[1].cbBuffer = length - credssp->ContextSizes.cbMaxSignature;
Buffers[1].pvBuffer = &buffer[credssp->ContextSizes.cbMaxSignature];
Message.cBuffers = 2;
Message.ulVersion = SECBUFFER_VERSION;
Message.pBuffers = (PSecBuffer) &Buffers;
status = credssp->table->DecryptMessage(&credssp->context, &Message, credssp->recv_seq_num++, &pfQOP);
if (status != SEC_E_OK)
return status;
credssp_read_ts_credentials(credssp, &Buffers[1]);
free(buffer);
return SEC_E_OK;
}
int credssp_sizeof_nego_token(int length)
{
length = ber_sizeof_octet_string(length);
length += ber_sizeof_contextual_tag(length);
return length;
}
int credssp_sizeof_nego_tokens(int length)
{
length = credssp_sizeof_nego_token(length);
length += ber_sizeof_sequence_tag(length);
length += ber_sizeof_sequence_tag(length);
length += ber_sizeof_contextual_tag(length);
return length;
}
int credssp_sizeof_pub_key_auth(int length)
{
length = ber_sizeof_octet_string(length);
length += ber_sizeof_contextual_tag(length);
return length;
}
int credssp_sizeof_auth_info(int length)
{
length = ber_sizeof_octet_string(length);
length += ber_sizeof_contextual_tag(length);
return length;
}
int credssp_sizeof_ts_request(int length)
{
length += ber_sizeof_integer(2);
length += ber_sizeof_contextual_tag(3);
return length;
}
/**
* Send CredSSP message.
* @param credssp
*/
void credssp_send(rdpCredssp* credssp)
{
wStream* s;
int length;
int ts_request_length;
int nego_tokens_length;
int pub_key_auth_length;
int auth_info_length;
nego_tokens_length = (credssp->negoToken.cbBuffer > 0) ? credssp_sizeof_nego_tokens(credssp->negoToken.cbBuffer) : 0;
pub_key_auth_length = (credssp->pubKeyAuth.cbBuffer > 0) ? credssp_sizeof_pub_key_auth(credssp->pubKeyAuth.cbBuffer) : 0;
auth_info_length = (credssp->authInfo.cbBuffer > 0) ? credssp_sizeof_auth_info(credssp->authInfo.cbBuffer) : 0;
length = nego_tokens_length + pub_key_auth_length + auth_info_length;
ts_request_length = credssp_sizeof_ts_request(length);
s = Stream_New(NULL, ber_sizeof_sequence(ts_request_length));
/* TSRequest */
ber_write_sequence_tag(s, ts_request_length); /* SEQUENCE */
/* [0] version */
ber_write_contextual_tag(s, 0, 3, TRUE);
ber_write_integer(s, 2); /* INTEGER */
/* [1] negoTokens (NegoData) */
if (nego_tokens_length > 0)
{
length = nego_tokens_length;
length -= ber_write_contextual_tag(s, 1, ber_sizeof_sequence(ber_sizeof_sequence(ber_sizeof_sequence_octet_string(credssp->negoToken.cbBuffer))), TRUE); /* NegoData */
length -= ber_write_sequence_tag(s, ber_sizeof_sequence(ber_sizeof_sequence_octet_string(credssp->negoToken.cbBuffer))); /* SEQUENCE OF NegoDataItem */
length -= ber_write_sequence_tag(s, ber_sizeof_sequence_octet_string(credssp->negoToken.cbBuffer)); /* NegoDataItem */
length -= ber_write_sequence_octet_string(s, 0, (BYTE*) credssp->negoToken.pvBuffer, credssp->negoToken.cbBuffer); /* OCTET STRING */
// assert length == 0
}
/* [2] authInfo (OCTET STRING) */
if (auth_info_length > 0)
{
length = auth_info_length;
length -= ber_write_sequence_octet_string(s, 2, credssp->authInfo.pvBuffer, credssp->authInfo.cbBuffer);
// assert length == 0
}
/* [3] pubKeyAuth (OCTET STRING) */
if (pub_key_auth_length > 0)
{
length = pub_key_auth_length;
length -= ber_write_sequence_octet_string(s, 3, credssp->pubKeyAuth.pvBuffer, credssp->pubKeyAuth.cbBuffer);
// assert length == 0
}
Stream_SealLength(s);
transport_write(credssp->transport, s);
Stream_Free(s, TRUE);
}
/**
* Receive CredSSP message.
* @param credssp
* @return
*/
int credssp_recv(rdpCredssp* credssp)
{
wStream* s;
int length;
int status;
UINT32 version;
s = Stream_New(NULL, 4096);
status = transport_read(credssp->transport, s);
Stream_Length(s) = status;
if (status < 0)
{
fprintf(stderr, "credssp_recv() error: %d\n", status);
Stream_Free(s, TRUE);
return -1;
}
/* TSRequest */
if(!ber_read_sequence_tag(s, &length) ||
!ber_read_contextual_tag(s, 0, &length, TRUE) ||
!ber_read_integer(s, &version))
return -1;
/* [1] negoTokens (NegoData) */
if (ber_read_contextual_tag(s, 1, &length, TRUE) != FALSE)
{
if (!ber_read_sequence_tag(s, &length) || /* SEQUENCE OF NegoDataItem */
!ber_read_sequence_tag(s, &length) || /* NegoDataItem */
!ber_read_contextual_tag(s, 0, &length, TRUE) || /* [0] negoToken */
!ber_read_octet_string_tag(s, &length) || /* OCTET STRING */
Stream_GetRemainingLength(s) < length)
return -1;
sspi_SecBufferAlloc(&credssp->negoToken, length);
Stream_Read(s, credssp->negoToken.pvBuffer, length);
credssp->negoToken.cbBuffer = length;
}
/* [2] authInfo (OCTET STRING) */
if (ber_read_contextual_tag(s, 2, &length, TRUE) != FALSE)
{
if(!ber_read_octet_string_tag(s, &length) || /* OCTET STRING */
Stream_GetRemainingLength(s) < length)
return -1;
sspi_SecBufferAlloc(&credssp->authInfo, length);
Stream_Read(s, credssp->authInfo.pvBuffer, length);
credssp->authInfo.cbBuffer = length;
}
/* [3] pubKeyAuth (OCTET STRING) */
if (ber_read_contextual_tag(s, 3, &length, TRUE) != FALSE)
{
if(!ber_read_octet_string_tag(s, &length) || /* OCTET STRING */
Stream_GetRemainingLength(s) < length)
return -1;
sspi_SecBufferAlloc(&credssp->pubKeyAuth, length);
Stream_Read(s, credssp->pubKeyAuth.pvBuffer, length);
credssp->pubKeyAuth.cbBuffer = length;
}
Stream_Free(s, TRUE);
return 0;
}
void credssp_buffer_print(rdpCredssp* credssp)
{
if (credssp->negoToken.cbBuffer > 0)
{
fprintf(stderr, "CredSSP.negoToken (length = %d):\n", (int) credssp->negoToken.cbBuffer);
winpr_HexDump(credssp->negoToken.pvBuffer, credssp->negoToken.cbBuffer);
}
if (credssp->pubKeyAuth.cbBuffer > 0)
{
fprintf(stderr, "CredSSP.pubKeyAuth (length = %d):\n", (int) credssp->pubKeyAuth.cbBuffer);
winpr_HexDump(credssp->pubKeyAuth.pvBuffer, credssp->pubKeyAuth.cbBuffer);
}
if (credssp->authInfo.cbBuffer > 0)
{
fprintf(stderr, "CredSSP.authInfo (length = %d):\n", (int) credssp->authInfo.cbBuffer);
winpr_HexDump(credssp->authInfo.pvBuffer, credssp->authInfo.cbBuffer);
}
}
void credssp_buffer_free(rdpCredssp* credssp)
{
sspi_SecBufferFree(&credssp->negoToken);
sspi_SecBufferFree(&credssp->pubKeyAuth);
sspi_SecBufferFree(&credssp->authInfo);
}
/**
* Create new CredSSP state machine.
* @param transport
* @return new CredSSP state machine.
*/
rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings)
{
rdpCredssp* credssp;
credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp));
ZeroMemory(credssp, sizeof(rdpCredssp));
if (credssp != NULL)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
credssp->instance = instance;
credssp->settings = settings;
credssp->server = settings->ServerMode;
credssp->transport = transport;
credssp->send_seq_num = 0;
credssp->recv_seq_num = 0;
ZeroMemory(&credssp->negoToken, sizeof(SecBuffer));
ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));
ZeroMemory(&credssp->authInfo, sizeof(SecBuffer));
if (credssp->server)
{
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"),
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize);
if (status == ERROR_SUCCESS)
{
credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR));
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType,
(BYTE*) credssp->SspiModule, &dwSize);
if (status == ERROR_SUCCESS)
{
_tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule);
RegCloseKey(hKey);
}
}
}
}
}
return credssp;
}
/**
* Free CredSSP state machine.
* @param credssp
*/
void credssp_free(rdpCredssp* credssp)
{
if (credssp != NULL)
{
if (credssp->table)
credssp->table->DeleteSecurityContext(&credssp->context);
sspi_SecBufferFree(&credssp->PublicKey);
sspi_SecBufferFree(&credssp->ts_credentials);
free(credssp->ServicePrincipalName);
free(credssp->identity.User);
free(credssp->identity.Domain);
free(credssp->identity.Password);
free(credssp);
}
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_5715_0 |
crossvul-cpp_data_bad_2744_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.
*
* ROUTE - implementation of the IP router.
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Alan Cox, <gw4pts@gw4pts.ampr.org>
* Linus Torvalds, <Linus.Torvalds@helsinki.fi>
* Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*
* Fixes:
* Alan Cox : Verify area fixes.
* Alan Cox : cli() protects routing changes
* Rui Oliveira : ICMP routing table updates
* (rco@di.uminho.pt) Routing table insertion and update
* Linus Torvalds : Rewrote bits to be sensible
* Alan Cox : Added BSD route gw semantics
* Alan Cox : Super /proc >4K
* Alan Cox : MTU in route table
* Alan Cox : MSS actually. Also added the window
* clamper.
* Sam Lantinga : Fixed route matching in rt_del()
* Alan Cox : Routing cache support.
* Alan Cox : Removed compatibility cruft.
* Alan Cox : RTF_REJECT support.
* Alan Cox : TCP irtt support.
* Jonathan Naylor : Added Metric support.
* Miquel van Smoorenburg : BSD API fixes.
* Miquel van Smoorenburg : Metrics.
* Alan Cox : Use __u32 properly
* Alan Cox : Aligned routing errors more closely with BSD
* our system is still very different.
* Alan Cox : Faster /proc handling
* Alexey Kuznetsov : Massive rework to support tree based routing,
* routing caches and better behaviour.
*
* Olaf Erb : irtt wasn't being copied right.
* Bjorn Ekwall : Kerneld route support.
* Alan Cox : Multicast fixed (I hope)
* Pavel Krauz : Limited broadcast fixed
* Mike McLagan : Routing by source
* Alexey Kuznetsov : End of old history. Split to fib.c and
* route.c and rewritten from scratch.
* Andi Kleen : Load-limit warning messages.
* Vitaly E. Lavrov : Transparent proxy revived after year coma.
* Vitaly E. Lavrov : Race condition in ip_route_input_slow.
* Tobias Ringstrom : Uninitialized res.type in ip_route_output_slow.
* Vladimir V. Ivanov : IP rule info (flowid) is really useful.
* Marc Boucher : routing by fwmark
* Robert Olsson : Added rt_cache statistics
* Arnaldo C. Melo : Convert proc stuff to seq_file
* Eric Dumazet : hashed spinlocks and rt_check_expire() fixes.
* Ilia Sotnikov : Ignore TOS on PMTUD and Redirect
* Ilia Sotnikov : Removed TOS from hash calculations
*
* 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) "IPv4: " fmt
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/bitops.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/errno.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/inetdevice.h>
#include <linux/igmp.h>
#include <linux/pkt_sched.h>
#include <linux/mroute.h>
#include <linux/netfilter_ipv4.h>
#include <linux/random.h>
#include <linux/rcupdate.h>
#include <linux/times.h>
#include <linux/slab.h>
#include <linux/jhash.h>
#include <net/dst.h>
#include <net/dst_metadata.h>
#include <net/net_namespace.h>
#include <net/protocol.h>
#include <net/ip.h>
#include <net/route.h>
#include <net/inetpeer.h>
#include <net/sock.h>
#include <net/ip_fib.h>
#include <net/arp.h>
#include <net/tcp.h>
#include <net/icmp.h>
#include <net/xfrm.h>
#include <net/lwtunnel.h>
#include <net/netevent.h>
#include <net/rtnetlink.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#include <linux/kmemleak.h>
#endif
#include <net/secure_seq.h>
#include <net/ip_tunnels.h>
#include <net/l3mdev.h>
#include "fib_lookup.h"
#define RT_FL_TOS(oldflp4) \
((oldflp4)->flowi4_tos & (IPTOS_RT_MASK | RTO_ONLINK))
#define RT_GC_TIMEOUT (300*HZ)
static int ip_rt_max_size;
static int ip_rt_redirect_number __read_mostly = 9;
static int ip_rt_redirect_load __read_mostly = HZ / 50;
static int ip_rt_redirect_silence __read_mostly = ((HZ / 50) << (9 + 1));
static int ip_rt_error_cost __read_mostly = HZ;
static int ip_rt_error_burst __read_mostly = 5 * HZ;
static int ip_rt_mtu_expires __read_mostly = 10 * 60 * HZ;
static int ip_rt_min_pmtu __read_mostly = 512 + 20 + 20;
static int ip_rt_min_advmss __read_mostly = 256;
static int ip_rt_gc_timeout __read_mostly = RT_GC_TIMEOUT;
/*
* Interface to generic destination cache.
*/
static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie);
static unsigned int ipv4_default_advmss(const struct dst_entry *dst);
static unsigned int ipv4_mtu(const struct dst_entry *dst);
static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst);
static void ipv4_link_failure(struct sk_buff *skb);
static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu);
static void ip_do_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb);
static void ipv4_dst_destroy(struct dst_entry *dst);
static u32 *ipv4_cow_metrics(struct dst_entry *dst, unsigned long old)
{
WARN_ON(1);
return NULL;
}
static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst,
struct sk_buff *skb,
const void *daddr);
static void ipv4_confirm_neigh(const struct dst_entry *dst, const void *daddr);
static struct dst_ops ipv4_dst_ops = {
.family = AF_INET,
.check = ipv4_dst_check,
.default_advmss = ipv4_default_advmss,
.mtu = ipv4_mtu,
.cow_metrics = ipv4_cow_metrics,
.destroy = ipv4_dst_destroy,
.negative_advice = ipv4_negative_advice,
.link_failure = ipv4_link_failure,
.update_pmtu = ip_rt_update_pmtu,
.redirect = ip_do_redirect,
.local_out = __ip_local_out,
.neigh_lookup = ipv4_neigh_lookup,
.confirm_neigh = ipv4_confirm_neigh,
};
#define ECN_OR_COST(class) TC_PRIO_##class
const __u8 ip_tos2prio[16] = {
TC_PRIO_BESTEFFORT,
ECN_OR_COST(BESTEFFORT),
TC_PRIO_BESTEFFORT,
ECN_OR_COST(BESTEFFORT),
TC_PRIO_BULK,
ECN_OR_COST(BULK),
TC_PRIO_BULK,
ECN_OR_COST(BULK),
TC_PRIO_INTERACTIVE,
ECN_OR_COST(INTERACTIVE),
TC_PRIO_INTERACTIVE,
ECN_OR_COST(INTERACTIVE),
TC_PRIO_INTERACTIVE_BULK,
ECN_OR_COST(INTERACTIVE_BULK),
TC_PRIO_INTERACTIVE_BULK,
ECN_OR_COST(INTERACTIVE_BULK)
};
EXPORT_SYMBOL(ip_tos2prio);
static DEFINE_PER_CPU(struct rt_cache_stat, rt_cache_stat);
#define RT_CACHE_STAT_INC(field) raw_cpu_inc(rt_cache_stat.field)
#ifdef CONFIG_PROC_FS
static void *rt_cache_seq_start(struct seq_file *seq, loff_t *pos)
{
if (*pos)
return NULL;
return SEQ_START_TOKEN;
}
static void *rt_cache_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return NULL;
}
static void rt_cache_seq_stop(struct seq_file *seq, void *v)
{
}
static int rt_cache_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_printf(seq, "%-127s\n",
"Iface\tDestination\tGateway \tFlags\t\tRefCnt\tUse\t"
"Metric\tSource\t\tMTU\tWindow\tIRTT\tTOS\tHHRef\t"
"HHUptod\tSpecDst");
return 0;
}
static const struct seq_operations rt_cache_seq_ops = {
.start = rt_cache_seq_start,
.next = rt_cache_seq_next,
.stop = rt_cache_seq_stop,
.show = rt_cache_seq_show,
};
static int rt_cache_seq_open(struct inode *inode, struct file *file)
{
return seq_open(file, &rt_cache_seq_ops);
}
static const struct file_operations rt_cache_seq_fops = {
.owner = THIS_MODULE,
.open = rt_cache_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static void *rt_cpu_seq_start(struct seq_file *seq, loff_t *pos)
{
int cpu;
if (*pos == 0)
return SEQ_START_TOKEN;
for (cpu = *pos-1; cpu < nr_cpu_ids; ++cpu) {
if (!cpu_possible(cpu))
continue;
*pos = cpu+1;
return &per_cpu(rt_cache_stat, cpu);
}
return NULL;
}
static void *rt_cpu_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
int cpu;
for (cpu = *pos; cpu < nr_cpu_ids; ++cpu) {
if (!cpu_possible(cpu))
continue;
*pos = cpu+1;
return &per_cpu(rt_cache_stat, cpu);
}
return NULL;
}
static void rt_cpu_seq_stop(struct seq_file *seq, void *v)
{
}
static int rt_cpu_seq_show(struct seq_file *seq, void *v)
{
struct rt_cache_stat *st = v;
if (v == SEQ_START_TOKEN) {
seq_printf(seq, "entries in_hit in_slow_tot in_slow_mc in_no_route in_brd in_martian_dst in_martian_src out_hit out_slow_tot out_slow_mc gc_total gc_ignored gc_goal_miss gc_dst_overflow in_hlist_search out_hlist_search\n");
return 0;
}
seq_printf(seq,"%08x %08x %08x %08x %08x %08x %08x %08x "
" %08x %08x %08x %08x %08x %08x %08x %08x %08x \n",
dst_entries_get_slow(&ipv4_dst_ops),
0, /* st->in_hit */
st->in_slow_tot,
st->in_slow_mc,
st->in_no_route,
st->in_brd,
st->in_martian_dst,
st->in_martian_src,
0, /* st->out_hit */
st->out_slow_tot,
st->out_slow_mc,
0, /* st->gc_total */
0, /* st->gc_ignored */
0, /* st->gc_goal_miss */
0, /* st->gc_dst_overflow */
0, /* st->in_hlist_search */
0 /* st->out_hlist_search */
);
return 0;
}
static const struct seq_operations rt_cpu_seq_ops = {
.start = rt_cpu_seq_start,
.next = rt_cpu_seq_next,
.stop = rt_cpu_seq_stop,
.show = rt_cpu_seq_show,
};
static int rt_cpu_seq_open(struct inode *inode, struct file *file)
{
return seq_open(file, &rt_cpu_seq_ops);
}
static const struct file_operations rt_cpu_seq_fops = {
.owner = THIS_MODULE,
.open = rt_cpu_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
#ifdef CONFIG_IP_ROUTE_CLASSID
static int rt_acct_proc_show(struct seq_file *m, void *v)
{
struct ip_rt_acct *dst, *src;
unsigned int i, j;
dst = kcalloc(256, sizeof(struct ip_rt_acct), GFP_KERNEL);
if (!dst)
return -ENOMEM;
for_each_possible_cpu(i) {
src = (struct ip_rt_acct *)per_cpu_ptr(ip_rt_acct, i);
for (j = 0; j < 256; j++) {
dst[j].o_bytes += src[j].o_bytes;
dst[j].o_packets += src[j].o_packets;
dst[j].i_bytes += src[j].i_bytes;
dst[j].i_packets += src[j].i_packets;
}
}
seq_write(m, dst, 256 * sizeof(struct ip_rt_acct));
kfree(dst);
return 0;
}
static int rt_acct_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, rt_acct_proc_show, NULL);
}
static const struct file_operations rt_acct_proc_fops = {
.owner = THIS_MODULE,
.open = rt_acct_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
static int __net_init ip_rt_do_proc_init(struct net *net)
{
struct proc_dir_entry *pde;
pde = proc_create("rt_cache", S_IRUGO, net->proc_net,
&rt_cache_seq_fops);
if (!pde)
goto err1;
pde = proc_create("rt_cache", S_IRUGO,
net->proc_net_stat, &rt_cpu_seq_fops);
if (!pde)
goto err2;
#ifdef CONFIG_IP_ROUTE_CLASSID
pde = proc_create("rt_acct", 0, net->proc_net, &rt_acct_proc_fops);
if (!pde)
goto err3;
#endif
return 0;
#ifdef CONFIG_IP_ROUTE_CLASSID
err3:
remove_proc_entry("rt_cache", net->proc_net_stat);
#endif
err2:
remove_proc_entry("rt_cache", net->proc_net);
err1:
return -ENOMEM;
}
static void __net_exit ip_rt_do_proc_exit(struct net *net)
{
remove_proc_entry("rt_cache", net->proc_net_stat);
remove_proc_entry("rt_cache", net->proc_net);
#ifdef CONFIG_IP_ROUTE_CLASSID
remove_proc_entry("rt_acct", net->proc_net);
#endif
}
static struct pernet_operations ip_rt_proc_ops __net_initdata = {
.init = ip_rt_do_proc_init,
.exit = ip_rt_do_proc_exit,
};
static int __init ip_rt_proc_init(void)
{
return register_pernet_subsys(&ip_rt_proc_ops);
}
#else
static inline int ip_rt_proc_init(void)
{
return 0;
}
#endif /* CONFIG_PROC_FS */
static inline bool rt_is_expired(const struct rtable *rth)
{
return rth->rt_genid != rt_genid_ipv4(dev_net(rth->dst.dev));
}
void rt_cache_flush(struct net *net)
{
rt_genid_bump_ipv4(net);
}
static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst,
struct sk_buff *skb,
const void *daddr)
{
struct net_device *dev = dst->dev;
const __be32 *pkey = daddr;
const struct rtable *rt;
struct neighbour *n;
rt = (const struct rtable *) dst;
if (rt->rt_gateway)
pkey = (const __be32 *) &rt->rt_gateway;
else if (skb)
pkey = &ip_hdr(skb)->daddr;
n = __ipv4_neigh_lookup(dev, *(__force u32 *)pkey);
if (n)
return n;
return neigh_create(&arp_tbl, pkey, dev);
}
static void ipv4_confirm_neigh(const struct dst_entry *dst, const void *daddr)
{
struct net_device *dev = dst->dev;
const __be32 *pkey = daddr;
const struct rtable *rt;
rt = (const struct rtable *)dst;
if (rt->rt_gateway)
pkey = (const __be32 *)&rt->rt_gateway;
else if (!daddr ||
(rt->rt_flags &
(RTCF_MULTICAST | RTCF_BROADCAST | RTCF_LOCAL)))
return;
__ipv4_confirm_neigh(dev, *(__force u32 *)pkey);
}
#define IP_IDENTS_SZ 2048u
static atomic_t *ip_idents __read_mostly;
static u32 *ip_tstamps __read_mostly;
/* In order to protect privacy, we add a perturbation to identifiers
* if one generator is seldom used. This makes hard for an attacker
* to infer how many packets were sent between two points in time.
*/
u32 ip_idents_reserve(u32 hash, int segs)
{
u32 *p_tstamp = ip_tstamps + hash % IP_IDENTS_SZ;
atomic_t *p_id = ip_idents + hash % IP_IDENTS_SZ;
u32 old = ACCESS_ONCE(*p_tstamp);
u32 now = (u32)jiffies;
u32 new, delta = 0;
if (old != now && cmpxchg(p_tstamp, old, now) == old)
delta = prandom_u32_max(now - old);
/* Do not use atomic_add_return() as it makes UBSAN unhappy */
do {
old = (u32)atomic_read(p_id);
new = old + delta + segs;
} while (atomic_cmpxchg(p_id, old, new) != old);
return new - segs;
}
EXPORT_SYMBOL(ip_idents_reserve);
void __ip_select_ident(struct net *net, struct iphdr *iph, int segs)
{
static u32 ip_idents_hashrnd __read_mostly;
u32 hash, id;
net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd));
hash = jhash_3words((__force u32)iph->daddr,
(__force u32)iph->saddr,
iph->protocol ^ net_hash_mix(net),
ip_idents_hashrnd);
id = ip_idents_reserve(hash, segs);
iph->id = htons(id);
}
EXPORT_SYMBOL(__ip_select_ident);
static void __build_flow_key(const struct net *net, struct flowi4 *fl4,
const struct sock *sk,
const struct iphdr *iph,
int oif, u8 tos,
u8 prot, u32 mark, int flow_flags)
{
if (sk) {
const struct inet_sock *inet = inet_sk(sk);
oif = sk->sk_bound_dev_if;
mark = sk->sk_mark;
tos = RT_CONN_FLAGS(sk);
prot = inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol;
}
flowi4_init_output(fl4, oif, mark, tos,
RT_SCOPE_UNIVERSE, prot,
flow_flags,
iph->daddr, iph->saddr, 0, 0,
sock_net_uid(net, sk));
}
static void build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb,
const struct sock *sk)
{
const struct net *net = dev_net(skb->dev);
const struct iphdr *iph = ip_hdr(skb);
int oif = skb->dev->ifindex;
u8 tos = RT_TOS(iph->tos);
u8 prot = iph->protocol;
u32 mark = skb->mark;
__build_flow_key(net, fl4, sk, iph, oif, tos, prot, mark, 0);
}
static void build_sk_flow_key(struct flowi4 *fl4, const struct sock *sk)
{
const struct inet_sock *inet = inet_sk(sk);
const struct ip_options_rcu *inet_opt;
__be32 daddr = inet->inet_daddr;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
flowi4_init_output(fl4, sk->sk_bound_dev_if, sk->sk_mark,
RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol,
inet_sk_flowi_flags(sk),
daddr, inet->inet_saddr, 0, 0, sk->sk_uid);
rcu_read_unlock();
}
static void ip_rt_build_flow_key(struct flowi4 *fl4, const struct sock *sk,
const struct sk_buff *skb)
{
if (skb)
build_skb_flow_key(fl4, skb, sk);
else
build_sk_flow_key(fl4, sk);
}
static DEFINE_SPINLOCK(fnhe_lock);
static void fnhe_flush_routes(struct fib_nh_exception *fnhe)
{
struct rtable *rt;
rt = rcu_dereference(fnhe->fnhe_rth_input);
if (rt) {
RCU_INIT_POINTER(fnhe->fnhe_rth_input, NULL);
dst_dev_put(&rt->dst);
dst_release(&rt->dst);
}
rt = rcu_dereference(fnhe->fnhe_rth_output);
if (rt) {
RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL);
dst_dev_put(&rt->dst);
dst_release(&rt->dst);
}
}
static struct fib_nh_exception *fnhe_oldest(struct fnhe_hash_bucket *hash)
{
struct fib_nh_exception *fnhe, *oldest;
oldest = rcu_dereference(hash->chain);
for (fnhe = rcu_dereference(oldest->fnhe_next); fnhe;
fnhe = rcu_dereference(fnhe->fnhe_next)) {
if (time_before(fnhe->fnhe_stamp, oldest->fnhe_stamp))
oldest = fnhe;
}
fnhe_flush_routes(oldest);
return oldest;
}
static inline u32 fnhe_hashfun(__be32 daddr)
{
static u32 fnhe_hashrnd __read_mostly;
u32 hval;
net_get_random_once(&fnhe_hashrnd, sizeof(fnhe_hashrnd));
hval = jhash_1word((__force u32) daddr, fnhe_hashrnd);
return hash_32(hval, FNHE_HASH_SHIFT);
}
static void fill_route_from_fnhe(struct rtable *rt, struct fib_nh_exception *fnhe)
{
rt->rt_pmtu = fnhe->fnhe_pmtu;
rt->dst.expires = fnhe->fnhe_expires;
if (fnhe->fnhe_gw) {
rt->rt_flags |= RTCF_REDIRECTED;
rt->rt_gateway = fnhe->fnhe_gw;
rt->rt_uses_gateway = 1;
}
}
static void update_or_create_fnhe(struct fib_nh *nh, __be32 daddr, __be32 gw,
u32 pmtu, unsigned long expires)
{
struct fnhe_hash_bucket *hash;
struct fib_nh_exception *fnhe;
struct rtable *rt;
unsigned int i;
int depth;
u32 hval = fnhe_hashfun(daddr);
spin_lock_bh(&fnhe_lock);
hash = rcu_dereference(nh->nh_exceptions);
if (!hash) {
hash = kzalloc(FNHE_HASH_SIZE * sizeof(*hash), GFP_ATOMIC);
if (!hash)
goto out_unlock;
rcu_assign_pointer(nh->nh_exceptions, hash);
}
hash += hval;
depth = 0;
for (fnhe = rcu_dereference(hash->chain); fnhe;
fnhe = rcu_dereference(fnhe->fnhe_next)) {
if (fnhe->fnhe_daddr == daddr)
break;
depth++;
}
if (fnhe) {
if (gw)
fnhe->fnhe_gw = gw;
if (pmtu) {
fnhe->fnhe_pmtu = pmtu;
fnhe->fnhe_expires = max(1UL, expires);
}
/* Update all cached dsts too */
rt = rcu_dereference(fnhe->fnhe_rth_input);
if (rt)
fill_route_from_fnhe(rt, fnhe);
rt = rcu_dereference(fnhe->fnhe_rth_output);
if (rt)
fill_route_from_fnhe(rt, fnhe);
} else {
if (depth > FNHE_RECLAIM_DEPTH)
fnhe = fnhe_oldest(hash);
else {
fnhe = kzalloc(sizeof(*fnhe), GFP_ATOMIC);
if (!fnhe)
goto out_unlock;
fnhe->fnhe_next = hash->chain;
rcu_assign_pointer(hash->chain, fnhe);
}
fnhe->fnhe_genid = fnhe_genid(dev_net(nh->nh_dev));
fnhe->fnhe_daddr = daddr;
fnhe->fnhe_gw = gw;
fnhe->fnhe_pmtu = pmtu;
fnhe->fnhe_expires = expires;
/* Exception created; mark the cached routes for the nexthop
* stale, so anyone caching it rechecks if this exception
* applies to them.
*/
rt = rcu_dereference(nh->nh_rth_input);
if (rt)
rt->dst.obsolete = DST_OBSOLETE_KILL;
for_each_possible_cpu(i) {
struct rtable __rcu **prt;
prt = per_cpu_ptr(nh->nh_pcpu_rth_output, i);
rt = rcu_dereference(*prt);
if (rt)
rt->dst.obsolete = DST_OBSOLETE_KILL;
}
}
fnhe->fnhe_stamp = jiffies;
out_unlock:
spin_unlock_bh(&fnhe_lock);
}
static void __ip_do_redirect(struct rtable *rt, struct sk_buff *skb, struct flowi4 *fl4,
bool kill_route)
{
__be32 new_gw = icmp_hdr(skb)->un.gateway;
__be32 old_gw = ip_hdr(skb)->saddr;
struct net_device *dev = skb->dev;
struct in_device *in_dev;
struct fib_result res;
struct neighbour *n;
struct net *net;
switch (icmp_hdr(skb)->code & 7) {
case ICMP_REDIR_NET:
case ICMP_REDIR_NETTOS:
case ICMP_REDIR_HOST:
case ICMP_REDIR_HOSTTOS:
break;
default:
return;
}
if (rt->rt_gateway != old_gw)
return;
in_dev = __in_dev_get_rcu(dev);
if (!in_dev)
return;
net = dev_net(dev);
if (new_gw == old_gw || !IN_DEV_RX_REDIRECTS(in_dev) ||
ipv4_is_multicast(new_gw) || ipv4_is_lbcast(new_gw) ||
ipv4_is_zeronet(new_gw))
goto reject_redirect;
if (!IN_DEV_SHARED_MEDIA(in_dev)) {
if (!inet_addr_onlink(in_dev, new_gw, old_gw))
goto reject_redirect;
if (IN_DEV_SEC_REDIRECTS(in_dev) && ip_fib_check_default(new_gw, dev))
goto reject_redirect;
} else {
if (inet_addr_type(net, new_gw) != RTN_UNICAST)
goto reject_redirect;
}
n = __ipv4_neigh_lookup(rt->dst.dev, new_gw);
if (!n)
n = neigh_create(&arp_tbl, &new_gw, rt->dst.dev);
if (!IS_ERR(n)) {
if (!(n->nud_state & NUD_VALID)) {
neigh_event_send(n, NULL);
} else {
if (fib_lookup(net, fl4, &res, 0) == 0) {
struct fib_nh *nh = &FIB_RES_NH(res);
update_or_create_fnhe(nh, fl4->daddr, new_gw,
0, jiffies + ip_rt_gc_timeout);
}
if (kill_route)
rt->dst.obsolete = DST_OBSOLETE_KILL;
call_netevent_notifiers(NETEVENT_NEIGH_UPDATE, n);
}
neigh_release(n);
}
return;
reject_redirect:
#ifdef CONFIG_IP_ROUTE_VERBOSE
if (IN_DEV_LOG_MARTIANS(in_dev)) {
const struct iphdr *iph = (const struct iphdr *) skb->data;
__be32 daddr = iph->daddr;
__be32 saddr = iph->saddr;
net_info_ratelimited("Redirect from %pI4 on %s about %pI4 ignored\n"
" Advised path = %pI4 -> %pI4\n",
&old_gw, dev->name, &new_gw,
&saddr, &daddr);
}
#endif
;
}
static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb)
{
struct rtable *rt;
struct flowi4 fl4;
const struct iphdr *iph = (const struct iphdr *) skb->data;
struct net *net = dev_net(skb->dev);
int oif = skb->dev->ifindex;
u8 tos = RT_TOS(iph->tos);
u8 prot = iph->protocol;
u32 mark = skb->mark;
rt = (struct rtable *) dst;
__build_flow_key(net, &fl4, sk, iph, oif, tos, prot, mark, 0);
__ip_do_redirect(rt, skb, &fl4, true);
}
static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst)
{
struct rtable *rt = (struct rtable *)dst;
struct dst_entry *ret = dst;
if (rt) {
if (dst->obsolete > 0) {
ip_rt_put(rt);
ret = NULL;
} else if ((rt->rt_flags & RTCF_REDIRECTED) ||
rt->dst.expires) {
ip_rt_put(rt);
ret = NULL;
}
}
return ret;
}
/*
* Algorithm:
* 1. The first ip_rt_redirect_number redirects are sent
* with exponential backoff, then we stop sending them at all,
* assuming that the host ignores our redirects.
* 2. If we did not see packets requiring redirects
* during ip_rt_redirect_silence, we assume that the host
* forgot redirected route and start to send redirects again.
*
* This algorithm is much cheaper and more intelligent than dumb load limiting
* in icmp.c.
*
* NOTE. Do not forget to inhibit load limiting for redirects (redundant)
* and "frag. need" (breaks PMTU discovery) in icmp.c.
*/
void ip_rt_send_redirect(struct sk_buff *skb)
{
struct rtable *rt = skb_rtable(skb);
struct in_device *in_dev;
struct inet_peer *peer;
struct net *net;
int log_martians;
int vif;
rcu_read_lock();
in_dev = __in_dev_get_rcu(rt->dst.dev);
if (!in_dev || !IN_DEV_TX_REDIRECTS(in_dev)) {
rcu_read_unlock();
return;
}
log_martians = IN_DEV_LOG_MARTIANS(in_dev);
vif = l3mdev_master_ifindex_rcu(rt->dst.dev);
rcu_read_unlock();
net = dev_net(rt->dst.dev);
peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, vif, 1);
if (!peer) {
icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST,
rt_nexthop(rt, ip_hdr(skb)->daddr));
return;
}
/* No redirected packets during ip_rt_redirect_silence;
* reset the algorithm.
*/
if (time_after(jiffies, peer->rate_last + ip_rt_redirect_silence))
peer->rate_tokens = 0;
/* Too many ignored redirects; do not send anything
* set dst.rate_last to the last seen redirected packet.
*/
if (peer->rate_tokens >= ip_rt_redirect_number) {
peer->rate_last = jiffies;
goto out_put_peer;
}
/* Check for load limit; set rate_last to the latest sent
* redirect.
*/
if (peer->rate_tokens == 0 ||
time_after(jiffies,
(peer->rate_last +
(ip_rt_redirect_load << peer->rate_tokens)))) {
__be32 gw = rt_nexthop(rt, ip_hdr(skb)->daddr);
icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, gw);
peer->rate_last = jiffies;
++peer->rate_tokens;
#ifdef CONFIG_IP_ROUTE_VERBOSE
if (log_martians &&
peer->rate_tokens == ip_rt_redirect_number)
net_warn_ratelimited("host %pI4/if%d ignores redirects for %pI4 to %pI4\n",
&ip_hdr(skb)->saddr, inet_iif(skb),
&ip_hdr(skb)->daddr, &gw);
#endif
}
out_put_peer:
inet_putpeer(peer);
}
static int ip_error(struct sk_buff *skb)
{
struct in_device *in_dev = __in_dev_get_rcu(skb->dev);
struct rtable *rt = skb_rtable(skb);
struct inet_peer *peer;
unsigned long now;
struct net *net;
bool send;
int code;
/* IP on this device is disabled. */
if (!in_dev)
goto out;
net = dev_net(rt->dst.dev);
if (!IN_DEV_FORWARD(in_dev)) {
switch (rt->dst.error) {
case EHOSTUNREACH:
__IP_INC_STATS(net, IPSTATS_MIB_INADDRERRORS);
break;
case ENETUNREACH:
__IP_INC_STATS(net, IPSTATS_MIB_INNOROUTES);
break;
}
goto out;
}
switch (rt->dst.error) {
case EINVAL:
default:
goto out;
case EHOSTUNREACH:
code = ICMP_HOST_UNREACH;
break;
case ENETUNREACH:
code = ICMP_NET_UNREACH;
__IP_INC_STATS(net, IPSTATS_MIB_INNOROUTES);
break;
case EACCES:
code = ICMP_PKT_FILTERED;
break;
}
peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr,
l3mdev_master_ifindex(skb->dev), 1);
send = true;
if (peer) {
now = jiffies;
peer->rate_tokens += now - peer->rate_last;
if (peer->rate_tokens > ip_rt_error_burst)
peer->rate_tokens = ip_rt_error_burst;
peer->rate_last = now;
if (peer->rate_tokens >= ip_rt_error_cost)
peer->rate_tokens -= ip_rt_error_cost;
else
send = false;
inet_putpeer(peer);
}
if (send)
icmp_send(skb, ICMP_DEST_UNREACH, code, 0);
out: kfree_skb(skb);
return 0;
}
static void __ip_rt_update_pmtu(struct rtable *rt, struct flowi4 *fl4, u32 mtu)
{
struct dst_entry *dst = &rt->dst;
struct fib_result res;
if (dst_metric_locked(dst, RTAX_MTU))
return;
if (ipv4_mtu(dst) < mtu)
return;
if (mtu < ip_rt_min_pmtu)
mtu = ip_rt_min_pmtu;
if (rt->rt_pmtu == mtu &&
time_before(jiffies, dst->expires - ip_rt_mtu_expires / 2))
return;
rcu_read_lock();
if (fib_lookup(dev_net(dst->dev), fl4, &res, 0) == 0) {
struct fib_nh *nh = &FIB_RES_NH(res);
update_or_create_fnhe(nh, fl4->daddr, 0, mtu,
jiffies + ip_rt_mtu_expires);
}
rcu_read_unlock();
}
static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu)
{
struct rtable *rt = (struct rtable *) dst;
struct flowi4 fl4;
ip_rt_build_flow_key(&fl4, sk, skb);
__ip_rt_update_pmtu(rt, &fl4, mtu);
}
void ipv4_update_pmtu(struct sk_buff *skb, struct net *net, u32 mtu,
int oif, u32 mark, u8 protocol, int flow_flags)
{
const struct iphdr *iph = (const struct iphdr *) skb->data;
struct flowi4 fl4;
struct rtable *rt;
if (!mark)
mark = IP4_REPLY_MARK(net, skb->mark);
__build_flow_key(net, &fl4, NULL, iph, oif,
RT_TOS(iph->tos), protocol, mark, flow_flags);
rt = __ip_route_output_key(net, &fl4);
if (!IS_ERR(rt)) {
__ip_rt_update_pmtu(rt, &fl4, mtu);
ip_rt_put(rt);
}
}
EXPORT_SYMBOL_GPL(ipv4_update_pmtu);
static void __ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu)
{
const struct iphdr *iph = (const struct iphdr *) skb->data;
struct flowi4 fl4;
struct rtable *rt;
__build_flow_key(sock_net(sk), &fl4, sk, iph, 0, 0, 0, 0, 0);
if (!fl4.flowi4_mark)
fl4.flowi4_mark = IP4_REPLY_MARK(sock_net(sk), skb->mark);
rt = __ip_route_output_key(sock_net(sk), &fl4);
if (!IS_ERR(rt)) {
__ip_rt_update_pmtu(rt, &fl4, mtu);
ip_rt_put(rt);
}
}
void ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu)
{
const struct iphdr *iph = (const struct iphdr *) skb->data;
struct flowi4 fl4;
struct rtable *rt;
struct dst_entry *odst = NULL;
bool new = false;
struct net *net = sock_net(sk);
bh_lock_sock(sk);
if (!ip_sk_accept_pmtu(sk))
goto out;
odst = sk_dst_get(sk);
if (sock_owned_by_user(sk) || !odst) {
__ipv4_sk_update_pmtu(skb, sk, mtu);
goto out;
}
__build_flow_key(net, &fl4, sk, iph, 0, 0, 0, 0, 0);
rt = (struct rtable *)odst;
if (odst->obsolete && !odst->ops->check(odst, 0)) {
rt = ip_route_output_flow(sock_net(sk), &fl4, sk);
if (IS_ERR(rt))
goto out;
new = true;
}
__ip_rt_update_pmtu((struct rtable *) rt->dst.path, &fl4, mtu);
if (!dst_check(&rt->dst, 0)) {
if (new)
dst_release(&rt->dst);
rt = ip_route_output_flow(sock_net(sk), &fl4, sk);
if (IS_ERR(rt))
goto out;
new = true;
}
if (new)
sk_dst_set(sk, &rt->dst);
out:
bh_unlock_sock(sk);
dst_release(odst);
}
EXPORT_SYMBOL_GPL(ipv4_sk_update_pmtu);
void ipv4_redirect(struct sk_buff *skb, struct net *net,
int oif, u32 mark, u8 protocol, int flow_flags)
{
const struct iphdr *iph = (const struct iphdr *) skb->data;
struct flowi4 fl4;
struct rtable *rt;
__build_flow_key(net, &fl4, NULL, iph, oif,
RT_TOS(iph->tos), protocol, mark, flow_flags);
rt = __ip_route_output_key(net, &fl4);
if (!IS_ERR(rt)) {
__ip_do_redirect(rt, skb, &fl4, false);
ip_rt_put(rt);
}
}
EXPORT_SYMBOL_GPL(ipv4_redirect);
void ipv4_sk_redirect(struct sk_buff *skb, struct sock *sk)
{
const struct iphdr *iph = (const struct iphdr *) skb->data;
struct flowi4 fl4;
struct rtable *rt;
struct net *net = sock_net(sk);
__build_flow_key(net, &fl4, sk, iph, 0, 0, 0, 0, 0);
rt = __ip_route_output_key(net, &fl4);
if (!IS_ERR(rt)) {
__ip_do_redirect(rt, skb, &fl4, false);
ip_rt_put(rt);
}
}
EXPORT_SYMBOL_GPL(ipv4_sk_redirect);
static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie)
{
struct rtable *rt = (struct rtable *) dst;
/* All IPV4 dsts are created with ->obsolete set to the value
* DST_OBSOLETE_FORCE_CHK which forces validation calls down
* into this function always.
*
* When a PMTU/redirect information update invalidates a route,
* this is indicated by setting obsolete to DST_OBSOLETE_KILL or
* DST_OBSOLETE_DEAD by dst_free().
*/
if (dst->obsolete != DST_OBSOLETE_FORCE_CHK || rt_is_expired(rt))
return NULL;
return dst;
}
static void ipv4_link_failure(struct sk_buff *skb)
{
struct rtable *rt;
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0);
rt = skb_rtable(skb);
if (rt)
dst_set_expires(&rt->dst, 0);
}
static int ip_rt_bug(struct net *net, struct sock *sk, struct sk_buff *skb)
{
pr_debug("%s: %pI4 -> %pI4, %s\n",
__func__, &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr,
skb->dev ? skb->dev->name : "?");
kfree_skb(skb);
WARN_ON(1);
return 0;
}
/*
We do not cache source address of outgoing interface,
because it is used only by IP RR, TS and SRR options,
so that it out of fast path.
BTW remember: "addr" is allowed to be not aligned
in IP options!
*/
void ip_rt_get_source(u8 *addr, struct sk_buff *skb, struct rtable *rt)
{
__be32 src;
if (rt_is_output_route(rt))
src = ip_hdr(skb)->saddr;
else {
struct fib_result res;
struct flowi4 fl4;
struct iphdr *iph;
iph = ip_hdr(skb);
memset(&fl4, 0, sizeof(fl4));
fl4.daddr = iph->daddr;
fl4.saddr = iph->saddr;
fl4.flowi4_tos = RT_TOS(iph->tos);
fl4.flowi4_oif = rt->dst.dev->ifindex;
fl4.flowi4_iif = skb->dev->ifindex;
fl4.flowi4_mark = skb->mark;
rcu_read_lock();
if (fib_lookup(dev_net(rt->dst.dev), &fl4, &res, 0) == 0)
src = FIB_RES_PREFSRC(dev_net(rt->dst.dev), res);
else
src = inet_select_addr(rt->dst.dev,
rt_nexthop(rt, iph->daddr),
RT_SCOPE_UNIVERSE);
rcu_read_unlock();
}
memcpy(addr, &src, 4);
}
#ifdef CONFIG_IP_ROUTE_CLASSID
static void set_class_tag(struct rtable *rt, u32 tag)
{
if (!(rt->dst.tclassid & 0xFFFF))
rt->dst.tclassid |= tag & 0xFFFF;
if (!(rt->dst.tclassid & 0xFFFF0000))
rt->dst.tclassid |= tag & 0xFFFF0000;
}
#endif
static unsigned int ipv4_default_advmss(const struct dst_entry *dst)
{
unsigned int header_size = sizeof(struct tcphdr) + sizeof(struct iphdr);
unsigned int advmss = max_t(unsigned int, dst->dev->mtu - header_size,
ip_rt_min_advmss);
return min(advmss, IPV4_MAX_PMTU - header_size);
}
static unsigned int ipv4_mtu(const struct dst_entry *dst)
{
const struct rtable *rt = (const struct rtable *) dst;
unsigned int mtu = rt->rt_pmtu;
if (!mtu || time_after_eq(jiffies, rt->dst.expires))
mtu = dst_metric_raw(dst, RTAX_MTU);
if (mtu)
return mtu;
mtu = READ_ONCE(dst->dev->mtu);
if (unlikely(dst_metric_locked(dst, RTAX_MTU))) {
if (rt->rt_uses_gateway && mtu > 576)
mtu = 576;
}
mtu = min_t(unsigned int, mtu, IP_MAX_MTU);
return mtu - lwtunnel_headroom(dst->lwtstate, mtu);
}
static struct fib_nh_exception *find_exception(struct fib_nh *nh, __be32 daddr)
{
struct fnhe_hash_bucket *hash = rcu_dereference(nh->nh_exceptions);
struct fib_nh_exception *fnhe;
u32 hval;
if (!hash)
return NULL;
hval = fnhe_hashfun(daddr);
for (fnhe = rcu_dereference(hash[hval].chain); fnhe;
fnhe = rcu_dereference(fnhe->fnhe_next)) {
if (fnhe->fnhe_daddr == daddr)
return fnhe;
}
return NULL;
}
static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe,
__be32 daddr, const bool do_cache)
{
bool ret = false;
spin_lock_bh(&fnhe_lock);
if (daddr == fnhe->fnhe_daddr) {
struct rtable __rcu **porig;
struct rtable *orig;
int genid = fnhe_genid(dev_net(rt->dst.dev));
if (rt_is_input_route(rt))
porig = &fnhe->fnhe_rth_input;
else
porig = &fnhe->fnhe_rth_output;
orig = rcu_dereference(*porig);
if (fnhe->fnhe_genid != genid) {
fnhe->fnhe_genid = genid;
fnhe->fnhe_gw = 0;
fnhe->fnhe_pmtu = 0;
fnhe->fnhe_expires = 0;
fnhe_flush_routes(fnhe);
orig = NULL;
}
fill_route_from_fnhe(rt, fnhe);
if (!rt->rt_gateway)
rt->rt_gateway = daddr;
if (do_cache) {
dst_hold(&rt->dst);
rcu_assign_pointer(*porig, rt);
if (orig) {
dst_dev_put(&orig->dst);
dst_release(&orig->dst);
}
ret = true;
}
fnhe->fnhe_stamp = jiffies;
}
spin_unlock_bh(&fnhe_lock);
return ret;
}
static bool rt_cache_route(struct fib_nh *nh, struct rtable *rt)
{
struct rtable *orig, *prev, **p;
bool ret = true;
if (rt_is_input_route(rt)) {
p = (struct rtable **)&nh->nh_rth_input;
} else {
p = (struct rtable **)raw_cpu_ptr(nh->nh_pcpu_rth_output);
}
orig = *p;
/* hold dst before doing cmpxchg() to avoid race condition
* on this dst
*/
dst_hold(&rt->dst);
prev = cmpxchg(p, orig, rt);
if (prev == orig) {
if (orig) {
dst_dev_put(&orig->dst);
dst_release(&orig->dst);
}
} else {
dst_release(&rt->dst);
ret = false;
}
return ret;
}
struct uncached_list {
spinlock_t lock;
struct list_head head;
};
static DEFINE_PER_CPU_ALIGNED(struct uncached_list, rt_uncached_list);
static void rt_add_uncached_list(struct rtable *rt)
{
struct uncached_list *ul = raw_cpu_ptr(&rt_uncached_list);
rt->rt_uncached_list = ul;
spin_lock_bh(&ul->lock);
list_add_tail(&rt->rt_uncached, &ul->head);
spin_unlock_bh(&ul->lock);
}
static void ipv4_dst_destroy(struct dst_entry *dst)
{
struct dst_metrics *p = (struct dst_metrics *)DST_METRICS_PTR(dst);
struct rtable *rt = (struct rtable *) dst;
if (p != &dst_default_metrics && atomic_dec_and_test(&p->refcnt))
kfree(p);
if (!list_empty(&rt->rt_uncached)) {
struct uncached_list *ul = rt->rt_uncached_list;
spin_lock_bh(&ul->lock);
list_del(&rt->rt_uncached);
spin_unlock_bh(&ul->lock);
}
}
void rt_flush_dev(struct net_device *dev)
{
struct net *net = dev_net(dev);
struct rtable *rt;
int cpu;
for_each_possible_cpu(cpu) {
struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu);
spin_lock_bh(&ul->lock);
list_for_each_entry(rt, &ul->head, rt_uncached) {
if (rt->dst.dev != dev)
continue;
rt->dst.dev = net->loopback_dev;
dev_hold(rt->dst.dev);
dev_put(dev);
}
spin_unlock_bh(&ul->lock);
}
}
static bool rt_cache_valid(const struct rtable *rt)
{
return rt &&
rt->dst.obsolete == DST_OBSOLETE_FORCE_CHK &&
!rt_is_expired(rt);
}
static void rt_set_nexthop(struct rtable *rt, __be32 daddr,
const struct fib_result *res,
struct fib_nh_exception *fnhe,
struct fib_info *fi, u16 type, u32 itag,
const bool do_cache)
{
bool cached = false;
if (fi) {
struct fib_nh *nh = &FIB_RES_NH(*res);
if (nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK) {
rt->rt_gateway = nh->nh_gw;
rt->rt_uses_gateway = 1;
}
dst_init_metrics(&rt->dst, fi->fib_metrics->metrics, true);
if (fi->fib_metrics != &dst_default_metrics) {
rt->dst._metrics |= DST_METRICS_REFCOUNTED;
atomic_inc(&fi->fib_metrics->refcnt);
}
#ifdef CONFIG_IP_ROUTE_CLASSID
rt->dst.tclassid = nh->nh_tclassid;
#endif
rt->dst.lwtstate = lwtstate_get(nh->nh_lwtstate);
if (unlikely(fnhe))
cached = rt_bind_exception(rt, fnhe, daddr, do_cache);
else if (do_cache)
cached = rt_cache_route(nh, rt);
if (unlikely(!cached)) {
/* Routes we intend to cache in nexthop exception or
* FIB nexthop have the DST_NOCACHE bit clear.
* However, if we are unsuccessful at storing this
* route into the cache we really need to set it.
*/
if (!rt->rt_gateway)
rt->rt_gateway = daddr;
rt_add_uncached_list(rt);
}
} else
rt_add_uncached_list(rt);
#ifdef CONFIG_IP_ROUTE_CLASSID
#ifdef CONFIG_IP_MULTIPLE_TABLES
set_class_tag(rt, res->tclassid);
#endif
set_class_tag(rt, itag);
#endif
}
struct rtable *rt_dst_alloc(struct net_device *dev,
unsigned int flags, u16 type,
bool nopolicy, bool noxfrm, bool will_cache)
{
struct rtable *rt;
rt = dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK,
(will_cache ? 0 : DST_HOST) |
(nopolicy ? DST_NOPOLICY : 0) |
(noxfrm ? DST_NOXFRM : 0));
if (rt) {
rt->rt_genid = rt_genid_ipv4(dev_net(dev));
rt->rt_flags = flags;
rt->rt_type = type;
rt->rt_is_input = 0;
rt->rt_iif = 0;
rt->rt_pmtu = 0;
rt->rt_gateway = 0;
rt->rt_uses_gateway = 0;
rt->rt_table_id = 0;
INIT_LIST_HEAD(&rt->rt_uncached);
rt->dst.output = ip_output;
if (flags & RTCF_LOCAL)
rt->dst.input = ip_local_deliver;
}
return rt;
}
EXPORT_SYMBOL(rt_dst_alloc);
/* called in rcu_read_lock() section */
static int ip_route_input_mc(struct sk_buff *skb, __be32 daddr, __be32 saddr,
u8 tos, struct net_device *dev, int our)
{
struct rtable *rth;
struct in_device *in_dev = __in_dev_get_rcu(dev);
unsigned int flags = RTCF_MULTICAST;
u32 itag = 0;
int err;
/* Primary sanity checks. */
if (!in_dev)
return -EINVAL;
if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) ||
skb->protocol != htons(ETH_P_IP))
goto e_inval;
if (ipv4_is_loopback(saddr) && !IN_DEV_ROUTE_LOCALNET(in_dev))
goto e_inval;
if (ipv4_is_zeronet(saddr)) {
if (!ipv4_is_local_multicast(daddr))
goto e_inval;
} else {
err = fib_validate_source(skb, saddr, 0, tos, 0, dev,
in_dev, &itag);
if (err < 0)
goto e_err;
}
if (our)
flags |= RTCF_LOCAL;
rth = rt_dst_alloc(dev_net(dev)->loopback_dev, flags, RTN_MULTICAST,
IN_DEV_CONF_GET(in_dev, NOPOLICY), false, false);
if (!rth)
goto e_nobufs;
#ifdef CONFIG_IP_ROUTE_CLASSID
rth->dst.tclassid = itag;
#endif
rth->dst.output = ip_rt_bug;
rth->rt_is_input= 1;
#ifdef CONFIG_IP_MROUTE
if (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev))
rth->dst.input = ip_mr_input;
#endif
RT_CACHE_STAT_INC(in_slow_mc);
skb_dst_set(skb, &rth->dst);
return 0;
e_nobufs:
return -ENOBUFS;
e_inval:
return -EINVAL;
e_err:
return err;
}
static void ip_handle_martian_source(struct net_device *dev,
struct in_device *in_dev,
struct sk_buff *skb,
__be32 daddr,
__be32 saddr)
{
RT_CACHE_STAT_INC(in_martian_src);
#ifdef CONFIG_IP_ROUTE_VERBOSE
if (IN_DEV_LOG_MARTIANS(in_dev) && net_ratelimit()) {
/*
* RFC1812 recommendation, if source is martian,
* the only hint is MAC header.
*/
pr_warn("martian source %pI4 from %pI4, on dev %s\n",
&daddr, &saddr, dev->name);
if (dev->hard_header_len && skb_mac_header_was_set(skb)) {
print_hex_dump(KERN_WARNING, "ll header: ",
DUMP_PREFIX_OFFSET, 16, 1,
skb_mac_header(skb),
dev->hard_header_len, true);
}
}
#endif
}
static void ip_del_fnhe(struct fib_nh *nh, __be32 daddr)
{
struct fnhe_hash_bucket *hash;
struct fib_nh_exception *fnhe, __rcu **fnhe_p;
u32 hval = fnhe_hashfun(daddr);
spin_lock_bh(&fnhe_lock);
hash = rcu_dereference_protected(nh->nh_exceptions,
lockdep_is_held(&fnhe_lock));
hash += hval;
fnhe_p = &hash->chain;
fnhe = rcu_dereference_protected(*fnhe_p, lockdep_is_held(&fnhe_lock));
while (fnhe) {
if (fnhe->fnhe_daddr == daddr) {
rcu_assign_pointer(*fnhe_p, rcu_dereference_protected(
fnhe->fnhe_next, lockdep_is_held(&fnhe_lock)));
fnhe_flush_routes(fnhe);
kfree_rcu(fnhe, rcu);
break;
}
fnhe_p = &fnhe->fnhe_next;
fnhe = rcu_dereference_protected(fnhe->fnhe_next,
lockdep_is_held(&fnhe_lock));
}
spin_unlock_bh(&fnhe_lock);
}
static void set_lwt_redirect(struct rtable *rth)
{
if (lwtunnel_output_redirect(rth->dst.lwtstate)) {
rth->dst.lwtstate->orig_output = rth->dst.output;
rth->dst.output = lwtunnel_output;
}
if (lwtunnel_input_redirect(rth->dst.lwtstate)) {
rth->dst.lwtstate->orig_input = rth->dst.input;
rth->dst.input = lwtunnel_input;
}
}
/* called in rcu_read_lock() section */
static int __mkroute_input(struct sk_buff *skb,
const struct fib_result *res,
struct in_device *in_dev,
__be32 daddr, __be32 saddr, u32 tos)
{
struct fib_nh_exception *fnhe;
struct rtable *rth;
int err;
struct in_device *out_dev;
bool do_cache;
u32 itag = 0;
/* get a working reference to the output device */
out_dev = __in_dev_get_rcu(FIB_RES_DEV(*res));
if (!out_dev) {
net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n");
return -EINVAL;
}
err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res),
in_dev->dev, in_dev, &itag);
if (err < 0) {
ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr,
saddr);
goto cleanup;
}
do_cache = res->fi && !itag;
if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) &&
skb->protocol == htons(ETH_P_IP) &&
(IN_DEV_SHARED_MEDIA(out_dev) ||
inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res))))
IPCB(skb)->flags |= IPSKB_DOREDIRECT;
if (skb->protocol != htons(ETH_P_IP)) {
/* Not IP (i.e. ARP). Do not create route, if it is
* invalid for proxy arp. DNAT routes are always valid.
*
* Proxy arp feature have been extended to allow, ARP
* replies back to the same interface, to support
* Private VLAN switch technologies. See arp.c.
*/
if (out_dev == in_dev &&
IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) {
err = -EINVAL;
goto cleanup;
}
}
fnhe = find_exception(&FIB_RES_NH(*res), daddr);
if (do_cache) {
if (fnhe) {
rth = rcu_dereference(fnhe->fnhe_rth_input);
if (rth && rth->dst.expires &&
time_after(jiffies, rth->dst.expires)) {
ip_del_fnhe(&FIB_RES_NH(*res), daddr);
fnhe = NULL;
} else {
goto rt_cache;
}
}
rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input);
rt_cache:
if (rt_cache_valid(rth)) {
skb_dst_set_noref(skb, &rth->dst);
goto out;
}
}
rth = rt_dst_alloc(out_dev->dev, 0, res->type,
IN_DEV_CONF_GET(in_dev, NOPOLICY),
IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache);
if (!rth) {
err = -ENOBUFS;
goto cleanup;
}
rth->rt_is_input = 1;
if (res->table)
rth->rt_table_id = res->table->tb_id;
RT_CACHE_STAT_INC(in_slow_tot);
rth->dst.input = ip_forward;
rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag,
do_cache);
set_lwt_redirect(rth);
skb_dst_set(skb, &rth->dst);
out:
err = 0;
cleanup:
return err;
}
#ifdef CONFIG_IP_ROUTE_MULTIPATH
/* To make ICMP packets follow the right flow, the multipath hash is
* calculated from the inner IP addresses.
*/
static void ip_multipath_l3_keys(const struct sk_buff *skb,
struct flow_keys *hash_keys)
{
const struct iphdr *outer_iph = ip_hdr(skb);
const struct iphdr *inner_iph;
const struct icmphdr *icmph;
struct iphdr _inner_iph;
struct icmphdr _icmph;
hash_keys->addrs.v4addrs.src = outer_iph->saddr;
hash_keys->addrs.v4addrs.dst = outer_iph->daddr;
if (likely(outer_iph->protocol != IPPROTO_ICMP))
return;
if (unlikely((outer_iph->frag_off & htons(IP_OFFSET)) != 0))
return;
icmph = skb_header_pointer(skb, outer_iph->ihl * 4, sizeof(_icmph),
&_icmph);
if (!icmph)
return;
if (icmph->type != ICMP_DEST_UNREACH &&
icmph->type != ICMP_REDIRECT &&
icmph->type != ICMP_TIME_EXCEEDED &&
icmph->type != ICMP_PARAMETERPROB)
return;
inner_iph = skb_header_pointer(skb,
outer_iph->ihl * 4 + sizeof(_icmph),
sizeof(_inner_iph), &_inner_iph);
if (!inner_iph)
return;
hash_keys->addrs.v4addrs.src = inner_iph->saddr;
hash_keys->addrs.v4addrs.dst = inner_iph->daddr;
}
/* if skb is set it will be used and fl4 can be NULL */
int fib_multipath_hash(const struct fib_info *fi, const struct flowi4 *fl4,
const struct sk_buff *skb)
{
struct net *net = fi->fib_net;
struct flow_keys hash_keys;
u32 mhash;
switch (net->ipv4.sysctl_fib_multipath_hash_policy) {
case 0:
memset(&hash_keys, 0, sizeof(hash_keys));
hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
if (skb) {
ip_multipath_l3_keys(skb, &hash_keys);
} else {
hash_keys.addrs.v4addrs.src = fl4->saddr;
hash_keys.addrs.v4addrs.dst = fl4->daddr;
}
break;
case 1:
/* skb is currently provided only when forwarding */
if (skb) {
unsigned int flag = FLOW_DISSECTOR_F_STOP_AT_ENCAP;
struct flow_keys keys;
/* short-circuit if we already have L4 hash present */
if (skb->l4_hash)
return skb_get_hash_raw(skb) >> 1;
memset(&hash_keys, 0, sizeof(hash_keys));
skb_flow_dissect_flow_keys(skb, &keys, flag);
hash_keys.addrs.v4addrs.src = keys.addrs.v4addrs.src;
hash_keys.addrs.v4addrs.dst = keys.addrs.v4addrs.dst;
hash_keys.ports.src = keys.ports.src;
hash_keys.ports.dst = keys.ports.dst;
hash_keys.basic.ip_proto = keys.basic.ip_proto;
} else {
memset(&hash_keys, 0, sizeof(hash_keys));
hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
hash_keys.addrs.v4addrs.src = fl4->saddr;
hash_keys.addrs.v4addrs.dst = fl4->daddr;
hash_keys.ports.src = fl4->fl4_sport;
hash_keys.ports.dst = fl4->fl4_dport;
hash_keys.basic.ip_proto = fl4->flowi4_proto;
}
break;
}
mhash = flow_hash_from_keys(&hash_keys);
return mhash >> 1;
}
EXPORT_SYMBOL_GPL(fib_multipath_hash);
#endif /* CONFIG_IP_ROUTE_MULTIPATH */
static int ip_mkroute_input(struct sk_buff *skb,
struct fib_result *res,
struct in_device *in_dev,
__be32 daddr, __be32 saddr, u32 tos)
{
#ifdef CONFIG_IP_ROUTE_MULTIPATH
if (res->fi && res->fi->fib_nhs > 1) {
int h = fib_multipath_hash(res->fi, NULL, skb);
fib_select_multipath(res, h);
}
#endif
/* create a routing cache entry */
return __mkroute_input(skb, res, in_dev, daddr, saddr, tos);
}
/*
* NOTE. We drop all the packets that has local source
* addresses, because every properly looped back packet
* must have correct destination already attached by output routine.
*
* Such approach solves two big problems:
* 1. Not simplex devices are handled properly.
* 2. IP spoofing attempts are filtered with 100% of guarantee.
* called with rcu_read_lock()
*/
static int ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr,
u8 tos, struct net_device *dev,
struct fib_result *res)
{
struct in_device *in_dev = __in_dev_get_rcu(dev);
struct ip_tunnel_info *tun_info;
struct flowi4 fl4;
unsigned int flags = 0;
u32 itag = 0;
struct rtable *rth;
int err = -EINVAL;
struct net *net = dev_net(dev);
bool do_cache;
/* IP on this device is disabled. */
if (!in_dev)
goto out;
/* Check for the most weird martians, which can be not detected
by fib_lookup.
*/
tun_info = skb_tunnel_info(skb);
if (tun_info && !(tun_info->mode & IP_TUNNEL_INFO_TX))
fl4.flowi4_tun_key.tun_id = tun_info->key.tun_id;
else
fl4.flowi4_tun_key.tun_id = 0;
skb_dst_drop(skb);
if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr))
goto martian_source;
res->fi = NULL;
res->table = NULL;
if (ipv4_is_lbcast(daddr) || (saddr == 0 && daddr == 0))
goto brd_input;
/* Accept zero addresses only to limited broadcast;
* I even do not know to fix it or not. Waiting for complains :-)
*/
if (ipv4_is_zeronet(saddr))
goto martian_source;
if (ipv4_is_zeronet(daddr))
goto martian_destination;
/* Following code try to avoid calling IN_DEV_NET_ROUTE_LOCALNET(),
* and call it once if daddr or/and saddr are loopback addresses
*/
if (ipv4_is_loopback(daddr)) {
if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net))
goto martian_destination;
} else if (ipv4_is_loopback(saddr)) {
if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net))
goto martian_source;
}
/*
* Now we are ready to route packet.
*/
fl4.flowi4_oif = 0;
fl4.flowi4_iif = dev->ifindex;
fl4.flowi4_mark = skb->mark;
fl4.flowi4_tos = tos;
fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
fl4.flowi4_flags = 0;
fl4.daddr = daddr;
fl4.saddr = saddr;
fl4.flowi4_uid = sock_net_uid(net, NULL);
err = fib_lookup(net, &fl4, res, 0);
if (err != 0) {
if (!IN_DEV_FORWARD(in_dev))
err = -EHOSTUNREACH;
goto no_route;
}
if (res->type == RTN_BROADCAST)
goto brd_input;
if (res->type == RTN_LOCAL) {
err = fib_validate_source(skb, saddr, daddr, tos,
0, dev, in_dev, &itag);
if (err < 0)
goto martian_source;
goto local_input;
}
if (!IN_DEV_FORWARD(in_dev)) {
err = -EHOSTUNREACH;
goto no_route;
}
if (res->type != RTN_UNICAST)
goto martian_destination;
err = ip_mkroute_input(skb, res, in_dev, daddr, saddr, tos);
out: return err;
brd_input:
if (skb->protocol != htons(ETH_P_IP))
goto e_inval;
if (!ipv4_is_zeronet(saddr)) {
err = fib_validate_source(skb, saddr, 0, tos, 0, dev,
in_dev, &itag);
if (err < 0)
goto martian_source;
}
flags |= RTCF_BROADCAST;
res->type = RTN_BROADCAST;
RT_CACHE_STAT_INC(in_brd);
local_input:
do_cache = false;
if (res->fi) {
if (!itag) {
rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input);
if (rt_cache_valid(rth)) {
skb_dst_set_noref(skb, &rth->dst);
err = 0;
goto out;
}
do_cache = true;
}
}
rth = rt_dst_alloc(l3mdev_master_dev_rcu(dev) ? : net->loopback_dev,
flags | RTCF_LOCAL, res->type,
IN_DEV_CONF_GET(in_dev, NOPOLICY), false, do_cache);
if (!rth)
goto e_nobufs;
rth->dst.output= ip_rt_bug;
#ifdef CONFIG_IP_ROUTE_CLASSID
rth->dst.tclassid = itag;
#endif
rth->rt_is_input = 1;
if (res->table)
rth->rt_table_id = res->table->tb_id;
RT_CACHE_STAT_INC(in_slow_tot);
if (res->type == RTN_UNREACHABLE) {
rth->dst.input= ip_error;
rth->dst.error= -err;
rth->rt_flags &= ~RTCF_LOCAL;
}
if (do_cache) {
struct fib_nh *nh = &FIB_RES_NH(*res);
rth->dst.lwtstate = lwtstate_get(nh->nh_lwtstate);
if (lwtunnel_input_redirect(rth->dst.lwtstate)) {
WARN_ON(rth->dst.input == lwtunnel_input);
rth->dst.lwtstate->orig_input = rth->dst.input;
rth->dst.input = lwtunnel_input;
}
if (unlikely(!rt_cache_route(nh, rth)))
rt_add_uncached_list(rth);
}
skb_dst_set(skb, &rth->dst);
err = 0;
goto out;
no_route:
RT_CACHE_STAT_INC(in_no_route);
res->type = RTN_UNREACHABLE;
res->fi = NULL;
res->table = NULL;
goto local_input;
/*
* Do not cache martian addresses: they should be logged (RFC1812)
*/
martian_destination:
RT_CACHE_STAT_INC(in_martian_dst);
#ifdef CONFIG_IP_ROUTE_VERBOSE
if (IN_DEV_LOG_MARTIANS(in_dev))
net_warn_ratelimited("martian destination %pI4 from %pI4, dev %s\n",
&daddr, &saddr, dev->name);
#endif
e_inval:
err = -EINVAL;
goto out;
e_nobufs:
err = -ENOBUFS;
goto out;
martian_source:
ip_handle_martian_source(dev, in_dev, skb, daddr, saddr);
goto out;
}
int ip_route_input_noref(struct sk_buff *skb, __be32 daddr, __be32 saddr,
u8 tos, struct net_device *dev)
{
struct fib_result res;
int err;
tos &= IPTOS_RT_MASK;
rcu_read_lock();
err = ip_route_input_rcu(skb, daddr, saddr, tos, dev, &res);
rcu_read_unlock();
return err;
}
EXPORT_SYMBOL(ip_route_input_noref);
/* called with rcu_read_lock held */
int ip_route_input_rcu(struct sk_buff *skb, __be32 daddr, __be32 saddr,
u8 tos, struct net_device *dev, struct fib_result *res)
{
/* Multicast recognition logic is moved from route cache to here.
The problem was that too many Ethernet cards have broken/missing
hardware multicast filters :-( As result the host on multicasting
network acquires a lot of useless route cache entries, sort of
SDR messages from all the world. Now we try to get rid of them.
Really, provided software IP multicast filter is organized
reasonably (at least, hashed), it does not result in a slowdown
comparing with route cache reject entries.
Note, that multicast routers are not affected, because
route cache entry is created eventually.
*/
if (ipv4_is_multicast(daddr)) {
struct in_device *in_dev = __in_dev_get_rcu(dev);
int our = 0;
int err = -EINVAL;
if (in_dev)
our = ip_check_mc_rcu(in_dev, daddr, saddr,
ip_hdr(skb)->protocol);
/* check l3 master if no match yet */
if ((!in_dev || !our) && netif_is_l3_slave(dev)) {
struct in_device *l3_in_dev;
l3_in_dev = __in_dev_get_rcu(skb->dev);
if (l3_in_dev)
our = ip_check_mc_rcu(l3_in_dev, daddr, saddr,
ip_hdr(skb)->protocol);
}
if (our
#ifdef CONFIG_IP_MROUTE
||
(!ipv4_is_local_multicast(daddr) &&
IN_DEV_MFORWARD(in_dev))
#endif
) {
err = ip_route_input_mc(skb, daddr, saddr,
tos, dev, our);
}
return err;
}
return ip_route_input_slow(skb, daddr, saddr, tos, dev, res);
}
/* called with rcu_read_lock() */
static struct rtable *__mkroute_output(const struct fib_result *res,
const struct flowi4 *fl4, int orig_oif,
struct net_device *dev_out,
unsigned int flags)
{
struct fib_info *fi = res->fi;
struct fib_nh_exception *fnhe;
struct in_device *in_dev;
u16 type = res->type;
struct rtable *rth;
bool do_cache;
in_dev = __in_dev_get_rcu(dev_out);
if (!in_dev)
return ERR_PTR(-EINVAL);
if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev)))
if (ipv4_is_loopback(fl4->saddr) &&
!(dev_out->flags & IFF_LOOPBACK) &&
!netif_is_l3_master(dev_out))
return ERR_PTR(-EINVAL);
if (ipv4_is_lbcast(fl4->daddr))
type = RTN_BROADCAST;
else if (ipv4_is_multicast(fl4->daddr))
type = RTN_MULTICAST;
else if (ipv4_is_zeronet(fl4->daddr))
return ERR_PTR(-EINVAL);
if (dev_out->flags & IFF_LOOPBACK)
flags |= RTCF_LOCAL;
do_cache = true;
if (type == RTN_BROADCAST) {
flags |= RTCF_BROADCAST | RTCF_LOCAL;
fi = NULL;
} else if (type == RTN_MULTICAST) {
flags |= RTCF_MULTICAST | RTCF_LOCAL;
if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr,
fl4->flowi4_proto))
flags &= ~RTCF_LOCAL;
else
do_cache = false;
/* If multicast route do not exist use
* default one, but do not gateway in this case.
* Yes, it is hack.
*/
if (fi && res->prefixlen < 4)
fi = NULL;
} else if ((type == RTN_LOCAL) && (orig_oif != 0) &&
(orig_oif != dev_out->ifindex)) {
/* For local routes that require a particular output interface
* we do not want to cache the result. Caching the result
* causes incorrect behaviour when there are multiple source
* addresses on the interface, the end result being that if the
* intended recipient is waiting on that interface for the
* packet he won't receive it because it will be delivered on
* the loopback interface and the IP_PKTINFO ipi_ifindex will
* be set to the loopback interface as well.
*/
fi = NULL;
}
fnhe = NULL;
do_cache &= fi != NULL;
if (do_cache) {
struct rtable __rcu **prth;
struct fib_nh *nh = &FIB_RES_NH(*res);
fnhe = find_exception(nh, fl4->daddr);
if (fnhe) {
prth = &fnhe->fnhe_rth_output;
rth = rcu_dereference(*prth);
if (rth && rth->dst.expires &&
time_after(jiffies, rth->dst.expires)) {
ip_del_fnhe(nh, fl4->daddr);
fnhe = NULL;
} else {
goto rt_cache;
}
}
if (unlikely(fl4->flowi4_flags &
FLOWI_FLAG_KNOWN_NH &&
!(nh->nh_gw &&
nh->nh_scope == RT_SCOPE_LINK))) {
do_cache = false;
goto add;
}
prth = raw_cpu_ptr(nh->nh_pcpu_rth_output);
rth = rcu_dereference(*prth);
rt_cache:
if (rt_cache_valid(rth) && dst_hold_safe(&rth->dst))
return rth;
}
add:
rth = rt_dst_alloc(dev_out, flags, type,
IN_DEV_CONF_GET(in_dev, NOPOLICY),
IN_DEV_CONF_GET(in_dev, NOXFRM),
do_cache);
if (!rth)
return ERR_PTR(-ENOBUFS);
rth->rt_iif = orig_oif ? : 0;
if (res->table)
rth->rt_table_id = res->table->tb_id;
RT_CACHE_STAT_INC(out_slow_tot);
if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) {
if (flags & RTCF_LOCAL &&
!(dev_out->flags & IFF_LOOPBACK)) {
rth->dst.output = ip_mc_output;
RT_CACHE_STAT_INC(out_slow_mc);
}
#ifdef CONFIG_IP_MROUTE
if (type == RTN_MULTICAST) {
if (IN_DEV_MFORWARD(in_dev) &&
!ipv4_is_local_multicast(fl4->daddr)) {
rth->dst.input = ip_mr_input;
rth->dst.output = ip_mc_output;
}
}
#endif
}
rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0, do_cache);
set_lwt_redirect(rth);
return rth;
}
/*
* Major route resolver routine.
*/
struct rtable *ip_route_output_key_hash(struct net *net, struct flowi4 *fl4,
const struct sk_buff *skb)
{
__u8 tos = RT_FL_TOS(fl4);
struct fib_result res;
struct rtable *rth;
res.tclassid = 0;
res.fi = NULL;
res.table = NULL;
fl4->flowi4_iif = LOOPBACK_IFINDEX;
fl4->flowi4_tos = tos & IPTOS_RT_MASK;
fl4->flowi4_scope = ((tos & RTO_ONLINK) ?
RT_SCOPE_LINK : RT_SCOPE_UNIVERSE);
rcu_read_lock();
rth = ip_route_output_key_hash_rcu(net, fl4, &res, skb);
rcu_read_unlock();
return rth;
}
EXPORT_SYMBOL_GPL(ip_route_output_key_hash);
struct rtable *ip_route_output_key_hash_rcu(struct net *net, struct flowi4 *fl4,
struct fib_result *res,
const struct sk_buff *skb)
{
struct net_device *dev_out = NULL;
int orig_oif = fl4->flowi4_oif;
unsigned int flags = 0;
struct rtable *rth;
int err = -ENETUNREACH;
if (fl4->saddr) {
rth = ERR_PTR(-EINVAL);
if (ipv4_is_multicast(fl4->saddr) ||
ipv4_is_lbcast(fl4->saddr) ||
ipv4_is_zeronet(fl4->saddr))
goto out;
/* I removed check for oif == dev_out->oif here.
It was wrong for two reasons:
1. ip_dev_find(net, saddr) can return wrong iface, if saddr
is assigned to multiple interfaces.
2. Moreover, we are allowed to send packets with saddr
of another iface. --ANK
*/
if (fl4->flowi4_oif == 0 &&
(ipv4_is_multicast(fl4->daddr) ||
ipv4_is_lbcast(fl4->daddr))) {
/* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */
dev_out = __ip_dev_find(net, fl4->saddr, false);
if (!dev_out)
goto out;
/* Special hack: user can direct multicasts
and limited broadcast via necessary interface
without fiddling with IP_MULTICAST_IF or IP_PKTINFO.
This hack is not just for fun, it allows
vic,vat and friends to work.
They bind socket to loopback, set ttl to zero
and expect that it will work.
From the viewpoint of routing cache they are broken,
because we are not allowed to build multicast path
with loopback source addr (look, routing cache
cannot know, that ttl is zero, so that packet
will not leave this host and route is valid).
Luckily, this hack is good workaround.
*/
fl4->flowi4_oif = dev_out->ifindex;
goto make_route;
}
if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) {
/* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */
if (!__ip_dev_find(net, fl4->saddr, false))
goto out;
}
}
if (fl4->flowi4_oif) {
dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif);
rth = ERR_PTR(-ENODEV);
if (!dev_out)
goto out;
/* RACE: Check return value of inet_select_addr instead. */
if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) {
rth = ERR_PTR(-ENETUNREACH);
goto out;
}
if (ipv4_is_local_multicast(fl4->daddr) ||
ipv4_is_lbcast(fl4->daddr) ||
fl4->flowi4_proto == IPPROTO_IGMP) {
if (!fl4->saddr)
fl4->saddr = inet_select_addr(dev_out, 0,
RT_SCOPE_LINK);
goto make_route;
}
if (!fl4->saddr) {
if (ipv4_is_multicast(fl4->daddr))
fl4->saddr = inet_select_addr(dev_out, 0,
fl4->flowi4_scope);
else if (!fl4->daddr)
fl4->saddr = inet_select_addr(dev_out, 0,
RT_SCOPE_HOST);
}
}
if (!fl4->daddr) {
fl4->daddr = fl4->saddr;
if (!fl4->daddr)
fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK);
dev_out = net->loopback_dev;
fl4->flowi4_oif = LOOPBACK_IFINDEX;
res->type = RTN_LOCAL;
flags |= RTCF_LOCAL;
goto make_route;
}
err = fib_lookup(net, fl4, res, 0);
if (err) {
res->fi = NULL;
res->table = NULL;
if (fl4->flowi4_oif &&
(ipv4_is_multicast(fl4->daddr) ||
!netif_index_is_l3_master(net, fl4->flowi4_oif))) {
/* Apparently, routing tables are wrong. Assume,
that the destination is on link.
WHY? DW.
Because we are allowed to send to iface
even if it has NO routes and NO assigned
addresses. When oif is specified, routing
tables are looked up with only one purpose:
to catch if destination is gatewayed, rather than
direct. Moreover, if MSG_DONTROUTE is set,
we send packet, ignoring both routing tables
and ifaddr state. --ANK
We could make it even if oif is unknown,
likely IPv6, but we do not.
*/
if (fl4->saddr == 0)
fl4->saddr = inet_select_addr(dev_out, 0,
RT_SCOPE_LINK);
res->type = RTN_UNICAST;
goto make_route;
}
rth = ERR_PTR(err);
goto out;
}
if (res->type == RTN_LOCAL) {
if (!fl4->saddr) {
if (res->fi->fib_prefsrc)
fl4->saddr = res->fi->fib_prefsrc;
else
fl4->saddr = fl4->daddr;
}
/* L3 master device is the loopback for that domain */
dev_out = l3mdev_master_dev_rcu(FIB_RES_DEV(*res)) ? :
net->loopback_dev;
fl4->flowi4_oif = dev_out->ifindex;
flags |= RTCF_LOCAL;
goto make_route;
}
fib_select_path(net, res, fl4, skb);
dev_out = FIB_RES_DEV(*res);
fl4->flowi4_oif = dev_out->ifindex;
make_route:
rth = __mkroute_output(res, fl4, orig_oif, dev_out, flags);
out:
return rth;
}
static struct dst_entry *ipv4_blackhole_dst_check(struct dst_entry *dst, u32 cookie)
{
return NULL;
}
static unsigned int ipv4_blackhole_mtu(const struct dst_entry *dst)
{
unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
return mtu ? : dst->dev->mtu;
}
static void ipv4_rt_blackhole_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu)
{
}
static void ipv4_rt_blackhole_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb)
{
}
static u32 *ipv4_rt_blackhole_cow_metrics(struct dst_entry *dst,
unsigned long old)
{
return NULL;
}
static struct dst_ops ipv4_dst_blackhole_ops = {
.family = AF_INET,
.check = ipv4_blackhole_dst_check,
.mtu = ipv4_blackhole_mtu,
.default_advmss = ipv4_default_advmss,
.update_pmtu = ipv4_rt_blackhole_update_pmtu,
.redirect = ipv4_rt_blackhole_redirect,
.cow_metrics = ipv4_rt_blackhole_cow_metrics,
.neigh_lookup = ipv4_neigh_lookup,
};
struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_orig)
{
struct rtable *ort = (struct rtable *) dst_orig;
struct rtable *rt;
rt = dst_alloc(&ipv4_dst_blackhole_ops, NULL, 1, DST_OBSOLETE_NONE, 0);
if (rt) {
struct dst_entry *new = &rt->dst;
new->__use = 1;
new->input = dst_discard;
new->output = dst_discard_out;
new->dev = net->loopback_dev;
if (new->dev)
dev_hold(new->dev);
rt->rt_is_input = ort->rt_is_input;
rt->rt_iif = ort->rt_iif;
rt->rt_pmtu = ort->rt_pmtu;
rt->rt_genid = rt_genid_ipv4(net);
rt->rt_flags = ort->rt_flags;
rt->rt_type = ort->rt_type;
rt->rt_gateway = ort->rt_gateway;
rt->rt_uses_gateway = ort->rt_uses_gateway;
INIT_LIST_HEAD(&rt->rt_uncached);
}
dst_release(dst_orig);
return rt ? &rt->dst : ERR_PTR(-ENOMEM);
}
struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4,
const struct sock *sk)
{
struct rtable *rt = __ip_route_output_key(net, flp4);
if (IS_ERR(rt))
return rt;
if (flp4->flowi4_proto)
rt = (struct rtable *)xfrm_lookup_route(net, &rt->dst,
flowi4_to_flowi(flp4),
sk, 0);
return rt;
}
EXPORT_SYMBOL_GPL(ip_route_output_flow);
/* called with rcu_read_lock held */
static int rt_fill_info(struct net *net, __be32 dst, __be32 src, u32 table_id,
struct flowi4 *fl4, struct sk_buff *skb, u32 portid,
u32 seq)
{
struct rtable *rt = skb_rtable(skb);
struct rtmsg *r;
struct nlmsghdr *nlh;
unsigned long expires = 0;
u32 error;
u32 metrics[RTAX_MAX];
nlh = nlmsg_put(skb, portid, seq, RTM_NEWROUTE, sizeof(*r), 0);
if (!nlh)
return -EMSGSIZE;
r = nlmsg_data(nlh);
r->rtm_family = AF_INET;
r->rtm_dst_len = 32;
r->rtm_src_len = 0;
r->rtm_tos = fl4->flowi4_tos;
r->rtm_table = table_id < 256 ? table_id : RT_TABLE_COMPAT;
if (nla_put_u32(skb, RTA_TABLE, table_id))
goto nla_put_failure;
r->rtm_type = rt->rt_type;
r->rtm_scope = RT_SCOPE_UNIVERSE;
r->rtm_protocol = RTPROT_UNSPEC;
r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED;
if (rt->rt_flags & RTCF_NOTIFY)
r->rtm_flags |= RTM_F_NOTIFY;
if (IPCB(skb)->flags & IPSKB_DOREDIRECT)
r->rtm_flags |= RTCF_DOREDIRECT;
if (nla_put_in_addr(skb, RTA_DST, dst))
goto nla_put_failure;
if (src) {
r->rtm_src_len = 32;
if (nla_put_in_addr(skb, RTA_SRC, src))
goto nla_put_failure;
}
if (rt->dst.dev &&
nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex))
goto nla_put_failure;
#ifdef CONFIG_IP_ROUTE_CLASSID
if (rt->dst.tclassid &&
nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid))
goto nla_put_failure;
#endif
if (!rt_is_input_route(rt) &&
fl4->saddr != src) {
if (nla_put_in_addr(skb, RTA_PREFSRC, fl4->saddr))
goto nla_put_failure;
}
if (rt->rt_uses_gateway &&
nla_put_in_addr(skb, RTA_GATEWAY, rt->rt_gateway))
goto nla_put_failure;
expires = rt->dst.expires;
if (expires) {
unsigned long now = jiffies;
if (time_before(now, expires))
expires -= now;
else
expires = 0;
}
memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics));
if (rt->rt_pmtu && expires)
metrics[RTAX_MTU - 1] = rt->rt_pmtu;
if (rtnetlink_put_metrics(skb, metrics) < 0)
goto nla_put_failure;
if (fl4->flowi4_mark &&
nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark))
goto nla_put_failure;
if (!uid_eq(fl4->flowi4_uid, INVALID_UID) &&
nla_put_u32(skb, RTA_UID,
from_kuid_munged(current_user_ns(), fl4->flowi4_uid)))
goto nla_put_failure;
error = rt->dst.error;
if (rt_is_input_route(rt)) {
#ifdef CONFIG_IP_MROUTE
if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) &&
IPV4_DEVCONF_ALL(net, MC_FORWARDING)) {
int err = ipmr_get_route(net, skb,
fl4->saddr, fl4->daddr,
r, portid);
if (err <= 0) {
if (err == 0)
return 0;
goto nla_put_failure;
}
} else
#endif
if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex))
goto nla_put_failure;
}
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0)
goto nla_put_failure;
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(in_skb->sk);
struct rtmsg *rtm;
struct nlattr *tb[RTA_MAX+1];
struct fib_result res = {};
struct rtable *rt = NULL;
struct flowi4 fl4;
__be32 dst = 0;
__be32 src = 0;
u32 iif;
int err;
int mark;
struct sk_buff *skb;
u32 table_id = RT_TABLE_MAIN;
kuid_t uid;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy,
extack);
if (err < 0)
goto errout;
rtm = nlmsg_data(nlh);
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb) {
err = -ENOBUFS;
goto errout;
}
/* Reserve room for dummy headers, this skb can pass
through good chunk of routing engine.
*/
skb_reset_mac_header(skb);
skb_reset_network_header(skb);
src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0;
dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0;
iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0;
mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0;
if (tb[RTA_UID])
uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID]));
else
uid = (iif ? INVALID_UID : current_uid());
/* Bugfix: need to give ip_route_input enough of an IP header to
* not gag.
*/
ip_hdr(skb)->protocol = IPPROTO_UDP;
ip_hdr(skb)->saddr = src;
ip_hdr(skb)->daddr = dst;
skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr));
memset(&fl4, 0, sizeof(fl4));
fl4.daddr = dst;
fl4.saddr = src;
fl4.flowi4_tos = rtm->rtm_tos;
fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0;
fl4.flowi4_mark = mark;
fl4.flowi4_uid = uid;
rcu_read_lock();
if (iif) {
struct net_device *dev;
dev = dev_get_by_index_rcu(net, iif);
if (!dev) {
err = -ENODEV;
goto errout_free;
}
skb->protocol = htons(ETH_P_IP);
skb->dev = dev;
skb->mark = mark;
err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos,
dev, &res);
rt = skb_rtable(skb);
if (err == 0 && rt->dst.error)
err = -rt->dst.error;
} else {
rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb);
err = 0;
if (IS_ERR(rt))
err = PTR_ERR(rt);
else
skb_dst_set(skb, &rt->dst);
}
if (err)
goto errout_free;
if (rtm->rtm_flags & RTM_F_NOTIFY)
rt->rt_flags |= RTCF_NOTIFY;
if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE)
table_id = rt->rt_table_id;
if (rtm->rtm_flags & RTM_F_FIB_MATCH)
err = fib_dump_info(skb, NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq, RTM_NEWROUTE, table_id,
rt->rt_type, res.prefix, res.prefixlen,
fl4.flowi4_tos, res.fi, 0);
else
err = rt_fill_info(net, dst, src, table_id, &fl4, skb,
NETLINK_CB(in_skb).portid, nlh->nlmsg_seq);
if (err < 0)
goto errout_free;
rcu_read_unlock();
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
errout:
return err;
errout_free:
rcu_read_unlock();
kfree_skb(skb);
goto errout;
}
void ip_rt_multicast_event(struct in_device *in_dev)
{
rt_cache_flush(dev_net(in_dev->dev));
}
#ifdef CONFIG_SYSCTL
static int ip_rt_gc_interval __read_mostly = 60 * HZ;
static int ip_rt_gc_min_interval __read_mostly = HZ / 2;
static int ip_rt_gc_elasticity __read_mostly = 8;
static int ipv4_sysctl_rtcache_flush(struct ctl_table *__ctl, int write,
void __user *buffer,
size_t *lenp, loff_t *ppos)
{
struct net *net = (struct net *)__ctl->extra1;
if (write) {
rt_cache_flush(net);
fnhe_genid_bump(net);
return 0;
}
return -EINVAL;
}
static struct ctl_table ipv4_route_table[] = {
{
.procname = "gc_thresh",
.data = &ipv4_dst_ops.gc_thresh,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "max_size",
.data = &ip_rt_max_size,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
/* Deprecated. Use gc_min_interval_ms */
.procname = "gc_min_interval",
.data = &ip_rt_gc_min_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_min_interval_ms",
.data = &ip_rt_gc_min_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{
.procname = "gc_timeout",
.data = &ip_rt_gc_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_interval",
.data = &ip_rt_gc_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "redirect_load",
.data = &ip_rt_redirect_load,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "redirect_number",
.data = &ip_rt_redirect_number,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "redirect_silence",
.data = &ip_rt_redirect_silence,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "error_cost",
.data = &ip_rt_error_cost,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "error_burst",
.data = &ip_rt_error_burst,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "gc_elasticity",
.data = &ip_rt_gc_elasticity,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "mtu_expires",
.data = &ip_rt_mtu_expires,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "min_pmtu",
.data = &ip_rt_min_pmtu,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "min_adv_mss",
.data = &ip_rt_min_advmss,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ }
};
static struct ctl_table ipv4_route_flush_table[] = {
{
.procname = "flush",
.maxlen = sizeof(int),
.mode = 0200,
.proc_handler = ipv4_sysctl_rtcache_flush,
},
{ },
};
static __net_init int sysctl_route_net_init(struct net *net)
{
struct ctl_table *tbl;
tbl = ipv4_route_flush_table;
if (!net_eq(net, &init_net)) {
tbl = kmemdup(tbl, sizeof(ipv4_route_flush_table), GFP_KERNEL);
if (!tbl)
goto err_dup;
/* Don't export sysctls to unprivileged users */
if (net->user_ns != &init_user_ns)
tbl[0].procname = NULL;
}
tbl[0].extra1 = net;
net->ipv4.route_hdr = register_net_sysctl(net, "net/ipv4/route", tbl);
if (!net->ipv4.route_hdr)
goto err_reg;
return 0;
err_reg:
if (tbl != ipv4_route_flush_table)
kfree(tbl);
err_dup:
return -ENOMEM;
}
static __net_exit void sysctl_route_net_exit(struct net *net)
{
struct ctl_table *tbl;
tbl = net->ipv4.route_hdr->ctl_table_arg;
unregister_net_sysctl_table(net->ipv4.route_hdr);
BUG_ON(tbl == ipv4_route_flush_table);
kfree(tbl);
}
static __net_initdata struct pernet_operations sysctl_route_ops = {
.init = sysctl_route_net_init,
.exit = sysctl_route_net_exit,
};
#endif
static __net_init int rt_genid_init(struct net *net)
{
atomic_set(&net->ipv4.rt_genid, 0);
atomic_set(&net->fnhe_genid, 0);
atomic_set(&net->ipv4.dev_addr_genid, get_random_int());
return 0;
}
static __net_initdata struct pernet_operations rt_genid_ops = {
.init = rt_genid_init,
};
static int __net_init ipv4_inetpeer_init(struct net *net)
{
struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL);
if (!bp)
return -ENOMEM;
inet_peer_base_init(bp);
net->ipv4.peers = bp;
return 0;
}
static void __net_exit ipv4_inetpeer_exit(struct net *net)
{
struct inet_peer_base *bp = net->ipv4.peers;
net->ipv4.peers = NULL;
inetpeer_invalidate_tree(bp);
kfree(bp);
}
static __net_initdata struct pernet_operations ipv4_inetpeer_ops = {
.init = ipv4_inetpeer_init,
.exit = ipv4_inetpeer_exit,
};
#ifdef CONFIG_IP_ROUTE_CLASSID
struct ip_rt_acct __percpu *ip_rt_acct __read_mostly;
#endif /* CONFIG_IP_ROUTE_CLASSID */
int __init ip_rt_init(void)
{
int rc = 0;
int cpu;
ip_idents = kmalloc(IP_IDENTS_SZ * sizeof(*ip_idents), GFP_KERNEL);
if (!ip_idents)
panic("IP: failed to allocate ip_idents\n");
prandom_bytes(ip_idents, IP_IDENTS_SZ * sizeof(*ip_idents));
ip_tstamps = kcalloc(IP_IDENTS_SZ, sizeof(*ip_tstamps), GFP_KERNEL);
if (!ip_tstamps)
panic("IP: failed to allocate ip_tstamps\n");
for_each_possible_cpu(cpu) {
struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu);
INIT_LIST_HEAD(&ul->head);
spin_lock_init(&ul->lock);
}
#ifdef CONFIG_IP_ROUTE_CLASSID
ip_rt_acct = __alloc_percpu(256 * sizeof(struct ip_rt_acct), __alignof__(struct ip_rt_acct));
if (!ip_rt_acct)
panic("IP: failed to allocate ip_rt_acct\n");
#endif
ipv4_dst_ops.kmem_cachep =
kmem_cache_create("ip_dst_cache", sizeof(struct rtable), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
ipv4_dst_blackhole_ops.kmem_cachep = ipv4_dst_ops.kmem_cachep;
if (dst_entries_init(&ipv4_dst_ops) < 0)
panic("IP: failed to allocate ipv4_dst_ops counter\n");
if (dst_entries_init(&ipv4_dst_blackhole_ops) < 0)
panic("IP: failed to allocate ipv4_dst_blackhole_ops counter\n");
ipv4_dst_ops.gc_thresh = ~0;
ip_rt_max_size = INT_MAX;
devinet_init();
ip_fib_init();
if (ip_rt_proc_init())
pr_err("Unable to create route proc files\n");
#ifdef CONFIG_XFRM
xfrm_init();
xfrm4_init();
#endif
rtnl_register(PF_INET, RTM_GETROUTE, inet_rtm_getroute, NULL, NULL);
#ifdef CONFIG_SYSCTL
register_pernet_subsys(&sysctl_route_ops);
#endif
register_pernet_subsys(&rt_genid_ops);
register_pernet_subsys(&ipv4_inetpeer_ops);
return rc;
}
#ifdef CONFIG_SYSCTL
/*
* We really need to sanitize the damn ipv4 init order, then all
* this nonsense will go away.
*/
void __init ip_static_sysctl_init(void)
{
register_net_sysctl(&init_net, "net/ipv4/route", ipv4_route_table);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_2744_0 |
crossvul-cpp_data_good_2199_0 | /*
* Copyright (C) 2006,2008 by the Massachusetts Institute of Technology.
* All rights reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* A module that implements the spnego security mechanism.
* It is used to negotiate the security mechanism between
* peers using the GSS-API. SPNEGO is specified in RFC 4178.
*
*/
/*
* Copyright (c) 2006-2008, Novell, Inc.
* 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.
* * The copyright holder's name is not 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.
*/
/* #pragma ident "@(#)spnego_mech.c 1.7 04/09/28 SMI" */
#include <k5-int.h>
#include <krb5.h>
#include <mglueP.h>
#include "gssapiP_spnego.h"
#include <gssapi_err_generic.h>
#undef g_token_size
#undef g_verify_token_header
#undef g_make_token_header
#define HARD_ERROR(v) ((v) != GSS_S_COMPLETE && (v) != GSS_S_CONTINUE_NEEDED)
typedef const gss_OID_desc *gss_OID_const;
/* der routines defined in libgss */
extern unsigned int gssint_der_length_size(unsigned int);
extern int gssint_get_der_length(unsigned char **, unsigned int,
unsigned int*);
extern int gssint_put_der_length(unsigned int, unsigned char **, unsigned int);
/* private routines for spnego_mechanism */
static spnego_token_t make_spnego_token(const char *);
static gss_buffer_desc make_err_msg(const char *);
static int g_token_size(gss_OID_const, unsigned int);
static int g_make_token_header(gss_OID_const, unsigned int,
unsigned char **, unsigned int);
static int g_verify_token_header(gss_OID_const, unsigned int *,
unsigned char **,
int, unsigned int);
static int g_verify_neg_token_init(unsigned char **, unsigned int);
static gss_OID get_mech_oid(OM_uint32 *, unsigned char **, size_t);
static gss_buffer_t get_input_token(unsigned char **, unsigned int);
static gss_OID_set get_mech_set(OM_uint32 *, unsigned char **, unsigned int);
static OM_uint32 get_req_flags(unsigned char **, OM_uint32, OM_uint32 *);
static OM_uint32 get_available_mechs(OM_uint32 *, gss_name_t, gss_cred_usage_t,
gss_const_key_value_set_t,
gss_cred_id_t *, gss_OID_set *);
static OM_uint32 get_negotiable_mechs(OM_uint32 *, spnego_gss_cred_id_t,
gss_cred_usage_t, gss_OID_set *);
static void release_spnego_ctx(spnego_gss_ctx_id_t *);
static void check_spnego_options(spnego_gss_ctx_id_t);
static spnego_gss_ctx_id_t create_spnego_ctx(void);
static int put_mech_set(gss_OID_set mechSet, gss_buffer_t buf);
static int put_input_token(unsigned char **, gss_buffer_t, unsigned int);
static int put_mech_oid(unsigned char **, gss_OID_const, unsigned int);
static int put_negResult(unsigned char **, OM_uint32, unsigned int);
static OM_uint32
process_mic(OM_uint32 *, gss_buffer_t, spnego_gss_ctx_id_t,
gss_buffer_t *, OM_uint32 *, send_token_flag *);
static OM_uint32
handle_mic(OM_uint32 *, gss_buffer_t, int, spnego_gss_ctx_id_t,
gss_buffer_t *, OM_uint32 *, send_token_flag *);
static OM_uint32
init_ctx_new(OM_uint32 *, spnego_gss_cred_id_t, gss_ctx_id_t *,
send_token_flag *);
static OM_uint32
init_ctx_nego(OM_uint32 *, spnego_gss_ctx_id_t, OM_uint32, gss_OID,
gss_buffer_t *, gss_buffer_t *,
OM_uint32 *, send_token_flag *);
static OM_uint32
init_ctx_cont(OM_uint32 *, gss_ctx_id_t *, gss_buffer_t,
gss_buffer_t *, gss_buffer_t *,
OM_uint32 *, send_token_flag *);
static OM_uint32
init_ctx_reselect(OM_uint32 *, spnego_gss_ctx_id_t, OM_uint32,
gss_OID, gss_buffer_t *, gss_buffer_t *,
OM_uint32 *, send_token_flag *);
static OM_uint32
init_ctx_call_init(OM_uint32 *, spnego_gss_ctx_id_t, spnego_gss_cred_id_t,
gss_name_t, OM_uint32, OM_uint32, gss_buffer_t,
gss_OID *, gss_buffer_t, OM_uint32 *, OM_uint32 *,
OM_uint32 *, send_token_flag *);
static OM_uint32
acc_ctx_new(OM_uint32 *, gss_buffer_t, gss_ctx_id_t *,
spnego_gss_cred_id_t, gss_buffer_t *,
gss_buffer_t *, OM_uint32 *, send_token_flag *);
static OM_uint32
acc_ctx_cont(OM_uint32 *, gss_buffer_t, gss_ctx_id_t *,
gss_buffer_t *, gss_buffer_t *,
OM_uint32 *, send_token_flag *);
static OM_uint32
acc_ctx_vfy_oid(OM_uint32 *, spnego_gss_ctx_id_t, gss_OID,
OM_uint32 *, send_token_flag *);
static OM_uint32
acc_ctx_call_acc(OM_uint32 *, spnego_gss_ctx_id_t, spnego_gss_cred_id_t,
gss_buffer_t, gss_OID *, gss_buffer_t,
OM_uint32 *, OM_uint32 *, gss_cred_id_t *,
OM_uint32 *, send_token_flag *);
static gss_OID
negotiate_mech(gss_OID_set, gss_OID_set, OM_uint32 *);
static int
g_get_tag_and_length(unsigned char **, int, unsigned int, unsigned int *);
static int
make_spnego_tokenInit_msg(spnego_gss_ctx_id_t,
int,
gss_buffer_t,
OM_uint32, gss_buffer_t, send_token_flag,
gss_buffer_t);
static int
make_spnego_tokenTarg_msg(OM_uint32, gss_OID, gss_buffer_t,
gss_buffer_t, send_token_flag,
gss_buffer_t);
static OM_uint32
get_negTokenInit(OM_uint32 *, gss_buffer_t, gss_buffer_t,
gss_OID_set *, OM_uint32 *, gss_buffer_t *,
gss_buffer_t *);
static OM_uint32
get_negTokenResp(OM_uint32 *, unsigned char *, unsigned int,
OM_uint32 *, gss_OID *, gss_buffer_t *, gss_buffer_t *);
static int
is_kerb_mech(gss_OID oid);
/* SPNEGO oid structure */
static const gss_OID_desc spnego_oids[] = {
{SPNEGO_OID_LENGTH, SPNEGO_OID},
};
const gss_OID_desc * const gss_mech_spnego = spnego_oids+0;
static const gss_OID_set_desc spnego_oidsets[] = {
{1, (gss_OID) spnego_oids+0},
};
const gss_OID_set_desc * const gss_mech_set_spnego = spnego_oidsets+0;
static int make_NegHints(OM_uint32 *, spnego_gss_cred_id_t, gss_buffer_t *);
static int put_neg_hints(unsigned char **, gss_buffer_t, unsigned int);
static OM_uint32
acc_ctx_hints(OM_uint32 *, gss_ctx_id_t *, spnego_gss_cred_id_t,
gss_buffer_t *, OM_uint32 *, send_token_flag *);
/*
* The Mech OID for SPNEGO:
* { iso(1) org(3) dod(6) internet(1) security(5)
* mechanism(5) spnego(2) }
*/
static struct gss_config spnego_mechanism =
{
{SPNEGO_OID_LENGTH, SPNEGO_OID},
NULL,
spnego_gss_acquire_cred,
spnego_gss_release_cred,
spnego_gss_init_sec_context,
#ifndef LEAN_CLIENT
spnego_gss_accept_sec_context,
#else
NULL,
#endif /* LEAN_CLIENT */
NULL, /* gss_process_context_token */
spnego_gss_delete_sec_context, /* gss_delete_sec_context */
spnego_gss_context_time, /* gss_context_time */
spnego_gss_get_mic, /* gss_get_mic */
spnego_gss_verify_mic, /* gss_verify_mic */
spnego_gss_wrap, /* gss_wrap */
spnego_gss_unwrap, /* gss_unwrap */
spnego_gss_display_status,
NULL, /* gss_indicate_mechs */
spnego_gss_compare_name,
spnego_gss_display_name,
spnego_gss_import_name,
spnego_gss_release_name,
spnego_gss_inquire_cred, /* gss_inquire_cred */
NULL, /* gss_add_cred */
#ifndef LEAN_CLIENT
spnego_gss_export_sec_context, /* gss_export_sec_context */
spnego_gss_import_sec_context, /* gss_import_sec_context */
#else
NULL, /* gss_export_sec_context */
NULL, /* gss_import_sec_context */
#endif /* LEAN_CLIENT */
NULL, /* gss_inquire_cred_by_mech */
spnego_gss_inquire_names_for_mech,
spnego_gss_inquire_context, /* gss_inquire_context */
NULL, /* gss_internal_release_oid */
spnego_gss_wrap_size_limit, /* gss_wrap_size_limit */
NULL, /* gssd_pname_to_uid */
NULL, /* gss_userok */
NULL, /* gss_export_name */
spnego_gss_duplicate_name, /* gss_duplicate_name */
NULL, /* gss_store_cred */
spnego_gss_inquire_sec_context_by_oid, /* gss_inquire_sec_context_by_oid */
spnego_gss_inquire_cred_by_oid, /* gss_inquire_cred_by_oid */
spnego_gss_set_sec_context_option, /* gss_set_sec_context_option */
spnego_gss_set_cred_option, /* gssspi_set_cred_option */
NULL, /* gssspi_mech_invoke */
spnego_gss_wrap_aead,
spnego_gss_unwrap_aead,
spnego_gss_wrap_iov,
spnego_gss_unwrap_iov,
spnego_gss_wrap_iov_length,
spnego_gss_complete_auth_token,
spnego_gss_acquire_cred_impersonate_name,
NULL, /* gss_add_cred_impersonate_name */
spnego_gss_display_name_ext,
spnego_gss_inquire_name,
spnego_gss_get_name_attribute,
spnego_gss_set_name_attribute,
spnego_gss_delete_name_attribute,
spnego_gss_export_name_composite,
spnego_gss_map_name_to_any,
spnego_gss_release_any_name_mapping,
spnego_gss_pseudo_random,
spnego_gss_set_neg_mechs,
spnego_gss_inquire_saslname_for_mech,
spnego_gss_inquire_mech_for_saslname,
spnego_gss_inquire_attrs_for_mech,
spnego_gss_acquire_cred_from,
NULL, /* gss_store_cred_into */
spnego_gss_acquire_cred_with_password,
spnego_gss_export_cred,
spnego_gss_import_cred,
NULL, /* gssspi_import_sec_context_by_mech */
NULL, /* gssspi_import_name_by_mech */
NULL, /* gssspi_import_cred_by_mech */
spnego_gss_get_mic_iov,
spnego_gss_verify_mic_iov,
spnego_gss_get_mic_iov_length
};
#ifdef _GSS_STATIC_LINK
#include "mglueP.h"
static int gss_spnegomechglue_init(void)
{
struct gss_mech_config mech_spnego;
memset(&mech_spnego, 0, sizeof(mech_spnego));
mech_spnego.mech = &spnego_mechanism;
mech_spnego.mechNameStr = "spnego";
mech_spnego.mech_type = GSS_C_NO_OID;
return gssint_register_mechinfo(&mech_spnego);
}
#else
gss_mechanism KRB5_CALLCONV
gss_mech_initialize(void)
{
return (&spnego_mechanism);
}
MAKE_INIT_FUNCTION(gss_krb5int_lib_init);
MAKE_FINI_FUNCTION(gss_krb5int_lib_fini);
int gss_krb5int_lib_init(void);
#endif /* _GSS_STATIC_LINK */
int gss_spnegoint_lib_init(void)
{
int err;
err = k5_key_register(K5_KEY_GSS_SPNEGO_STATUS, NULL);
if (err)
return err;
#ifdef _GSS_STATIC_LINK
return gss_spnegomechglue_init();
#else
return 0;
#endif
}
void gss_spnegoint_lib_fini(void)
{
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_acquire_cred(OM_uint32 *minor_status,
gss_name_t desired_name,
OM_uint32 time_req,
gss_OID_set desired_mechs,
gss_cred_usage_t cred_usage,
gss_cred_id_t *output_cred_handle,
gss_OID_set *actual_mechs,
OM_uint32 *time_rec)
{
return spnego_gss_acquire_cred_from(minor_status, desired_name, time_req,
desired_mechs, cred_usage, NULL,
output_cred_handle, actual_mechs,
time_rec);
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_acquire_cred_from(OM_uint32 *minor_status,
const gss_name_t desired_name,
OM_uint32 time_req,
const gss_OID_set desired_mechs,
gss_cred_usage_t cred_usage,
gss_const_key_value_set_t cred_store,
gss_cred_id_t *output_cred_handle,
gss_OID_set *actual_mechs,
OM_uint32 *time_rec)
{
OM_uint32 status, tmpmin;
gss_OID_set amechs;
gss_cred_id_t mcred = NULL;
spnego_gss_cred_id_t spcred = NULL;
dsyslog("Entering spnego_gss_acquire_cred\n");
if (actual_mechs)
*actual_mechs = NULL;
if (time_rec)
*time_rec = 0;
/* We will obtain a mechglue credential and wrap it in a
* spnego_gss_cred_id_rec structure. Allocate the wrapper. */
spcred = malloc(sizeof(spnego_gss_cred_id_rec));
if (spcred == NULL) {
*minor_status = ENOMEM;
return (GSS_S_FAILURE);
}
spcred->neg_mechs = GSS_C_NULL_OID_SET;
/*
* Always use get_available_mechs to collect a list of
* mechs for which creds are available.
*/
status = get_available_mechs(minor_status, desired_name,
cred_usage, cred_store, &mcred,
&amechs);
if (actual_mechs && amechs != GSS_C_NULL_OID_SET) {
(void) gssint_copy_oid_set(&tmpmin, amechs, actual_mechs);
}
(void) gss_release_oid_set(&tmpmin, &amechs);
if (status == GSS_S_COMPLETE) {
spcred->mcred = mcred;
*output_cred_handle = (gss_cred_id_t)spcred;
} else {
free(spcred);
*output_cred_handle = GSS_C_NO_CREDENTIAL;
}
dsyslog("Leaving spnego_gss_acquire_cred\n");
return (status);
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_release_cred(OM_uint32 *minor_status,
gss_cred_id_t *cred_handle)
{
spnego_gss_cred_id_t spcred = NULL;
dsyslog("Entering spnego_gss_release_cred\n");
if (minor_status == NULL || cred_handle == NULL)
return (GSS_S_CALL_INACCESSIBLE_WRITE);
*minor_status = 0;
if (*cred_handle == GSS_C_NO_CREDENTIAL)
return (GSS_S_COMPLETE);
spcred = (spnego_gss_cred_id_t)*cred_handle;
*cred_handle = GSS_C_NO_CREDENTIAL;
gss_release_oid_set(minor_status, &spcred->neg_mechs);
gss_release_cred(minor_status, &spcred->mcred);
free(spcred);
dsyslog("Leaving spnego_gss_release_cred\n");
return (GSS_S_COMPLETE);
}
static void
check_spnego_options(spnego_gss_ctx_id_t spnego_ctx)
{
spnego_ctx->optionStr = gssint_get_modOptions(
(const gss_OID)&spnego_oids[0]);
}
static spnego_gss_ctx_id_t
create_spnego_ctx(void)
{
spnego_gss_ctx_id_t spnego_ctx = NULL;
spnego_ctx = (spnego_gss_ctx_id_t)
malloc(sizeof (spnego_gss_ctx_id_rec));
if (spnego_ctx == NULL) {
return (NULL);
}
spnego_ctx->magic_num = SPNEGO_MAGIC_ID;
spnego_ctx->ctx_handle = GSS_C_NO_CONTEXT;
spnego_ctx->mech_set = NULL;
spnego_ctx->internal_mech = NULL;
spnego_ctx->optionStr = NULL;
spnego_ctx->DER_mechTypes.length = 0;
spnego_ctx->DER_mechTypes.value = NULL;
spnego_ctx->default_cred = GSS_C_NO_CREDENTIAL;
spnego_ctx->mic_reqd = 0;
spnego_ctx->mic_sent = 0;
spnego_ctx->mic_rcvd = 0;
spnego_ctx->mech_complete = 0;
spnego_ctx->nego_done = 0;
spnego_ctx->internal_name = GSS_C_NO_NAME;
spnego_ctx->actual_mech = GSS_C_NO_OID;
check_spnego_options(spnego_ctx);
return (spnego_ctx);
}
/* iso(1) org(3) dod(6) internet(1) private(4) enterprises(1) samba(7165)
* gssntlmssp(655) controls(1) spnego_req_mechlistMIC(2) */
static const gss_OID_desc spnego_req_mechlistMIC_oid =
{ 11, "\x2B\x06\x01\x04\x01\xB7\x7D\x85\x0F\x01\x02" };
/*
* Return nonzero if the mechanism has reason to believe that a mechlistMIC
* exchange will be required. Microsoft servers erroneously require SPNEGO
* mechlistMIC if they see an internal MIC within an NTLMSSP Authenticate
* message, even if NTLMSSP was the preferred mechanism.
*/
static int
mech_requires_mechlistMIC(spnego_gss_ctx_id_t sc)
{
OM_uint32 major, minor;
gss_ctx_id_t ctx = sc->ctx_handle;
gss_OID oid = (gss_OID)&spnego_req_mechlistMIC_oid;
gss_buffer_set_t bufs;
int result;
major = gss_inquire_sec_context_by_oid(&minor, ctx, oid, &bufs);
if (major != GSS_S_COMPLETE)
return 0;
/* Report true if the mech returns a single buffer containing a single
* byte with value 1. */
result = (bufs != NULL && bufs->count == 1 &&
bufs->elements[0].length == 1 &&
memcmp(bufs->elements[0].value, "\1", 1) == 0);
(void) gss_release_buffer_set(&minor, &bufs);
return result;
}
/*
* Both initiator and acceptor call here to verify and/or create mechListMIC,
* and to consistency-check the MIC state. handle_mic is invoked only if the
* negotiated mech has completed and supports MICs.
*/
static OM_uint32
handle_mic(OM_uint32 *minor_status, gss_buffer_t mic_in,
int send_mechtok, spnego_gss_ctx_id_t sc,
gss_buffer_t *mic_out,
OM_uint32 *negState, send_token_flag *tokflag)
{
OM_uint32 ret;
ret = GSS_S_FAILURE;
*mic_out = GSS_C_NO_BUFFER;
if (mic_in != GSS_C_NO_BUFFER) {
if (sc->mic_rcvd) {
/* Reject MIC if we've already received a MIC. */
*negState = REJECT;
*tokflag = ERROR_TOKEN_SEND;
return GSS_S_DEFECTIVE_TOKEN;
}
} else if (sc->mic_reqd && !send_mechtok) {
/*
* If the peer sends the final mechanism token, it
* must send the MIC with that token if the
* negotiation requires MICs.
*/
*negState = REJECT;
*tokflag = ERROR_TOKEN_SEND;
return GSS_S_DEFECTIVE_TOKEN;
}
ret = process_mic(minor_status, mic_in, sc, mic_out,
negState, tokflag);
if (ret != GSS_S_COMPLETE) {
return ret;
}
if (sc->mic_reqd) {
assert(sc->mic_sent || sc->mic_rcvd);
}
if (sc->mic_sent && sc->mic_rcvd) {
ret = GSS_S_COMPLETE;
*negState = ACCEPT_COMPLETE;
if (*mic_out == GSS_C_NO_BUFFER) {
/*
* We sent a MIC on the previous pass; we
* shouldn't be sending a mechanism token.
*/
assert(!send_mechtok);
*tokflag = NO_TOKEN_SEND;
} else {
*tokflag = CONT_TOKEN_SEND;
}
} else if (sc->mic_reqd) {
*negState = ACCEPT_INCOMPLETE;
ret = GSS_S_CONTINUE_NEEDED;
} else if (*negState == ACCEPT_COMPLETE) {
ret = GSS_S_COMPLETE;
} else {
ret = GSS_S_CONTINUE_NEEDED;
}
return ret;
}
/*
* Perform the actual verification and/or generation of mechListMIC.
*/
static OM_uint32
process_mic(OM_uint32 *minor_status, gss_buffer_t mic_in,
spnego_gss_ctx_id_t sc, gss_buffer_t *mic_out,
OM_uint32 *negState, send_token_flag *tokflag)
{
OM_uint32 ret, tmpmin;
gss_qop_t qop_state;
gss_buffer_desc tmpmic = GSS_C_EMPTY_BUFFER;
ret = GSS_S_FAILURE;
if (mic_in != GSS_C_NO_BUFFER) {
ret = gss_verify_mic(minor_status, sc->ctx_handle,
&sc->DER_mechTypes,
mic_in, &qop_state);
if (ret != GSS_S_COMPLETE) {
*negState = REJECT;
*tokflag = ERROR_TOKEN_SEND;
return ret;
}
/* If we got a MIC, we must send a MIC. */
sc->mic_reqd = 1;
sc->mic_rcvd = 1;
}
if (sc->mic_reqd && !sc->mic_sent) {
ret = gss_get_mic(minor_status, sc->ctx_handle,
GSS_C_QOP_DEFAULT,
&sc->DER_mechTypes,
&tmpmic);
if (ret != GSS_S_COMPLETE) {
gss_release_buffer(&tmpmin, &tmpmic);
*tokflag = NO_TOKEN_SEND;
return ret;
}
*mic_out = malloc(sizeof(gss_buffer_desc));
if (*mic_out == GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, &tmpmic);
*tokflag = NO_TOKEN_SEND;
return GSS_S_FAILURE;
}
**mic_out = tmpmic;
sc->mic_sent = 1;
}
return GSS_S_COMPLETE;
}
/*
* Initial call to spnego_gss_init_sec_context().
*/
static OM_uint32
init_ctx_new(OM_uint32 *minor_status,
spnego_gss_cred_id_t spcred,
gss_ctx_id_t *ctx,
send_token_flag *tokflag)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = NULL;
sc = create_spnego_ctx();
if (sc == NULL)
return GSS_S_FAILURE;
/* determine negotiation mech set */
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE,
&sc->mech_set);
if (ret != GSS_S_COMPLETE)
goto cleanup;
/* Set an initial internal mech to make the first context token. */
sc->internal_mech = &sc->mech_set->elements[0];
if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
/*
* The actual context is not yet determined, set the output
* context handle to refer to the spnego context itself.
*/
sc->ctx_handle = GSS_C_NO_CONTEXT;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
*tokflag = INIT_TOKEN_SEND;
ret = GSS_S_CONTINUE_NEEDED;
cleanup:
release_spnego_ctx(&sc);
return ret;
}
/*
* Called by second and later calls to spnego_gss_init_sec_context()
* to decode reply and update state.
*/
static OM_uint32
init_ctx_cont(OM_uint32 *minor_status, gss_ctx_id_t *ctx, gss_buffer_t buf,
gss_buffer_t *responseToken, gss_buffer_t *mechListMIC,
OM_uint32 *negState, send_token_flag *tokflag)
{
OM_uint32 ret, tmpmin, acc_negState;
unsigned char *ptr;
spnego_gss_ctx_id_t sc;
gss_OID supportedMech = GSS_C_NO_OID;
sc = (spnego_gss_ctx_id_t)*ctx;
*negState = REJECT;
*tokflag = ERROR_TOKEN_SEND;
ptr = buf->value;
ret = get_negTokenResp(minor_status, ptr, buf->length,
&acc_negState, &supportedMech,
responseToken, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
if (acc_negState == REJECT) {
*minor_status = ERR_SPNEGO_NEGOTIATION_FAILED;
map_errcode(minor_status);
*tokflag = NO_TOKEN_SEND;
ret = GSS_S_FAILURE;
goto cleanup;
}
/*
* nego_done is false for the first call to init_ctx_cont()
*/
if (!sc->nego_done) {
ret = init_ctx_nego(minor_status, sc,
acc_negState,
supportedMech, responseToken,
mechListMIC,
negState, tokflag);
} else if ((!sc->mech_complete && *responseToken == GSS_C_NO_BUFFER) ||
(sc->mech_complete && *responseToken != GSS_C_NO_BUFFER)) {
/* Missing or spurious token from acceptor. */
ret = GSS_S_DEFECTIVE_TOKEN;
} else if (!sc->mech_complete ||
(sc->mic_reqd &&
(sc->ctx_flags & GSS_C_INTEG_FLAG))) {
/* Not obviously done; we may decide we're done later in
* init_ctx_call_init or handle_mic. */
*negState = ACCEPT_INCOMPLETE;
*tokflag = CONT_TOKEN_SEND;
ret = GSS_S_CONTINUE_NEEDED;
} else {
/* mech finished on last pass and no MIC required, so done. */
*negState = ACCEPT_COMPLETE;
*tokflag = NO_TOKEN_SEND;
ret = GSS_S_COMPLETE;
}
cleanup:
if (supportedMech != GSS_C_NO_OID)
generic_gss_release_oid(&tmpmin, &supportedMech);
return ret;
}
/*
* Consistency checking and mechanism negotiation handling for second
* call of spnego_gss_init_sec_context(). Call init_ctx_reselect() to
* update internal state if acceptor has counter-proposed.
*/
static OM_uint32
init_ctx_nego(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc,
OM_uint32 acc_negState, gss_OID supportedMech,
gss_buffer_t *responseToken, gss_buffer_t *mechListMIC,
OM_uint32 *negState, send_token_flag *tokflag)
{
OM_uint32 ret;
*negState = REJECT;
*tokflag = ERROR_TOKEN_SEND;
ret = GSS_S_DEFECTIVE_TOKEN;
/*
* Both supportedMech and negState must be present in first
* acceptor token.
*/
if (supportedMech == GSS_C_NO_OID) {
*minor_status = ERR_SPNEGO_NO_MECH_FROM_ACCEPTOR;
map_errcode(minor_status);
return GSS_S_DEFECTIVE_TOKEN;
}
if (acc_negState == ACCEPT_DEFECTIVE_TOKEN) {
*minor_status = ERR_SPNEGO_NEGOTIATION_FAILED;
map_errcode(minor_status);
return GSS_S_DEFECTIVE_TOKEN;
}
/*
* If the mechanism we sent is not the mechanism returned from
* the server, we need to handle the server's counter
* proposal. There is a bug in SAMBA servers that always send
* the old Kerberos mech OID, even though we sent the new one.
* So we will treat all the Kerberos mech OIDS as the same.
*/
if (!(is_kerb_mech(supportedMech) &&
is_kerb_mech(sc->internal_mech)) &&
!g_OID_equal(supportedMech, sc->internal_mech)) {
ret = init_ctx_reselect(minor_status, sc,
acc_negState, supportedMech,
responseToken, mechListMIC,
negState, tokflag);
} else if (*responseToken == GSS_C_NO_BUFFER) {
if (sc->mech_complete) {
/*
* Mech completed on first call to its
* init_sec_context(). Acceptor sends no mech
* token.
*/
*negState = ACCEPT_COMPLETE;
*tokflag = NO_TOKEN_SEND;
ret = GSS_S_COMPLETE;
} else {
/*
* Reject missing mech token when optimistic
* mech selected.
*/
*minor_status = ERR_SPNEGO_NO_TOKEN_FROM_ACCEPTOR;
map_errcode(minor_status);
ret = GSS_S_DEFECTIVE_TOKEN;
}
} else if ((*responseToken)->length == 0 && sc->mech_complete) {
/* Handle old IIS servers returning empty token instead of
* null tokens in the non-mutual auth case. */
*negState = ACCEPT_COMPLETE;
*tokflag = NO_TOKEN_SEND;
ret = GSS_S_COMPLETE;
} else if (sc->mech_complete) {
/* Reject spurious mech token. */
ret = GSS_S_DEFECTIVE_TOKEN;
} else {
*negState = ACCEPT_INCOMPLETE;
*tokflag = CONT_TOKEN_SEND;
ret = GSS_S_CONTINUE_NEEDED;
}
sc->nego_done = 1;
return ret;
}
/*
* Handle acceptor's counter-proposal of an alternative mechanism.
*/
static OM_uint32
init_ctx_reselect(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc,
OM_uint32 acc_negState, gss_OID supportedMech,
gss_buffer_t *responseToken, gss_buffer_t *mechListMIC,
OM_uint32 *negState, send_token_flag *tokflag)
{
OM_uint32 tmpmin;
size_t i;
gss_delete_sec_context(&tmpmin, &sc->ctx_handle,
GSS_C_NO_BUFFER);
/* Find supportedMech in sc->mech_set. */
for (i = 0; i < sc->mech_set->count; i++) {
if (g_OID_equal(supportedMech, &sc->mech_set->elements[i]))
break;
}
if (i == sc->mech_set->count)
return GSS_S_DEFECTIVE_TOKEN;
sc->internal_mech = &sc->mech_set->elements[i];
/*
* Windows 2003 and earlier don't correctly send a
* negState of request-mic when counter-proposing a
* mechanism. They probably don't handle mechListMICs
* properly either.
*/
if (acc_negState != REQUEST_MIC)
return GSS_S_DEFECTIVE_TOKEN;
sc->mech_complete = 0;
sc->mic_reqd = 1;
*negState = REQUEST_MIC;
*tokflag = CONT_TOKEN_SEND;
return GSS_S_CONTINUE_NEEDED;
}
/*
* Wrap call to mechanism gss_init_sec_context() and update state
* accordingly.
*/
static OM_uint32
init_ctx_call_init(OM_uint32 *minor_status,
spnego_gss_ctx_id_t sc,
spnego_gss_cred_id_t spcred,
gss_name_t target_name,
OM_uint32 req_flags,
OM_uint32 time_req,
gss_buffer_t mechtok_in,
gss_OID *actual_mech,
gss_buffer_t mechtok_out,
OM_uint32 *ret_flags,
OM_uint32 *time_rec,
OM_uint32 *negState,
send_token_flag *send_token)
{
OM_uint32 ret, tmpret, tmpmin;
gss_cred_id_t mcred;
mcred = (spcred == NULL) ? GSS_C_NO_CREDENTIAL : spcred->mcred;
ret = gss_init_sec_context(minor_status,
mcred,
&sc->ctx_handle,
target_name,
sc->internal_mech,
(req_flags | GSS_C_INTEG_FLAG),
time_req,
GSS_C_NO_CHANNEL_BINDINGS,
mechtok_in,
&sc->actual_mech,
mechtok_out,
&sc->ctx_flags,
time_rec);
if (ret == GSS_S_COMPLETE) {
sc->mech_complete = 1;
if (ret_flags != NULL)
*ret_flags = sc->ctx_flags;
/*
* Microsoft SPNEGO implementations expect an even number of
* token exchanges. So if we're sending a final token, ask for
* a zero-length token back from the server. Also ask for a
* token back if this is the first token or if a MIC exchange
* is required.
*/
if (*send_token == CONT_TOKEN_SEND &&
mechtok_out->length == 0 &&
(!sc->mic_reqd ||
!(sc->ctx_flags & GSS_C_INTEG_FLAG))) {
/* The exchange is complete. */
*negState = ACCEPT_COMPLETE;
ret = GSS_S_COMPLETE;
*send_token = NO_TOKEN_SEND;
} else {
/* Ask for one more hop. */
*negState = ACCEPT_INCOMPLETE;
ret = GSS_S_CONTINUE_NEEDED;
}
return ret;
}
if (ret == GSS_S_CONTINUE_NEEDED)
return ret;
if (*send_token != INIT_TOKEN_SEND) {
*send_token = ERROR_TOKEN_SEND;
*negState = REJECT;
return ret;
}
/*
* Since this is the first token, we can fall back to later mechanisms
* in the list. Since the mechanism list is expected to be short, we
* can do this with recursion. If all mechanisms produce errors, the
* caller should get the error from the first mech in the list.
*/
gssalloc_free(sc->mech_set->elements->elements);
memmove(sc->mech_set->elements, sc->mech_set->elements + 1,
--sc->mech_set->count * sizeof(*sc->mech_set->elements));
if (sc->mech_set->count == 0)
goto fail;
gss_release_buffer(&tmpmin, &sc->DER_mechTypes);
if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0)
goto fail;
tmpret = init_ctx_call_init(&tmpmin, sc, spcred, target_name,
req_flags, time_req, mechtok_in,
actual_mech, mechtok_out, ret_flags,
time_rec, negState, send_token);
if (HARD_ERROR(tmpret))
goto fail;
*minor_status = tmpmin;
return tmpret;
fail:
/* Don't output token on error from first call. */
*send_token = NO_TOKEN_SEND;
*negState = REJECT;
return ret;
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_init_sec_context(
OM_uint32 *minor_status,
gss_cred_id_t claimant_cred_handle,
gss_ctx_id_t *context_handle,
gss_name_t target_name,
gss_OID mech_type,
OM_uint32 req_flags,
OM_uint32 time_req,
gss_channel_bindings_t input_chan_bindings,
gss_buffer_t input_token,
gss_OID *actual_mech,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec)
{
send_token_flag send_token = NO_TOKEN_SEND;
OM_uint32 tmpmin, ret, negState;
gss_buffer_t mechtok_in, mechListMIC_in, mechListMIC_out;
gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER;
spnego_gss_cred_id_t spcred = NULL;
spnego_gss_ctx_id_t spnego_ctx = NULL;
dsyslog("Entering init_sec_context\n");
mechtok_in = mechListMIC_out = mechListMIC_in = GSS_C_NO_BUFFER;
negState = REJECT;
/*
* This function works in three steps:
*
* 1. Perform mechanism negotiation.
* 2. Invoke the negotiated or optimistic mech's gss_init_sec_context
* function and examine the results.
* 3. Process or generate MICs if necessary.
*
* The three steps share responsibility for determining when the
* exchange is complete. If the selected mech completed in a previous
* call and no MIC exchange is expected, then step 1 will decide. If
* the selected mech completes in this call and no MIC exchange is
* expected, then step 2 will decide. If a MIC exchange is expected,
* then step 3 will decide. If an error occurs in any step, the
* exchange will be aborted, possibly with an error token.
*
* negState determines the state of the negotiation, and is
* communicated to the acceptor if a continuing token is sent.
* send_token is used to indicate what type of token, if any, should be
* generated.
*/
/* Validate arguments. */
if (minor_status != NULL)
*minor_status = 0;
if (output_token != GSS_C_NO_BUFFER) {
output_token->length = 0;
output_token->value = NULL;
}
if (minor_status == NULL ||
output_token == GSS_C_NO_BUFFER ||
context_handle == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
if (actual_mech != NULL)
*actual_mech = GSS_C_NO_OID;
/* Step 1: perform mechanism negotiation. */
spcred = (spnego_gss_cred_id_t)claimant_cred_handle;
if (*context_handle == GSS_C_NO_CONTEXT) {
ret = init_ctx_new(minor_status, spcred,
context_handle, &send_token);
if (ret != GSS_S_CONTINUE_NEEDED) {
goto cleanup;
}
} else {
ret = init_ctx_cont(minor_status, context_handle,
input_token, &mechtok_in,
&mechListMIC_in, &negState, &send_token);
if (HARD_ERROR(ret)) {
goto cleanup;
}
}
/* Step 2: invoke the selected or optimistic mechanism's
* gss_init_sec_context function, if it didn't complete previously. */
spnego_ctx = (spnego_gss_ctx_id_t)*context_handle;
if (!spnego_ctx->mech_complete) {
ret = init_ctx_call_init(
minor_status, spnego_ctx, spcred,
target_name, req_flags,
time_req, mechtok_in,
actual_mech, &mechtok_out,
ret_flags, time_rec,
&negState, &send_token);
/* Give the mechanism a chance to force a mechlistMIC. */
if (!HARD_ERROR(ret) && mech_requires_mechlistMIC(spnego_ctx))
spnego_ctx->mic_reqd = 1;
}
/* Step 3: process or generate the MIC, if the negotiated mech is
* complete and supports MICs. */
if (!HARD_ERROR(ret) && spnego_ctx->mech_complete &&
(spnego_ctx->ctx_flags & GSS_C_INTEG_FLAG)) {
ret = handle_mic(minor_status,
mechListMIC_in,
(mechtok_out.length != 0),
spnego_ctx, &mechListMIC_out,
&negState, &send_token);
}
cleanup:
if (send_token == INIT_TOKEN_SEND) {
if (make_spnego_tokenInit_msg(spnego_ctx,
0,
mechListMIC_out,
req_flags,
&mechtok_out, send_token,
output_token) < 0) {
ret = GSS_S_FAILURE;
}
} else if (send_token != NO_TOKEN_SEND) {
if (make_spnego_tokenTarg_msg(negState, GSS_C_NO_OID,
&mechtok_out, mechListMIC_out,
send_token,
output_token) < 0) {
ret = GSS_S_FAILURE;
}
}
gss_release_buffer(&tmpmin, &mechtok_out);
if (ret == GSS_S_COMPLETE) {
/*
* Now, switch the output context to refer to the
* negotiated mechanism's context.
*/
*context_handle = (gss_ctx_id_t)spnego_ctx->ctx_handle;
if (actual_mech != NULL)
*actual_mech = spnego_ctx->actual_mech;
if (ret_flags != NULL)
*ret_flags = spnego_ctx->ctx_flags;
release_spnego_ctx(&spnego_ctx);
} else if (ret != GSS_S_CONTINUE_NEEDED) {
if (spnego_ctx != NULL) {
gss_delete_sec_context(&tmpmin,
&spnego_ctx->ctx_handle,
GSS_C_NO_BUFFER);
release_spnego_ctx(&spnego_ctx);
}
*context_handle = GSS_C_NO_CONTEXT;
}
if (mechtok_in != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mechtok_in);
free(mechtok_in);
}
if (mechListMIC_in != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mechListMIC_in);
free(mechListMIC_in);
}
if (mechListMIC_out != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mechListMIC_out);
free(mechListMIC_out);
}
return ret;
} /* init_sec_context */
/* We don't want to import KRB5 headers here */
static const gss_OID_desc gss_mech_krb5_oid =
{ 9, "\052\206\110\206\367\022\001\002\002" };
static const gss_OID_desc gss_mech_krb5_wrong_oid =
{ 9, "\052\206\110\202\367\022\001\002\002" };
/*
* verify that the input token length is not 0. If it is, just return.
* If the token length is greater than 0, der encode as a sequence
* and place in buf_out, advancing buf_out.
*/
static int
put_neg_hints(unsigned char **buf_out, gss_buffer_t input_token,
unsigned int buflen)
{
int ret;
/* if token length is 0, we do not want to send */
if (input_token->length == 0)
return (0);
if (input_token->length > buflen)
return (-1);
*(*buf_out)++ = SEQUENCE;
if ((ret = gssint_put_der_length(input_token->length, buf_out,
input_token->length)))
return (ret);
TWRITE_STR(*buf_out, input_token->value, input_token->length);
return (0);
}
/*
* NegHints ::= SEQUENCE {
* hintName [0] GeneralString OPTIONAL,
* hintAddress [1] OCTET STRING OPTIONAL
* }
*/
#define HOST_PREFIX "host@"
#define HOST_PREFIX_LEN (sizeof(HOST_PREFIX) - 1)
static int
make_NegHints(OM_uint32 *minor_status,
spnego_gss_cred_id_t spcred, gss_buffer_t *outbuf)
{
gss_buffer_desc hintNameBuf;
gss_name_t hintName = GSS_C_NO_NAME;
gss_name_t hintKerberosName;
gss_OID hintNameType;
OM_uint32 major_status;
OM_uint32 minor;
unsigned int tlen = 0;
unsigned int hintNameSize = 0;
unsigned char *ptr;
unsigned char *t;
*outbuf = GSS_C_NO_BUFFER;
if (spcred != NULL) {
major_status = gss_inquire_cred(minor_status,
spcred->mcred,
&hintName,
NULL,
NULL,
NULL);
if (major_status != GSS_S_COMPLETE)
return (major_status);
}
if (hintName == GSS_C_NO_NAME) {
krb5_error_code code;
krb5int_access kaccess;
char hostname[HOST_PREFIX_LEN + MAXHOSTNAMELEN + 1] = HOST_PREFIX;
code = krb5int_accessor(&kaccess, KRB5INT_ACCESS_VERSION);
if (code != 0) {
*minor_status = code;
return (GSS_S_FAILURE);
}
/* this breaks mutual authentication but Samba relies on it */
code = (*kaccess.clean_hostname)(NULL, NULL,
&hostname[HOST_PREFIX_LEN],
MAXHOSTNAMELEN);
if (code != 0) {
*minor_status = code;
return (GSS_S_FAILURE);
}
hintNameBuf.value = hostname;
hintNameBuf.length = strlen(hostname);
major_status = gss_import_name(minor_status,
&hintNameBuf,
GSS_C_NT_HOSTBASED_SERVICE,
&hintName);
if (major_status != GSS_S_COMPLETE) {
return (major_status);
}
}
hintNameBuf.value = NULL;
hintNameBuf.length = 0;
major_status = gss_canonicalize_name(minor_status,
hintName,
(gss_OID)&gss_mech_krb5_oid,
&hintKerberosName);
if (major_status != GSS_S_COMPLETE) {
gss_release_name(&minor, &hintName);
return (major_status);
}
gss_release_name(&minor, &hintName);
major_status = gss_display_name(minor_status,
hintKerberosName,
&hintNameBuf,
&hintNameType);
if (major_status != GSS_S_COMPLETE) {
gss_release_name(&minor, &hintName);
return (major_status);
}
gss_release_name(&minor, &hintKerberosName);
/*
* Now encode the name hint into a NegHints ASN.1 type
*/
major_status = GSS_S_FAILURE;
/* Length of DER encoded GeneralString */
tlen = 1 + gssint_der_length_size(hintNameBuf.length) +
hintNameBuf.length;
hintNameSize = tlen;
/* Length of DER encoded hintName */
tlen += 1 + gssint_der_length_size(hintNameSize);
t = gssalloc_malloc(tlen);
if (t == NULL) {
*minor_status = ENOMEM;
goto errout;
}
ptr = t;
*ptr++ = CONTEXT | 0x00; /* hintName identifier */
if (gssint_put_der_length(hintNameSize,
&ptr, tlen - (int)(ptr-t)))
goto errout;
*ptr++ = GENERAL_STRING;
if (gssint_put_der_length(hintNameBuf.length,
&ptr, tlen - (int)(ptr-t)))
goto errout;
memcpy(ptr, hintNameBuf.value, hintNameBuf.length);
ptr += hintNameBuf.length;
*outbuf = (gss_buffer_t)malloc(sizeof(gss_buffer_desc));
if (*outbuf == NULL) {
*minor_status = ENOMEM;
goto errout;
}
(*outbuf)->value = (void *)t;
(*outbuf)->length = ptr - t;
t = NULL; /* don't free */
*minor_status = 0;
major_status = GSS_S_COMPLETE;
errout:
if (t != NULL) {
free(t);
}
gss_release_buffer(&minor, &hintNameBuf);
return (major_status);
}
/*
* Support the Microsoft NegHints extension to SPNEGO for compatibility with
* some versions of Samba. See:
* http://msdn.microsoft.com/en-us/library/cc247039(PROT.10).aspx
*/
static OM_uint32
acc_ctx_hints(OM_uint32 *minor_status,
gss_ctx_id_t *ctx,
spnego_gss_cred_id_t spcred,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 tmpmin, ret;
gss_OID_set supported_mechSet;
spnego_gss_ctx_id_t sc = NULL;
*mechListMIC = GSS_C_NO_BUFFER;
supported_mechSet = GSS_C_NO_OID_SET;
*return_token = NO_TOKEN_SEND;
*negState = REJECT;
*minor_status = 0;
/* A hint request must be the first token received. */
if (*ctx != GSS_C_NO_CONTEXT)
return GSS_S_DEFECTIVE_TOKEN;
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT,
&supported_mechSet);
if (ret != GSS_S_COMPLETE)
goto cleanup;
ret = make_NegHints(minor_status, spcred, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
sc = create_spnego_ctx();
if (sc == NULL) {
ret = GSS_S_FAILURE;
goto cleanup;
}
if (put_mech_set(supported_mechSet, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
sc->internal_mech = GSS_C_NO_OID;
*negState = ACCEPT_INCOMPLETE;
*return_token = INIT_TOKEN_SEND;
sc->firstpass = 1;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
ret = GSS_S_COMPLETE;
cleanup:
release_spnego_ctx(&sc);
gss_release_oid_set(&tmpmin, &supported_mechSet);
return ret;
}
/*
* Set negState to REJECT if the token is defective, else
* ACCEPT_INCOMPLETE or REQUEST_MIC, depending on whether initiator's
* preferred mechanism is supported.
*/
static OM_uint32
acc_ctx_new(OM_uint32 *minor_status,
gss_buffer_t buf,
gss_ctx_id_t *ctx,
spnego_gss_cred_id_t spcred,
gss_buffer_t *mechToken,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 tmpmin, ret, req_flags;
gss_OID_set supported_mechSet, mechTypes;
gss_buffer_desc der_mechTypes;
gss_OID mech_wanted;
spnego_gss_ctx_id_t sc = NULL;
ret = GSS_S_DEFECTIVE_TOKEN;
der_mechTypes.length = 0;
der_mechTypes.value = NULL;
*mechToken = *mechListMIC = GSS_C_NO_BUFFER;
supported_mechSet = mechTypes = GSS_C_NO_OID_SET;
*return_token = ERROR_TOKEN_SEND;
*negState = REJECT;
*minor_status = 0;
ret = get_negTokenInit(minor_status, buf, &der_mechTypes,
&mechTypes, &req_flags,
mechToken, mechListMIC);
if (ret != GSS_S_COMPLETE) {
goto cleanup;
}
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT,
&supported_mechSet);
if (ret != GSS_S_COMPLETE) {
*return_token = NO_TOKEN_SEND;
goto cleanup;
}
/*
* Select the best match between the list of mechs
* that the initiator requested and the list that
* the acceptor will support.
*/
mech_wanted = negotiate_mech(supported_mechSet, mechTypes, negState);
if (*negState == REJECT) {
ret = GSS_S_BAD_MECH;
goto cleanup;
}
sc = (spnego_gss_ctx_id_t)*ctx;
if (sc != NULL) {
gss_release_buffer(&tmpmin, &sc->DER_mechTypes);
assert(mech_wanted != GSS_C_NO_OID);
} else
sc = create_spnego_ctx();
if (sc == NULL) {
ret = GSS_S_FAILURE;
*return_token = NO_TOKEN_SEND;
goto cleanup;
}
sc->mech_set = mechTypes;
mechTypes = GSS_C_NO_OID_SET;
sc->internal_mech = mech_wanted;
sc->DER_mechTypes = der_mechTypes;
der_mechTypes.length = 0;
der_mechTypes.value = NULL;
if (*negState == REQUEST_MIC)
sc->mic_reqd = 1;
*return_token = INIT_TOKEN_SEND;
sc->firstpass = 1;
*ctx = (gss_ctx_id_t)sc;
ret = GSS_S_COMPLETE;
cleanup:
gss_release_oid_set(&tmpmin, &mechTypes);
gss_release_oid_set(&tmpmin, &supported_mechSet);
if (der_mechTypes.length != 0)
gss_release_buffer(&tmpmin, &der_mechTypes);
return ret;
}
static OM_uint32
acc_ctx_cont(OM_uint32 *minstat,
gss_buffer_t buf,
gss_ctx_id_t *ctx,
gss_buffer_t *responseToken,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 ret, tmpmin;
gss_OID supportedMech;
spnego_gss_ctx_id_t sc;
unsigned int len;
unsigned char *ptr, *bufstart;
sc = (spnego_gss_ctx_id_t)*ctx;
ret = GSS_S_DEFECTIVE_TOKEN;
*negState = REJECT;
*minstat = 0;
supportedMech = GSS_C_NO_OID;
*return_token = ERROR_TOKEN_SEND;
*responseToken = *mechListMIC = GSS_C_NO_BUFFER;
ptr = bufstart = buf->value;
#define REMAIN (buf->length - (ptr - bufstart))
if (REMAIN == 0 || REMAIN > INT_MAX)
return GSS_S_DEFECTIVE_TOKEN;
/*
* Attempt to work with old Sun SPNEGO.
*/
if (*ptr == HEADER_ID) {
ret = g_verify_token_header(gss_mech_spnego,
&len, &ptr, 0, REMAIN);
if (ret) {
*minstat = ret;
return GSS_S_DEFECTIVE_TOKEN;
}
}
if (*ptr != (CONTEXT | 0x01)) {
return GSS_S_DEFECTIVE_TOKEN;
}
ret = get_negTokenResp(minstat, ptr, REMAIN,
negState, &supportedMech,
responseToken, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
if (*responseToken == GSS_C_NO_BUFFER &&
*mechListMIC == GSS_C_NO_BUFFER) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
if (supportedMech != GSS_C_NO_OID) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
sc->firstpass = 0;
*negState = ACCEPT_INCOMPLETE;
*return_token = CONT_TOKEN_SEND;
cleanup:
if (supportedMech != GSS_C_NO_OID) {
generic_gss_release_oid(&tmpmin, &supportedMech);
}
return ret;
#undef REMAIN
}
/*
* Verify that mech OID is either exactly the same as the negotiated
* mech OID, or is a mech OID supported by the negotiated mech. MS
* implementations can list a most preferred mech using an incorrect
* krb5 OID while emitting a krb5 initiator mech token having the
* correct krb5 mech OID.
*/
static OM_uint32
acc_ctx_vfy_oid(OM_uint32 *minor_status,
spnego_gss_ctx_id_t sc, gss_OID mechoid,
OM_uint32 *negState, send_token_flag *tokflag)
{
OM_uint32 ret, tmpmin;
gss_mechanism mech = NULL;
gss_OID_set mech_set = GSS_C_NO_OID_SET;
int present = 0;
if (g_OID_equal(sc->internal_mech, mechoid))
return GSS_S_COMPLETE;
mech = gssint_get_mechanism(sc->internal_mech);
if (mech == NULL || mech->gss_indicate_mechs == NULL) {
*minor_status = ERR_SPNEGO_NEGOTIATION_FAILED;
map_errcode(minor_status);
*negState = REJECT;
*tokflag = ERROR_TOKEN_SEND;
return GSS_S_BAD_MECH;
}
ret = mech->gss_indicate_mechs(minor_status, &mech_set);
if (ret != GSS_S_COMPLETE) {
*tokflag = NO_TOKEN_SEND;
map_error(minor_status, mech);
goto cleanup;
}
ret = gss_test_oid_set_member(minor_status, mechoid,
mech_set, &present);
if (ret != GSS_S_COMPLETE)
goto cleanup;
if (!present) {
*minor_status = ERR_SPNEGO_NEGOTIATION_FAILED;
map_errcode(minor_status);
*negState = REJECT;
*tokflag = ERROR_TOKEN_SEND;
ret = GSS_S_BAD_MECH;
}
cleanup:
gss_release_oid_set(&tmpmin, &mech_set);
return ret;
}
#ifndef LEAN_CLIENT
/*
* Wrap call to gss_accept_sec_context() and update state
* accordingly.
*/
static OM_uint32
acc_ctx_call_acc(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc,
spnego_gss_cred_id_t spcred, gss_buffer_t mechtok_in,
gss_OID *mech_type, gss_buffer_t mechtok_out,
OM_uint32 *ret_flags, OM_uint32 *time_rec,
gss_cred_id_t *delegated_cred_handle,
OM_uint32 *negState, send_token_flag *tokflag)
{
OM_uint32 ret;
gss_OID_desc mechoid;
gss_cred_id_t mcred;
if (sc->ctx_handle == GSS_C_NO_CONTEXT) {
/*
* mechoid is an alias; don't free it.
*/
ret = gssint_get_mech_type(&mechoid, mechtok_in);
if (ret != GSS_S_COMPLETE) {
*tokflag = NO_TOKEN_SEND;
return ret;
}
ret = acc_ctx_vfy_oid(minor_status, sc, &mechoid,
negState, tokflag);
if (ret != GSS_S_COMPLETE)
return ret;
}
mcred = (spcred == NULL) ? GSS_C_NO_CREDENTIAL : spcred->mcred;
ret = gss_accept_sec_context(minor_status,
&sc->ctx_handle,
mcred,
mechtok_in,
GSS_C_NO_CHANNEL_BINDINGS,
&sc->internal_name,
mech_type,
mechtok_out,
&sc->ctx_flags,
time_rec,
delegated_cred_handle);
if (ret == GSS_S_COMPLETE) {
#ifdef MS_BUG_TEST
/*
* Force MIC to be not required even if we previously
* requested a MIC.
*/
char *envstr = getenv("MS_FORCE_NO_MIC");
if (envstr != NULL && strcmp(envstr, "1") == 0 &&
!(sc->ctx_flags & GSS_C_MUTUAL_FLAG) &&
sc->mic_reqd) {
sc->mic_reqd = 0;
}
#endif
sc->mech_complete = 1;
if (ret_flags != NULL)
*ret_flags = sc->ctx_flags;
if (!sc->mic_reqd ||
!(sc->ctx_flags & GSS_C_INTEG_FLAG)) {
/* No MIC exchange required, so we're done. */
*negState = ACCEPT_COMPLETE;
ret = GSS_S_COMPLETE;
} else {
/* handle_mic will decide if we're done. */
ret = GSS_S_CONTINUE_NEEDED;
}
} else if (ret != GSS_S_CONTINUE_NEEDED) {
*negState = REJECT;
*tokflag = ERROR_TOKEN_SEND;
}
return ret;
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_accept_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_cred_id_t verifier_cred_handle,
gss_buffer_t input_token,
gss_channel_bindings_t input_chan_bindings,
gss_name_t *src_name,
gss_OID *mech_type,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec,
gss_cred_id_t *delegated_cred_handle)
{
OM_uint32 ret, tmpmin, negState;
send_token_flag return_token;
gss_buffer_t mechtok_in, mic_in, mic_out;
gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER;
spnego_gss_ctx_id_t sc = NULL;
spnego_gss_cred_id_t spcred = NULL;
int sendTokenInit = 0, tmpret;
mechtok_in = mic_in = mic_out = GSS_C_NO_BUFFER;
/*
* This function works in three steps:
*
* 1. Perform mechanism negotiation.
* 2. Invoke the negotiated mech's gss_accept_sec_context function
* and examine the results.
* 3. Process or generate MICs if necessary.
*
* Step one determines whether the negotiation requires a MIC exchange,
* while steps two and three share responsibility for determining when
* the exchange is complete. If the selected mech completes in this
* call and no MIC exchange is expected, then step 2 will decide. If a
* MIC exchange is expected, then step 3 will decide. If an error
* occurs in any step, the exchange will be aborted, possibly with an
* error token.
*
* negState determines the state of the negotiation, and is
* communicated to the acceptor if a continuing token is sent.
* return_token is used to indicate what type of token, if any, should
* be generated.
*/
/* Validate arguments. */
if (minor_status != NULL)
*minor_status = 0;
if (output_token != GSS_C_NO_BUFFER) {
output_token->length = 0;
output_token->value = NULL;
}
if (minor_status == NULL ||
output_token == GSS_C_NO_BUFFER ||
context_handle == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
if (input_token == GSS_C_NO_BUFFER)
return GSS_S_CALL_INACCESSIBLE_READ;
/* Step 1: Perform mechanism negotiation. */
sc = (spnego_gss_ctx_id_t)*context_handle;
spcred = (spnego_gss_cred_id_t)verifier_cred_handle;
if (sc == NULL || sc->internal_mech == GSS_C_NO_OID) {
/* Process an initial token or request for NegHints. */
if (src_name != NULL)
*src_name = GSS_C_NO_NAME;
if (mech_type != NULL)
*mech_type = GSS_C_NO_OID;
if (time_rec != NULL)
*time_rec = 0;
if (ret_flags != NULL)
*ret_flags = 0;
if (delegated_cred_handle != NULL)
*delegated_cred_handle = GSS_C_NO_CREDENTIAL;
if (input_token->length == 0) {
ret = acc_ctx_hints(minor_status,
context_handle, spcred,
&mic_out,
&negState,
&return_token);
if (ret != GSS_S_COMPLETE)
goto cleanup;
sendTokenInit = 1;
ret = GSS_S_CONTINUE_NEEDED;
} else {
/* Can set negState to REQUEST_MIC */
ret = acc_ctx_new(minor_status, input_token,
context_handle, spcred,
&mechtok_in, &mic_in,
&negState, &return_token);
if (ret != GSS_S_COMPLETE)
goto cleanup;
ret = GSS_S_CONTINUE_NEEDED;
}
} else {
/* Process a response token. Can set negState to
* ACCEPT_INCOMPLETE. */
ret = acc_ctx_cont(minor_status, input_token,
context_handle, &mechtok_in,
&mic_in, &negState, &return_token);
if (ret != GSS_S_COMPLETE)
goto cleanup;
ret = GSS_S_CONTINUE_NEEDED;
}
/* Step 2: invoke the negotiated mechanism's gss_accept_sec_context
* function. */
sc = (spnego_gss_ctx_id_t)*context_handle;
/*
* Handle mechtok_in and mic_in only if they are
* present in input_token. If neither is present, whether
* this is an error depends on whether this is the first
* round-trip. RET is set to a default value according to
* whether it is the first round-trip.
*/
if (negState != REQUEST_MIC && mechtok_in != GSS_C_NO_BUFFER) {
ret = acc_ctx_call_acc(minor_status, sc, spcred,
mechtok_in, mech_type, &mechtok_out,
ret_flags, time_rec,
delegated_cred_handle,
&negState, &return_token);
}
/* Step 3: process or generate the MIC, if the negotiated mech is
* complete and supports MICs. */
if (!HARD_ERROR(ret) && sc->mech_complete &&
(sc->ctx_flags & GSS_C_INTEG_FLAG)) {
ret = handle_mic(minor_status, mic_in,
(mechtok_out.length != 0),
sc, &mic_out,
&negState, &return_token);
}
cleanup:
if (return_token == INIT_TOKEN_SEND && sendTokenInit) {
assert(sc != NULL);
tmpret = make_spnego_tokenInit_msg(sc, 1, mic_out, 0,
GSS_C_NO_BUFFER,
return_token, output_token);
if (tmpret < 0)
ret = GSS_S_FAILURE;
} else if (return_token != NO_TOKEN_SEND &&
return_token != CHECK_MIC) {
tmpret = make_spnego_tokenTarg_msg(negState,
sc ? sc->internal_mech :
GSS_C_NO_OID,
&mechtok_out, mic_out,
return_token,
output_token);
if (tmpret < 0)
ret = GSS_S_FAILURE;
}
if (ret == GSS_S_COMPLETE) {
*context_handle = (gss_ctx_id_t)sc->ctx_handle;
if (sc->internal_name != GSS_C_NO_NAME &&
src_name != NULL) {
*src_name = sc->internal_name;
sc->internal_name = GSS_C_NO_NAME;
}
release_spnego_ctx(&sc);
} else if (ret != GSS_S_CONTINUE_NEEDED) {
if (sc != NULL) {
gss_delete_sec_context(&tmpmin, &sc->ctx_handle,
GSS_C_NO_BUFFER);
release_spnego_ctx(&sc);
}
*context_handle = GSS_C_NO_CONTEXT;
}
gss_release_buffer(&tmpmin, &mechtok_out);
if (mechtok_in != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mechtok_in);
free(mechtok_in);
}
if (mic_in != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mic_in);
free(mic_in);
}
if (mic_out != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mic_out);
free(mic_out);
}
return ret;
}
#endif /* LEAN_CLIENT */
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_display_status(
OM_uint32 *minor_status,
OM_uint32 status_value,
int status_type,
gss_OID mech_type,
OM_uint32 *message_context,
gss_buffer_t status_string)
{
OM_uint32 maj = GSS_S_COMPLETE;
int ret;
dsyslog("Entering display_status\n");
*message_context = 0;
switch (status_value) {
case ERR_SPNEGO_NO_MECHS_AVAILABLE:
/* CSTYLED */
*status_string = make_err_msg(_("SPNEGO cannot find "
"mechanisms to negotiate"));
break;
case ERR_SPNEGO_NO_CREDS_ACQUIRED:
/* CSTYLED */
*status_string = make_err_msg(_("SPNEGO failed to acquire "
"creds"));
break;
case ERR_SPNEGO_NO_MECH_FROM_ACCEPTOR:
/* CSTYLED */
*status_string = make_err_msg(_("SPNEGO acceptor did not "
"select a mechanism"));
break;
case ERR_SPNEGO_NEGOTIATION_FAILED:
/* CSTYLED */
*status_string = make_err_msg(_("SPNEGO failed to negotiate a "
"mechanism"));
break;
case ERR_SPNEGO_NO_TOKEN_FROM_ACCEPTOR:
/* CSTYLED */
*status_string = make_err_msg(_("SPNEGO acceptor did not "
"return a valid token"));
break;
default:
/* Not one of our minor codes; might be from a mech. Call back
* to gss_display_status, but first check for recursion. */
if (k5_getspecific(K5_KEY_GSS_SPNEGO_STATUS) != NULL) {
/* Perhaps we returned a com_err code like ENOMEM. */
const char *err = error_message(status_value);
*status_string = make_err_msg(err);
break;
}
/* Set a non-null pointer value; doesn't matter which one. */
ret = k5_setspecific(K5_KEY_GSS_SPNEGO_STATUS, &ret);
if (ret != 0) {
*minor_status = ret;
maj = GSS_S_FAILURE;
break;
}
maj = gss_display_status(minor_status, status_value,
status_type, mech_type,
message_context, status_string);
/* This is unlikely to fail; not much we can do if it does. */
(void)k5_setspecific(K5_KEY_GSS_SPNEGO_STATUS, NULL);
break;
}
dsyslog("Leaving display_status\n");
return maj;
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_import_name(
OM_uint32 *minor_status,
gss_buffer_t input_name_buffer,
gss_OID input_name_type,
gss_name_t *output_name)
{
OM_uint32 status;
dsyslog("Entering import_name\n");
status = gss_import_name(minor_status, input_name_buffer,
input_name_type, output_name);
dsyslog("Leaving import_name\n");
return (status);
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_release_name(
OM_uint32 *minor_status,
gss_name_t *input_name)
{
OM_uint32 status;
dsyslog("Entering release_name\n");
status = gss_release_name(minor_status, input_name);
dsyslog("Leaving release_name\n");
return (status);
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_duplicate_name(
OM_uint32 *minor_status,
const gss_name_t input_name,
gss_name_t *output_name)
{
OM_uint32 status;
dsyslog("Entering duplicate_name\n");
status = gss_duplicate_name(minor_status, input_name, output_name);
dsyslog("Leaving duplicate_name\n");
return (status);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_inquire_cred(
OM_uint32 *minor_status,
gss_cred_id_t cred_handle,
gss_name_t *name,
OM_uint32 *lifetime,
int *cred_usage,
gss_OID_set *mechanisms)
{
OM_uint32 status;
spnego_gss_cred_id_t spcred = NULL;
gss_cred_id_t creds = GSS_C_NO_CREDENTIAL;
OM_uint32 tmp_minor_status;
OM_uint32 initiator_lifetime, acceptor_lifetime;
dsyslog("Entering inquire_cred\n");
/*
* To avoid infinite recursion, if GSS_C_NO_CREDENTIAL is
* supplied we call gss_inquire_cred_by_mech() on the
* first non-SPNEGO mechanism.
*/
spcred = (spnego_gss_cred_id_t)cred_handle;
if (spcred == NULL) {
status = get_available_mechs(minor_status,
GSS_C_NO_NAME,
GSS_C_BOTH,
GSS_C_NO_CRED_STORE,
&creds,
mechanisms);
if (status != GSS_S_COMPLETE) {
dsyslog("Leaving inquire_cred\n");
return (status);
}
if ((*mechanisms)->count == 0) {
gss_release_cred(&tmp_minor_status, &creds);
gss_release_oid_set(&tmp_minor_status, mechanisms);
dsyslog("Leaving inquire_cred\n");
return (GSS_S_DEFECTIVE_CREDENTIAL);
}
assert((*mechanisms)->elements != NULL);
status = gss_inquire_cred_by_mech(minor_status,
creds,
&(*mechanisms)->elements[0],
name,
&initiator_lifetime,
&acceptor_lifetime,
cred_usage);
if (status != GSS_S_COMPLETE) {
gss_release_cred(&tmp_minor_status, &creds);
dsyslog("Leaving inquire_cred\n");
return (status);
}
if (lifetime != NULL)
*lifetime = (*cred_usage == GSS_C_ACCEPT) ?
acceptor_lifetime : initiator_lifetime;
gss_release_cred(&tmp_minor_status, &creds);
} else {
status = gss_inquire_cred(minor_status, spcred->mcred,
name, lifetime,
cred_usage, mechanisms);
}
dsyslog("Leaving inquire_cred\n");
return (status);
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_compare_name(
OM_uint32 *minor_status,
const gss_name_t name1,
const gss_name_t name2,
int *name_equal)
{
OM_uint32 status = GSS_S_COMPLETE;
dsyslog("Entering compare_name\n");
status = gss_compare_name(minor_status, name1, name2, name_equal);
dsyslog("Leaving compare_name\n");
return (status);
}
/*ARGSUSED*/
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_display_name(
OM_uint32 *minor_status,
gss_name_t input_name,
gss_buffer_t output_name_buffer,
gss_OID *output_name_type)
{
OM_uint32 status = GSS_S_COMPLETE;
dsyslog("Entering display_name\n");
status = gss_display_name(minor_status, input_name,
output_name_buffer, output_name_type);
dsyslog("Leaving display_name\n");
return (status);
}
/*ARGSUSED*/
OM_uint32 KRB5_CALLCONV
spnego_gss_inquire_names_for_mech(
OM_uint32 *minor_status,
gss_OID mechanism,
gss_OID_set *name_types)
{
OM_uint32 major, minor;
dsyslog("Entering inquire_names_for_mech\n");
/*
* We only know how to handle our own mechanism.
*/
if ((mechanism != GSS_C_NULL_OID) &&
!g_OID_equal(gss_mech_spnego, mechanism)) {
*minor_status = 0;
return (GSS_S_FAILURE);
}
major = gss_create_empty_oid_set(minor_status, name_types);
if (major == GSS_S_COMPLETE) {
/* Now add our members. */
if (((major = gss_add_oid_set_member(minor_status,
(gss_OID) GSS_C_NT_USER_NAME,
name_types)) == GSS_S_COMPLETE) &&
((major = gss_add_oid_set_member(minor_status,
(gss_OID) GSS_C_NT_MACHINE_UID_NAME,
name_types)) == GSS_S_COMPLETE) &&
((major = gss_add_oid_set_member(minor_status,
(gss_OID) GSS_C_NT_STRING_UID_NAME,
name_types)) == GSS_S_COMPLETE)) {
major = gss_add_oid_set_member(minor_status,
(gss_OID) GSS_C_NT_HOSTBASED_SERVICE,
name_types);
}
if (major != GSS_S_COMPLETE)
(void) gss_release_oid_set(&minor, name_types);
}
dsyslog("Leaving inquire_names_for_mech\n");
return (major);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_unwrap(
OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer,
gss_buffer_t output_message_buffer,
int *conf_state,
gss_qop_t *qop_state)
{
OM_uint32 ret;
ret = gss_unwrap(minor_status,
context_handle,
input_message_buffer,
output_message_buffer,
conf_state,
qop_state);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_wrap(
OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
gss_buffer_t input_message_buffer,
int *conf_state,
gss_buffer_t output_message_buffer)
{
OM_uint32 ret;
ret = gss_wrap(minor_status,
context_handle,
conf_req_flag,
qop_req,
input_message_buffer,
conf_state,
output_message_buffer);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_process_context_token(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_buffer_t token_buffer)
{
OM_uint32 ret;
ret = gss_process_context_token(minor_status,
context_handle,
token_buffer);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_delete_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t output_token)
{
OM_uint32 ret = GSS_S_COMPLETE;
spnego_gss_ctx_id_t *ctx =
(spnego_gss_ctx_id_t *)context_handle;
*minor_status = 0;
if (context_handle == NULL)
return (GSS_S_FAILURE);
if (*ctx == NULL)
return (GSS_S_COMPLETE);
/*
* If this is still an SPNEGO mech, release it locally.
*/
if ((*ctx)->magic_num == SPNEGO_MAGIC_ID) {
(void) gss_delete_sec_context(minor_status,
&(*ctx)->ctx_handle,
output_token);
(void) release_spnego_ctx(ctx);
} else {
ret = gss_delete_sec_context(minor_status,
context_handle,
output_token);
}
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_context_time(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
OM_uint32 *time_rec)
{
OM_uint32 ret;
ret = gss_context_time(minor_status,
context_handle,
time_rec);
return (ret);
}
#ifndef LEAN_CLIENT
OM_uint32 KRB5_CALLCONV
spnego_gss_export_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 ret;
ret = gss_export_sec_context(minor_status,
context_handle,
interprocess_token);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_import_sec_context(
OM_uint32 *minor_status,
const gss_buffer_t interprocess_token,
gss_ctx_id_t *context_handle)
{
OM_uint32 ret;
ret = gss_import_sec_context(minor_status,
interprocess_token,
context_handle);
return (ret);
}
#endif /* LEAN_CLIENT */
OM_uint32 KRB5_CALLCONV
spnego_gss_inquire_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_name_t *src_name,
gss_name_t *targ_name,
OM_uint32 *lifetime_rec,
gss_OID *mech_type,
OM_uint32 *ctx_flags,
int *locally_initiated,
int *opened)
{
OM_uint32 ret = GSS_S_COMPLETE;
ret = gss_inquire_context(minor_status,
context_handle,
src_name,
targ_name,
lifetime_rec,
mech_type,
ctx_flags,
locally_initiated,
opened);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_wrap_size_limit(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
OM_uint32 req_output_size,
OM_uint32 *max_input_size)
{
OM_uint32 ret;
ret = gss_wrap_size_limit(minor_status,
context_handle,
conf_req_flag,
qop_req,
req_output_size,
max_input_size);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_get_mic(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_qop_t qop_req,
const gss_buffer_t message_buffer,
gss_buffer_t message_token)
{
OM_uint32 ret;
ret = gss_get_mic(minor_status,
context_handle,
qop_req,
message_buffer,
message_token);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_verify_mic(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_buffer_t msg_buffer,
const gss_buffer_t token_buffer,
gss_qop_t *qop_state)
{
OM_uint32 ret;
ret = gss_verify_mic(minor_status,
context_handle,
msg_buffer,
token_buffer,
qop_state);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_inquire_sec_context_by_oid(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
OM_uint32 ret;
ret = gss_inquire_sec_context_by_oid(minor_status,
context_handle,
desired_object,
data_set);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_inquire_cred_by_oid(
OM_uint32 *minor_status,
const gss_cred_id_t cred_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
OM_uint32 ret;
spnego_gss_cred_id_t spcred = (spnego_gss_cred_id_t)cred_handle;
gss_cred_id_t mcred;
mcred = (spcred == NULL) ? GSS_C_NO_CREDENTIAL : spcred->mcred;
ret = gss_inquire_cred_by_oid(minor_status,
mcred,
desired_object,
data_set);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_set_cred_option(
OM_uint32 *minor_status,
gss_cred_id_t *cred_handle,
const gss_OID desired_object,
const gss_buffer_t value)
{
OM_uint32 ret;
OM_uint32 tmp_minor_status;
spnego_gss_cred_id_t spcred = (spnego_gss_cred_id_t)*cred_handle;
gss_cred_id_t mcred;
mcred = (spcred == NULL) ? GSS_C_NO_CREDENTIAL : spcred->mcred;
ret = gss_set_cred_option(minor_status,
&mcred,
desired_object,
value);
if (ret == GSS_S_COMPLETE && spcred == NULL) {
/*
* If the mechanism allocated a new credential handle, then
* we need to wrap it up in an SPNEGO credential handle.
*/
spcred = malloc(sizeof(spnego_gss_cred_id_rec));
if (spcred == NULL) {
gss_release_cred(&tmp_minor_status, &mcred);
*minor_status = ENOMEM;
return (GSS_S_FAILURE);
}
spcred->mcred = mcred;
spcred->neg_mechs = GSS_C_NULL_OID_SET;
*cred_handle = (gss_cred_id_t)spcred;
}
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_set_sec_context_option(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
const gss_OID desired_object,
const gss_buffer_t value)
{
OM_uint32 ret;
ret = gss_set_sec_context_option(minor_status,
context_handle,
desired_object,
value);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_wrap_aead(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
gss_buffer_t input_assoc_buffer,
gss_buffer_t input_payload_buffer,
int *conf_state,
gss_buffer_t output_message_buffer)
{
OM_uint32 ret;
ret = gss_wrap_aead(minor_status,
context_handle,
conf_req_flag,
qop_req,
input_assoc_buffer,
input_payload_buffer,
conf_state,
output_message_buffer);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_unwrap_aead(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer,
gss_buffer_t input_assoc_buffer,
gss_buffer_t output_payload_buffer,
int *conf_state,
gss_qop_t *qop_state)
{
OM_uint32 ret;
ret = gss_unwrap_aead(minor_status,
context_handle,
input_message_buffer,
input_assoc_buffer,
output_payload_buffer,
conf_state,
qop_state);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_wrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
ret = gss_wrap_iov(minor_status,
context_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_unwrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int *conf_state,
gss_qop_t *qop_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
ret = gss_unwrap_iov(minor_status,
context_handle,
conf_state,
qop_state,
iov,
iov_count);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_wrap_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
ret = gss_wrap_iov_length(minor_status,
context_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_complete_auth_token(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer)
{
OM_uint32 ret;
ret = gss_complete_auth_token(minor_status,
context_handle,
input_message_buffer);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_acquire_cred_impersonate_name(OM_uint32 *minor_status,
const gss_cred_id_t impersonator_cred_handle,
const gss_name_t desired_name,
OM_uint32 time_req,
gss_OID_set desired_mechs,
gss_cred_usage_t cred_usage,
gss_cred_id_t *output_cred_handle,
gss_OID_set *actual_mechs,
OM_uint32 *time_rec)
{
OM_uint32 status;
gss_OID_set amechs = GSS_C_NULL_OID_SET;
spnego_gss_cred_id_t imp_spcred = NULL, out_spcred = NULL;
gss_cred_id_t imp_mcred, out_mcred;
dsyslog("Entering spnego_gss_acquire_cred_impersonate_name\n");
if (actual_mechs)
*actual_mechs = NULL;
if (time_rec)
*time_rec = 0;
imp_spcred = (spnego_gss_cred_id_t)impersonator_cred_handle;
imp_mcred = imp_spcred ? imp_spcred->mcred : GSS_C_NO_CREDENTIAL;
if (desired_mechs == GSS_C_NO_OID_SET) {
status = gss_inquire_cred(minor_status, imp_mcred, NULL, NULL,
NULL, &amechs);
if (status != GSS_S_COMPLETE)
return status;
desired_mechs = amechs;
}
status = gss_acquire_cred_impersonate_name(minor_status, imp_mcred,
desired_name, time_req,
desired_mechs, cred_usage,
&out_mcred, actual_mechs,
time_rec);
if (amechs != GSS_C_NULL_OID_SET)
(void) gss_release_oid_set(minor_status, &amechs);
out_spcred = malloc(sizeof(spnego_gss_cred_id_rec));
if (out_spcred == NULL) {
gss_release_cred(minor_status, &out_mcred);
*minor_status = ENOMEM;
return (GSS_S_FAILURE);
}
out_spcred->mcred = out_mcred;
out_spcred->neg_mechs = GSS_C_NULL_OID_SET;
*output_cred_handle = (gss_cred_id_t)out_spcred;
dsyslog("Leaving spnego_gss_acquire_cred_impersonate_name\n");
return (status);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_acquire_cred_with_password(OM_uint32 *minor_status,
const gss_name_t desired_name,
const gss_buffer_t password,
OM_uint32 time_req,
const gss_OID_set desired_mechs,
gss_cred_usage_t cred_usage,
gss_cred_id_t *output_cred_handle,
gss_OID_set *actual_mechs,
OM_uint32 *time_rec)
{
OM_uint32 status, tmpmin;
gss_OID_set amechs = GSS_C_NULL_OID_SET;
gss_cred_id_t mcred = NULL;
spnego_gss_cred_id_t spcred = NULL;
dsyslog("Entering spnego_gss_acquire_cred_with_password\n");
if (actual_mechs)
*actual_mechs = NULL;
if (time_rec)
*time_rec = 0;
status = get_available_mechs(minor_status, desired_name,
cred_usage, GSS_C_NO_CRED_STORE,
NULL, &amechs);
if (status != GSS_S_COMPLETE)
goto cleanup;
status = gss_acquire_cred_with_password(minor_status, desired_name,
password, time_req, amechs,
cred_usage, &mcred,
actual_mechs, time_rec);
if (status != GSS_S_COMPLETE)
goto cleanup;
spcred = malloc(sizeof(spnego_gss_cred_id_rec));
if (spcred == NULL) {
*minor_status = ENOMEM;
status = GSS_S_FAILURE;
goto cleanup;
}
spcred->neg_mechs = GSS_C_NULL_OID_SET;
spcred->mcred = mcred;
mcred = GSS_C_NO_CREDENTIAL;
*output_cred_handle = (gss_cred_id_t)spcred;
cleanup:
(void) gss_release_oid_set(&tmpmin, &amechs);
(void) gss_release_cred(&tmpmin, &mcred);
dsyslog("Leaving spnego_gss_acquire_cred_with_password\n");
return (status);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_display_name_ext(OM_uint32 *minor_status,
gss_name_t name,
gss_OID display_as_name_type,
gss_buffer_t display_name)
{
OM_uint32 ret;
ret = gss_display_name_ext(minor_status,
name,
display_as_name_type,
display_name);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_inquire_name(OM_uint32 *minor_status,
gss_name_t name,
int *name_is_MN,
gss_OID *MN_mech,
gss_buffer_set_t *attrs)
{
OM_uint32 ret;
ret = gss_inquire_name(minor_status,
name,
name_is_MN,
MN_mech,
attrs);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_get_name_attribute(OM_uint32 *minor_status,
gss_name_t name,
gss_buffer_t attr,
int *authenticated,
int *complete,
gss_buffer_t value,
gss_buffer_t display_value,
int *more)
{
OM_uint32 ret;
ret = gss_get_name_attribute(minor_status,
name,
attr,
authenticated,
complete,
value,
display_value,
more);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_set_name_attribute(OM_uint32 *minor_status,
gss_name_t name,
int complete,
gss_buffer_t attr,
gss_buffer_t value)
{
OM_uint32 ret;
ret = gss_set_name_attribute(minor_status,
name,
complete,
attr,
value);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_delete_name_attribute(OM_uint32 *minor_status,
gss_name_t name,
gss_buffer_t attr)
{
OM_uint32 ret;
ret = gss_delete_name_attribute(minor_status,
name,
attr);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_export_name_composite(OM_uint32 *minor_status,
gss_name_t name,
gss_buffer_t exp_composite_name)
{
OM_uint32 ret;
ret = gss_export_name_composite(minor_status,
name,
exp_composite_name);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_map_name_to_any(OM_uint32 *minor_status,
gss_name_t name,
int authenticated,
gss_buffer_t type_id,
gss_any_t *output)
{
OM_uint32 ret;
ret = gss_map_name_to_any(minor_status,
name,
authenticated,
type_id,
output);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_release_any_name_mapping(OM_uint32 *minor_status,
gss_name_t name,
gss_buffer_t type_id,
gss_any_t *input)
{
OM_uint32 ret;
ret = gss_release_any_name_mapping(minor_status,
name,
type_id,
input);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_pseudo_random(OM_uint32 *minor_status,
gss_ctx_id_t context,
int prf_key,
const gss_buffer_t prf_in,
ssize_t desired_output_len,
gss_buffer_t prf_out)
{
OM_uint32 ret;
ret = gss_pseudo_random(minor_status,
context,
prf_key,
prf_in,
desired_output_len,
prf_out);
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_set_neg_mechs(OM_uint32 *minor_status,
gss_cred_id_t cred_handle,
const gss_OID_set mech_list)
{
OM_uint32 ret;
spnego_gss_cred_id_t spcred = (spnego_gss_cred_id_t)cred_handle;
/* Store mech_list in spcred for use in negotiation logic. */
gss_release_oid_set(minor_status, &spcred->neg_mechs);
ret = generic_gss_copy_oid_set(minor_status, mech_list,
&spcred->neg_mechs);
return (ret);
}
#define SPNEGO_SASL_NAME "SPNEGO"
#define SPNEGO_SASL_NAME_LEN (sizeof(SPNEGO_SASL_NAME) - 1)
OM_uint32 KRB5_CALLCONV
spnego_gss_inquire_mech_for_saslname(OM_uint32 *minor_status,
const gss_buffer_t sasl_mech_name,
gss_OID *mech_type)
{
if (sasl_mech_name->length == SPNEGO_SASL_NAME_LEN &&
memcmp(sasl_mech_name->value, SPNEGO_SASL_NAME,
SPNEGO_SASL_NAME_LEN) == 0) {
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_spnego;
return (GSS_S_COMPLETE);
}
return (GSS_S_BAD_MECH);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_inquire_saslname_for_mech(OM_uint32 *minor_status,
const gss_OID desired_mech,
gss_buffer_t sasl_mech_name,
gss_buffer_t mech_name,
gss_buffer_t mech_description)
{
*minor_status = 0;
if (!g_OID_equal(desired_mech, gss_mech_spnego))
return (GSS_S_BAD_MECH);
if (!g_make_string_buffer(SPNEGO_SASL_NAME, sasl_mech_name) ||
!g_make_string_buffer("spnego", mech_name) ||
!g_make_string_buffer("Simple and Protected GSS-API "
"Negotiation Mechanism", mech_description))
goto fail;
return (GSS_S_COMPLETE);
fail:
*minor_status = ENOMEM;
return (GSS_S_FAILURE);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_inquire_attrs_for_mech(OM_uint32 *minor_status,
gss_const_OID mech,
gss_OID_set *mech_attrs,
gss_OID_set *known_mech_attrs)
{
OM_uint32 major, tmpMinor;
/* known_mech_attrs is handled by mechglue */
*minor_status = 0;
if (mech_attrs == NULL)
return (GSS_S_COMPLETE);
major = gss_create_empty_oid_set(minor_status, mech_attrs);
if (GSS_ERROR(major))
goto cleanup;
#define MA_SUPPORTED(ma) do { \
major = gss_add_oid_set_member(minor_status, \
(gss_OID)ma, mech_attrs); \
if (GSS_ERROR(major)) \
goto cleanup; \
} while (0)
MA_SUPPORTED(GSS_C_MA_MECH_NEGO);
MA_SUPPORTED(GSS_C_MA_ITOK_FRAMED);
cleanup:
if (GSS_ERROR(major))
gss_release_oid_set(&tmpMinor, mech_attrs);
return (major);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_export_cred(OM_uint32 *minor_status,
gss_cred_id_t cred_handle,
gss_buffer_t token)
{
spnego_gss_cred_id_t spcred = (spnego_gss_cred_id_t)cred_handle;
return (gss_export_cred(minor_status, spcred->mcred, token));
}
OM_uint32 KRB5_CALLCONV
spnego_gss_import_cred(OM_uint32 *minor_status,
gss_buffer_t token,
gss_cred_id_t *cred_handle)
{
OM_uint32 ret;
spnego_gss_cred_id_t spcred;
gss_cred_id_t mcred;
ret = gss_import_cred(minor_status, token, &mcred);
if (GSS_ERROR(ret))
return (ret);
spcred = malloc(sizeof(*spcred));
if (spcred == NULL) {
gss_release_cred(minor_status, &mcred);
*minor_status = ENOMEM;
return (GSS_S_FAILURE);
}
spcred->mcred = mcred;
spcred->neg_mechs = GSS_C_NULL_OID_SET;
*cred_handle = (gss_cred_id_t)spcred;
return (ret);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t qop_req, gss_iov_buffer_desc *iov,
int iov_count)
{
return gss_get_mic_iov(minor_status, context_handle, qop_req, iov,
iov_count);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t *qop_state, gss_iov_buffer_desc *iov,
int iov_count)
{
return gss_verify_mic_iov(minor_status, context_handle, qop_state, iov,
iov_count);
}
OM_uint32 KRB5_CALLCONV
spnego_gss_get_mic_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle, gss_qop_t qop_req,
gss_iov_buffer_desc *iov, int iov_count)
{
return gss_get_mic_iov_length(minor_status, context_handle, qop_req, iov,
iov_count);
}
/*
* We will release everything but the ctx_handle so that it
* can be passed back to init/accept context. This routine should
* not be called until after the ctx_handle memory is assigned to
* the supplied context handle from init/accept context.
*/
static void
release_spnego_ctx(spnego_gss_ctx_id_t *ctx)
{
spnego_gss_ctx_id_t context;
OM_uint32 minor_stat;
context = *ctx;
if (context != NULL) {
(void) gss_release_buffer(&minor_stat,
&context->DER_mechTypes);
(void) gss_release_oid_set(&minor_stat, &context->mech_set);
(void) gss_release_name(&minor_stat, &context->internal_name);
if (context->optionStr != NULL) {
free(context->optionStr);
context->optionStr = NULL;
}
free(context);
*ctx = NULL;
}
}
/*
* Can't use gss_indicate_mechs by itself to get available mechs for
* SPNEGO because it will also return the SPNEGO mech and we do not
* want to consider SPNEGO as an available security mech for
* negotiation. For this reason, get_available_mechs will return
* all available mechs except SPNEGO.
*
* If a ptr to a creds list is given, this function will attempt
* to acquire creds for the creds given and trim the list of
* returned mechanisms to only those for which creds are valid.
*
*/
static OM_uint32
get_available_mechs(OM_uint32 *minor_status,
gss_name_t name, gss_cred_usage_t usage,
gss_const_key_value_set_t cred_store,
gss_cred_id_t *creds, gss_OID_set *rmechs)
{
unsigned int i;
int found = 0;
OM_uint32 major_status = GSS_S_COMPLETE, tmpmin;
gss_OID_set mechs, goodmechs;
major_status = gss_indicate_mechs(minor_status, &mechs);
if (major_status != GSS_S_COMPLETE) {
return (major_status);
}
major_status = gss_create_empty_oid_set(minor_status, rmechs);
if (major_status != GSS_S_COMPLETE) {
(void) gss_release_oid_set(minor_status, &mechs);
return (major_status);
}
for (i = 0; i < mechs->count && major_status == GSS_S_COMPLETE; i++) {
if ((mechs->elements[i].length
!= spnego_mechanism.mech_type.length) ||
memcmp(mechs->elements[i].elements,
spnego_mechanism.mech_type.elements,
spnego_mechanism.mech_type.length)) {
major_status = gss_add_oid_set_member(minor_status,
&mechs->elements[i],
rmechs);
if (major_status == GSS_S_COMPLETE)
found++;
}
}
/*
* If the caller wanted a list of creds returned,
* trim the list of mechanisms down to only those
* for which the creds are valid.
*/
if (found > 0 && major_status == GSS_S_COMPLETE && creds != NULL) {
major_status = gss_acquire_cred_from(minor_status, name,
GSS_C_INDEFINITE,
*rmechs, usage,
cred_store, creds,
&goodmechs, NULL);
/*
* Drop the old list in favor of the new
* "trimmed" list.
*/
(void) gss_release_oid_set(&tmpmin, rmechs);
if (major_status == GSS_S_COMPLETE) {
(void) gssint_copy_oid_set(&tmpmin,
goodmechs, rmechs);
(void) gss_release_oid_set(&tmpmin, &goodmechs);
}
}
(void) gss_release_oid_set(&tmpmin, &mechs);
if (found == 0 || major_status != GSS_S_COMPLETE) {
*minor_status = ERR_SPNEGO_NO_MECHS_AVAILABLE;
map_errcode(minor_status);
if (major_status == GSS_S_COMPLETE)
major_status = GSS_S_FAILURE;
}
return (major_status);
}
/*
* Return a list of mechanisms we are willing to negotiate for a credential,
* taking into account the mech set provided with gss_set_neg_mechs if it
* exists.
*/
static OM_uint32
get_negotiable_mechs(OM_uint32 *minor_status, spnego_gss_cred_id_t spcred,
gss_cred_usage_t usage, gss_OID_set *rmechs)
{
OM_uint32 ret, tmpmin;
gss_cred_id_t creds = GSS_C_NO_CREDENTIAL, *credptr;
gss_OID_set cred_mechs = GSS_C_NULL_OID_SET;
gss_OID_set intersect_mechs = GSS_C_NULL_OID_SET;
unsigned int i;
int present;
if (spcred == NULL) {
/*
* The default credentials were supplied. Return a list of all
* available mechs except SPNEGO. When initiating, trim this
* list to mechs we can acquire credentials for.
*/
credptr = (usage == GSS_C_INITIATE) ? &creds : NULL;
ret = get_available_mechs(minor_status, GSS_C_NO_NAME, usage,
GSS_C_NO_CRED_STORE, credptr,
rmechs);
gss_release_cred(&tmpmin, &creds);
return (ret);
}
/* Get the list of mechs in the mechglue cred. */
ret = gss_inquire_cred(minor_status, spcred->mcred, NULL, NULL, NULL,
&cred_mechs);
if (ret != GSS_S_COMPLETE)
return (ret);
if (spcred->neg_mechs == GSS_C_NULL_OID_SET) {
/* gss_set_neg_mechs was never called; return cred_mechs. */
*rmechs = cred_mechs;
*minor_status = 0;
return (GSS_S_COMPLETE);
}
/* Compute the intersection of cred_mechs and spcred->neg_mechs,
* preserving the order in spcred->neg_mechs. */
ret = gss_create_empty_oid_set(minor_status, &intersect_mechs);
if (ret != GSS_S_COMPLETE) {
gss_release_oid_set(&tmpmin, &cred_mechs);
return (ret);
}
for (i = 0; i < spcred->neg_mechs->count; i++) {
gss_test_oid_set_member(&tmpmin,
&spcred->neg_mechs->elements[i],
cred_mechs, &present);
if (!present)
continue;
ret = gss_add_oid_set_member(minor_status,
&spcred->neg_mechs->elements[i],
&intersect_mechs);
if (ret != GSS_S_COMPLETE)
break;
}
gss_release_oid_set(&tmpmin, &cred_mechs);
if (intersect_mechs->count == 0 || ret != GSS_S_COMPLETE) {
gss_release_oid_set(&tmpmin, &intersect_mechs);
*minor_status = ERR_SPNEGO_NO_MECHS_AVAILABLE;
map_errcode(minor_status);
return (GSS_S_FAILURE);
}
*rmechs = intersect_mechs;
*minor_status = 0;
return (GSS_S_COMPLETE);
}
/* following are token creation and reading routines */
/*
* If buff_in is not pointing to a MECH_OID, then return NULL and do not
* advance the buffer, otherwise, decode the mech_oid from the buffer and
* place in gss_OID.
*/
static gss_OID
get_mech_oid(OM_uint32 *minor_status, unsigned char **buff_in, size_t length)
{
OM_uint32 status;
gss_OID_desc toid;
gss_OID mech_out = NULL;
unsigned char *start, *end;
if (length < 1 || **buff_in != MECH_OID)
return (NULL);
start = *buff_in;
end = start + length;
(*buff_in)++;
toid.length = *(*buff_in)++;
if ((*buff_in + toid.length) > end)
return (NULL);
toid.elements = *buff_in;
*buff_in += toid.length;
status = generic_gss_copy_oid(minor_status, &toid, &mech_out);
if (status != GSS_S_COMPLETE) {
map_errcode(minor_status);
mech_out = NULL;
}
return (mech_out);
}
/*
* der encode the given mechanism oid into buf_out, advancing the
* buffer pointer.
*/
static int
put_mech_oid(unsigned char **buf_out, gss_OID_const mech, unsigned int buflen)
{
if (buflen < mech->length + 2)
return (-1);
*(*buf_out)++ = MECH_OID;
*(*buf_out)++ = (unsigned char) mech->length;
memcpy(*buf_out, mech->elements, mech->length);
*buf_out += mech->length;
return (0);
}
/*
* verify that buff_in points to an octet string, if it does not,
* return NULL and don't advance the pointer. If it is an octet string
* decode buff_in into a gss_buffer_t and return it, advancing the
* buffer pointer.
*/
static gss_buffer_t
get_input_token(unsigned char **buff_in, unsigned int buff_length)
{
gss_buffer_t input_token;
unsigned int len;
if (g_get_tag_and_length(buff_in, OCTET_STRING, buff_length, &len) < 0)
return (NULL);
input_token = (gss_buffer_t)malloc(sizeof (gss_buffer_desc));
if (input_token == NULL)
return (NULL);
input_token->length = len;
if (input_token->length > 0) {
input_token->value = gssalloc_malloc(input_token->length);
if (input_token->value == NULL) {
free(input_token);
return (NULL);
}
memcpy(input_token->value, *buff_in, input_token->length);
} else {
input_token->value = NULL;
}
*buff_in += input_token->length;
return (input_token);
}
/*
* verify that the input token length is not 0. If it is, just return.
* If the token length is greater than 0, der encode as an octet string
* and place in buf_out, advancing buf_out.
*/
static int
put_input_token(unsigned char **buf_out, gss_buffer_t input_token,
unsigned int buflen)
{
int ret;
/* if token length is 0, we do not want to send */
if (input_token->length == 0)
return (0);
if (input_token->length > buflen)
return (-1);
*(*buf_out)++ = OCTET_STRING;
if ((ret = gssint_put_der_length(input_token->length, buf_out,
input_token->length)))
return (ret);
TWRITE_STR(*buf_out, input_token->value, input_token->length);
return (0);
}
/*
* verify that buff_in points to a sequence of der encoding. The mech
* set is the only sequence of encoded object in the token, so if it is
* a sequence of encoding, decode the mechset into a gss_OID_set and
* return it, advancing the buffer pointer.
*/
static gss_OID_set
get_mech_set(OM_uint32 *minor_status, unsigned char **buff_in,
unsigned int buff_length)
{
gss_OID_set returned_mechSet;
OM_uint32 major_status;
int length;
unsigned int bytes;
OM_uint32 set_length;
unsigned char *start;
int i;
if (**buff_in != SEQUENCE_OF)
return (NULL);
start = *buff_in;
(*buff_in)++;
length = gssint_get_der_length(buff_in, buff_length, &bytes);
if (length < 0 || buff_length - bytes < (unsigned int)length)
return NULL;
major_status = gss_create_empty_oid_set(minor_status,
&returned_mechSet);
if (major_status != GSS_S_COMPLETE)
return (NULL);
for (set_length = 0, i = 0; set_length < (unsigned int)length; i++) {
gss_OID_desc *temp = get_mech_oid(minor_status, buff_in,
buff_length - (*buff_in - start));
if (temp == NULL)
break;
major_status = gss_add_oid_set_member(minor_status,
temp, &returned_mechSet);
if (major_status == GSS_S_COMPLETE) {
set_length += returned_mechSet->elements[i].length +2;
if (generic_gss_release_oid(minor_status, &temp))
map_errcode(minor_status);
}
}
return (returned_mechSet);
}
/*
* Encode mechSet into buf.
*/
static int
put_mech_set(gss_OID_set mechSet, gss_buffer_t buf)
{
unsigned char *ptr;
unsigned int i;
unsigned int tlen, ilen;
tlen = ilen = 0;
for (i = 0; i < mechSet->count; i++) {
/*
* 0x06 [DER LEN] [OID]
*/
ilen += 1 +
gssint_der_length_size(mechSet->elements[i].length) +
mechSet->elements[i].length;
}
/*
* 0x30 [DER LEN]
*/
tlen = 1 + gssint_der_length_size(ilen) + ilen;
ptr = gssalloc_malloc(tlen);
if (ptr == NULL)
return -1;
buf->value = ptr;
buf->length = tlen;
#define REMAIN (buf->length - ((unsigned char *)buf->value - ptr))
*ptr++ = SEQUENCE_OF;
if (gssint_put_der_length(ilen, &ptr, REMAIN) < 0)
return -1;
for (i = 0; i < mechSet->count; i++) {
if (put_mech_oid(&ptr, &mechSet->elements[i], REMAIN) < 0) {
return -1;
}
}
return 0;
#undef REMAIN
}
/*
* Verify that buff_in is pointing to a BIT_STRING with the correct
* length and padding for the req_flags. If it is, decode req_flags
* and return them, otherwise, return NULL.
*/
static OM_uint32
get_req_flags(unsigned char **buff_in, OM_uint32 bodysize,
OM_uint32 *req_flags)
{
unsigned int len;
if (**buff_in != (CONTEXT | 0x01))
return (0);
if (g_get_tag_and_length(buff_in, (CONTEXT | 0x01),
bodysize, &len) < 0)
return GSS_S_DEFECTIVE_TOKEN;
if (*(*buff_in)++ != BIT_STRING)
return GSS_S_DEFECTIVE_TOKEN;
if (*(*buff_in)++ != BIT_STRING_LENGTH)
return GSS_S_DEFECTIVE_TOKEN;
if (*(*buff_in)++ != BIT_STRING_PADDING)
return GSS_S_DEFECTIVE_TOKEN;
*req_flags = (OM_uint32) (*(*buff_in)++ >> 1);
return (0);
}
static OM_uint32
get_negTokenInit(OM_uint32 *minor_status,
gss_buffer_t buf,
gss_buffer_t der_mechSet,
gss_OID_set *mechSet,
OM_uint32 *req_flags,
gss_buffer_t *mechtok,
gss_buffer_t *mechListMIC)
{
OM_uint32 err;
unsigned char *ptr, *bufstart;
unsigned int len;
gss_buffer_desc tmpbuf;
*minor_status = 0;
der_mechSet->length = 0;
der_mechSet->value = NULL;
*mechSet = GSS_C_NO_OID_SET;
*req_flags = 0;
*mechtok = *mechListMIC = GSS_C_NO_BUFFER;
ptr = bufstart = buf->value;
if ((buf->length - (ptr - bufstart)) > INT_MAX)
return GSS_S_FAILURE;
#define REMAIN (buf->length - (ptr - bufstart))
err = g_verify_token_header(gss_mech_spnego,
&len, &ptr, 0, REMAIN);
if (err) {
*minor_status = err;
map_errcode(minor_status);
return GSS_S_FAILURE;
}
*minor_status = g_verify_neg_token_init(&ptr, REMAIN);
if (*minor_status) {
map_errcode(minor_status);
return GSS_S_FAILURE;
}
/* alias into input_token */
tmpbuf.value = ptr;
tmpbuf.length = REMAIN;
*mechSet = get_mech_set(minor_status, &ptr, REMAIN);
if (*mechSet == NULL)
return GSS_S_FAILURE;
tmpbuf.length = ptr - (unsigned char *)tmpbuf.value;
der_mechSet->value = gssalloc_malloc(tmpbuf.length);
if (der_mechSet->value == NULL)
return GSS_S_FAILURE;
memcpy(der_mechSet->value, tmpbuf.value, tmpbuf.length);
der_mechSet->length = tmpbuf.length;
err = get_req_flags(&ptr, REMAIN, req_flags);
if (err != GSS_S_COMPLETE) {
return err;
}
if (g_get_tag_and_length(&ptr, (CONTEXT | 0x02),
REMAIN, &len) >= 0) {
*mechtok = get_input_token(&ptr, len);
if (*mechtok == GSS_C_NO_BUFFER) {
return GSS_S_FAILURE;
}
}
if (g_get_tag_and_length(&ptr, (CONTEXT | 0x03),
REMAIN, &len) >= 0) {
*mechListMIC = get_input_token(&ptr, len);
if (*mechListMIC == GSS_C_NO_BUFFER) {
return GSS_S_FAILURE;
}
}
return GSS_S_COMPLETE;
#undef REMAIN
}
static OM_uint32
get_negTokenResp(OM_uint32 *minor_status,
unsigned char *buf, unsigned int buflen,
OM_uint32 *negState,
gss_OID *supportedMech,
gss_buffer_t *responseToken,
gss_buffer_t *mechListMIC)
{
unsigned char *ptr, *bufstart;
unsigned int len;
int tmplen;
unsigned int tag, bytes;
*negState = ACCEPT_DEFECTIVE_TOKEN;
*supportedMech = GSS_C_NO_OID;
*responseToken = *mechListMIC = GSS_C_NO_BUFFER;
ptr = bufstart = buf;
#define REMAIN (buflen - (ptr - bufstart))
if (g_get_tag_and_length(&ptr, (CONTEXT | 0x01), REMAIN, &len) < 0)
return GSS_S_DEFECTIVE_TOKEN;
if (*ptr++ == SEQUENCE) {
tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes);
if (tmplen < 0 || REMAIN < (unsigned int)tmplen)
return GSS_S_DEFECTIVE_TOKEN;
}
if (REMAIN < 1)
tag = 0;
else
tag = *ptr++;
if (tag == CONTEXT) {
tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes);
if (tmplen < 0 || REMAIN < (unsigned int)tmplen)
return GSS_S_DEFECTIVE_TOKEN;
if (g_get_tag_and_length(&ptr, ENUMERATED,
REMAIN, &len) < 0)
return GSS_S_DEFECTIVE_TOKEN;
if (len != ENUMERATION_LENGTH)
return GSS_S_DEFECTIVE_TOKEN;
if (REMAIN < 1)
return GSS_S_DEFECTIVE_TOKEN;
*negState = *ptr++;
if (REMAIN < 1)
tag = 0;
else
tag = *ptr++;
}
if (tag == (CONTEXT | 0x01)) {
tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes);
if (tmplen < 0 || REMAIN < (unsigned int)tmplen)
return GSS_S_DEFECTIVE_TOKEN;
*supportedMech = get_mech_oid(minor_status, &ptr, REMAIN);
if (*supportedMech == GSS_C_NO_OID)
return GSS_S_DEFECTIVE_TOKEN;
if (REMAIN < 1)
tag = 0;
else
tag = *ptr++;
}
if (tag == (CONTEXT | 0x02)) {
tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes);
if (tmplen < 0 || REMAIN < (unsigned int)tmplen)
return GSS_S_DEFECTIVE_TOKEN;
*responseToken = get_input_token(&ptr, REMAIN);
if (*responseToken == GSS_C_NO_BUFFER)
return GSS_S_DEFECTIVE_TOKEN;
if (REMAIN < 1)
tag = 0;
else
tag = *ptr++;
}
if (tag == (CONTEXT | 0x03)) {
tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes);
if (tmplen < 0 || REMAIN < (unsigned int)tmplen)
return GSS_S_DEFECTIVE_TOKEN;
*mechListMIC = get_input_token(&ptr, REMAIN);
if (*mechListMIC == GSS_C_NO_BUFFER)
return GSS_S_DEFECTIVE_TOKEN;
/* Handle Windows 2000 duplicate response token */
if (*responseToken &&
((*responseToken)->length == (*mechListMIC)->length) &&
!memcmp((*responseToken)->value, (*mechListMIC)->value,
(*responseToken)->length)) {
OM_uint32 tmpmin;
gss_release_buffer(&tmpmin, *mechListMIC);
free(*mechListMIC);
*mechListMIC = NULL;
}
}
return GSS_S_COMPLETE;
#undef REMAIN
}
/*
* der encode the passed negResults as an ENUMERATED type and
* place it in buf_out, advancing the buffer.
*/
static int
put_negResult(unsigned char **buf_out, OM_uint32 negResult,
unsigned int buflen)
{
if (buflen < 3)
return (-1);
*(*buf_out)++ = ENUMERATED;
*(*buf_out)++ = ENUMERATION_LENGTH;
*(*buf_out)++ = (unsigned char) negResult;
return (0);
}
/*
* This routine compares the recieved mechset to the mechset that
* this server can support. It looks sequentially through the mechset
* and the first one that matches what the server can support is
* chosen as the negotiated mechanism. If one is found, negResult
* is set to ACCEPT_INCOMPLETE if it's the first mech, REQUEST_MIC if
* it's not the first mech, otherwise we return NULL and negResult
* is set to REJECT. The returned pointer is an alias into
* received->elements and should not be freed.
*
* NOTE: There is currently no way to specify a preference order of
* mechanisms supported by the acceptor.
*/
static gss_OID
negotiate_mech(gss_OID_set supported, gss_OID_set received,
OM_uint32 *negResult)
{
size_t i, j;
for (i = 0; i < received->count; i++) {
gss_OID mech_oid = &received->elements[i];
/* Accept wrong mechanism OID from MS clients */
if (g_OID_equal(mech_oid, &gss_mech_krb5_wrong_oid))
mech_oid = (gss_OID)&gss_mech_krb5_oid;
for (j = 0; j < supported->count; j++) {
if (g_OID_equal(mech_oid, &supported->elements[j])) {
*negResult = (i == 0) ? ACCEPT_INCOMPLETE :
REQUEST_MIC;
return &received->elements[i];
}
}
}
*negResult = REJECT;
return (NULL);
}
/*
* the next two routines make a token buffer suitable for
* spnego_gss_display_status. These currently take the string
* in name and place it in the token. Eventually, if
* spnego_gss_display_status returns valid error messages,
* these routines will be changes to return the error string.
*/
static spnego_token_t
make_spnego_token(const char *name)
{
return (spnego_token_t)strdup(name);
}
static gss_buffer_desc
make_err_msg(const char *name)
{
gss_buffer_desc buffer;
if (name == NULL) {
buffer.length = 0;
buffer.value = NULL;
} else {
buffer.length = strlen(name)+1;
buffer.value = make_spnego_token(name);
}
return (buffer);
}
/*
* Create the client side spnego token passed back to gss_init_sec_context
* and eventually up to the application program and over to the server.
*
* Use DER rules, definite length method per RFC 2478
*/
static int
make_spnego_tokenInit_msg(spnego_gss_ctx_id_t spnego_ctx,
int negHintsCompat,
gss_buffer_t mechListMIC, OM_uint32 req_flags,
gss_buffer_t data, send_token_flag sendtoken,
gss_buffer_t outbuf)
{
int ret = 0;
unsigned int tlen, dataLen = 0;
unsigned int negTokenInitSize = 0;
unsigned int negTokenInitSeqSize = 0;
unsigned int negTokenInitContSize = 0;
unsigned int rspTokenSize = 0;
unsigned int mechListTokenSize = 0;
unsigned int micTokenSize = 0;
unsigned char *t;
unsigned char *ptr;
if (outbuf == GSS_C_NO_BUFFER)
return (-1);
outbuf->length = 0;
outbuf->value = NULL;
/* calculate the data length */
/*
* 0xa0 [DER LEN] [mechTypes]
*/
mechListTokenSize = 1 +
gssint_der_length_size(spnego_ctx->DER_mechTypes.length) +
spnego_ctx->DER_mechTypes.length;
dataLen += mechListTokenSize;
/*
* If a token from gss_init_sec_context exists,
* add the length of the token + the ASN.1 overhead
*/
if (data != NULL) {
/*
* Encoded in final output as:
* 0xa2 [DER LEN] 0x04 [DER LEN] [DATA]
* -----s--------|--------s2----------
*/
rspTokenSize = 1 +
gssint_der_length_size(data->length) +
data->length;
dataLen += 1 + gssint_der_length_size(rspTokenSize) +
rspTokenSize;
}
if (mechListMIC) {
/*
* Encoded in final output as:
* 0xa3 [DER LEN] 0x04 [DER LEN] [DATA]
* --s-- -----tlen------------
*/
micTokenSize = 1 +
gssint_der_length_size(mechListMIC->length) +
mechListMIC->length;
dataLen += 1 +
gssint_der_length_size(micTokenSize) +
micTokenSize;
}
/*
* Add size of DER encoding
* [ SEQUENCE { MechTypeList | ReqFLags | Token | mechListMIC } ]
* 0x30 [DER_LEN] [data]
*
*/
negTokenInitContSize = dataLen;
negTokenInitSeqSize = 1 + gssint_der_length_size(dataLen) + dataLen;
dataLen = negTokenInitSeqSize;
/*
* negTokenInitSize indicates the bytes needed to
* hold the ASN.1 encoding of the entire NegTokenInit
* SEQUENCE.
* 0xa0 [DER_LEN] + data
*
*/
negTokenInitSize = 1 +
gssint_der_length_size(negTokenInitSeqSize) +
negTokenInitSeqSize;
tlen = g_token_size(gss_mech_spnego, negTokenInitSize);
t = (unsigned char *) gssalloc_malloc(tlen);
if (t == NULL) {
return (-1);
}
ptr = t;
/* create the message */
if ((ret = g_make_token_header(gss_mech_spnego, negTokenInitSize,
&ptr, tlen)))
goto errout;
*ptr++ = CONTEXT; /* NegotiationToken identifier */
if ((ret = gssint_put_der_length(negTokenInitSeqSize, &ptr, tlen)))
goto errout;
*ptr++ = SEQUENCE;
if ((ret = gssint_put_der_length(negTokenInitContSize, &ptr,
tlen - (int)(ptr-t))))
goto errout;
*ptr++ = CONTEXT | 0x00; /* MechTypeList identifier */
if ((ret = gssint_put_der_length(spnego_ctx->DER_mechTypes.length,
&ptr, tlen - (int)(ptr-t))))
goto errout;
/* We already encoded the MechSetList */
(void) memcpy(ptr, spnego_ctx->DER_mechTypes.value,
spnego_ctx->DER_mechTypes.length);
ptr += spnego_ctx->DER_mechTypes.length;
if (data != NULL) {
*ptr++ = CONTEXT | 0x02;
if ((ret = gssint_put_der_length(rspTokenSize,
&ptr, tlen - (int)(ptr - t))))
goto errout;
if ((ret = put_input_token(&ptr, data,
tlen - (int)(ptr - t))))
goto errout;
}
if (mechListMIC != GSS_C_NO_BUFFER) {
*ptr++ = CONTEXT | 0x03;
if ((ret = gssint_put_der_length(micTokenSize,
&ptr, tlen - (int)(ptr - t))))
goto errout;
if (negHintsCompat) {
ret = put_neg_hints(&ptr, mechListMIC,
tlen - (int)(ptr - t));
if (ret)
goto errout;
} else if ((ret = put_input_token(&ptr, mechListMIC,
tlen - (int)(ptr - t))))
goto errout;
}
errout:
if (ret != 0) {
if (t)
free(t);
t = NULL;
tlen = 0;
}
outbuf->length = tlen;
outbuf->value = (void *) t;
return (ret);
}
/*
* create the server side spnego token passed back to
* gss_accept_sec_context and eventually up to the application program
* and over to the client.
*/
static int
make_spnego_tokenTarg_msg(OM_uint32 status, gss_OID mech_wanted,
gss_buffer_t data, gss_buffer_t mechListMIC,
send_token_flag sendtoken,
gss_buffer_t outbuf)
{
unsigned int tlen = 0;
unsigned int ret = 0;
unsigned int NegTokenTargSize = 0;
unsigned int NegTokenSize = 0;
unsigned int rspTokenSize = 0;
unsigned int micTokenSize = 0;
unsigned int dataLen = 0;
unsigned char *t;
unsigned char *ptr;
if (outbuf == GSS_C_NO_BUFFER)
return (GSS_S_DEFECTIVE_TOKEN);
if (sendtoken == INIT_TOKEN_SEND && mech_wanted == GSS_C_NO_OID)
return (GSS_S_DEFECTIVE_TOKEN);
outbuf->length = 0;
outbuf->value = NULL;
/*
* ASN.1 encoding of the negResult
* ENUMERATED type is 3 bytes
* ENUMERATED TAG, Length, Value,
* Plus 2 bytes for the CONTEXT id and length.
*/
dataLen = 5;
/*
* calculate data length
*
* If this is the initial token, include length of
* mech_type and the negotiation result fields.
*/
if (sendtoken == INIT_TOKEN_SEND) {
int mechlistTokenSize;
/*
* 1 byte for the CONTEXT ID(0xa0),
* 1 byte for the OID ID(0x06)
* 1 byte for OID Length field
* Plus the rest... (OID Length, OID value)
*/
mechlistTokenSize = 3 + mech_wanted->length +
gssint_der_length_size(mech_wanted->length);
dataLen += mechlistTokenSize;
}
if (data != NULL && data->length > 0) {
/* Length of the inner token */
rspTokenSize = 1 + gssint_der_length_size(data->length) +
data->length;
dataLen += rspTokenSize;
/* Length of the outer token */
dataLen += 1 + gssint_der_length_size(rspTokenSize);
}
if (mechListMIC != NULL) {
/* Length of the inner token */
micTokenSize = 1 + gssint_der_length_size(mechListMIC->length) +
mechListMIC->length;
dataLen += micTokenSize;
/* Length of the outer token */
dataLen += 1 + gssint_der_length_size(micTokenSize);
}
/*
* Add size of DER encoded:
* NegTokenTarg [ SEQUENCE ] of
* NegResult[0] ENUMERATED {
* accept_completed(0),
* accept_incomplete(1),
* reject(2) }
* supportedMech [1] MechType OPTIONAL,
* responseToken [2] OCTET STRING OPTIONAL,
* mechListMIC [3] OCTET STRING OPTIONAL
*
* size = data->length + MechListMic + SupportedMech len +
* Result Length + ASN.1 overhead
*/
NegTokenTargSize = dataLen;
dataLen += 1 + gssint_der_length_size(NegTokenTargSize);
/*
* NegotiationToken [ CHOICE ]{
* negTokenInit [0] NegTokenInit,
* negTokenTarg [1] NegTokenTarg }
*/
NegTokenSize = dataLen;
dataLen += 1 + gssint_der_length_size(NegTokenSize);
tlen = dataLen;
t = (unsigned char *) gssalloc_malloc(tlen);
if (t == NULL) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
ptr = t;
/*
* Indicate that we are sending CHOICE 1
* (NegTokenTarg)
*/
*ptr++ = CONTEXT | 0x01;
if (gssint_put_der_length(NegTokenSize, &ptr, dataLen) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
*ptr++ = SEQUENCE;
if (gssint_put_der_length(NegTokenTargSize, &ptr,
tlen - (int)(ptr-t)) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
/*
* First field of the NegTokenTarg SEQUENCE
* is the ENUMERATED NegResult.
*/
*ptr++ = CONTEXT;
if (gssint_put_der_length(3, &ptr,
tlen - (int)(ptr-t)) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
if (put_negResult(&ptr, status, tlen - (int)(ptr - t)) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
if (sendtoken == INIT_TOKEN_SEND) {
/*
* Next, is the Supported MechType
*/
*ptr++ = CONTEXT | 0x01;
if (gssint_put_der_length(mech_wanted->length + 2,
&ptr,
tlen - (int)(ptr - t)) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
if (put_mech_oid(&ptr, mech_wanted,
tlen - (int)(ptr - t)) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
}
if (data != NULL && data->length > 0) {
*ptr++ = CONTEXT | 0x02;
if (gssint_put_der_length(rspTokenSize, &ptr,
tlen - (int)(ptr - t)) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
if (put_input_token(&ptr, data,
tlen - (int)(ptr - t)) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
}
if (mechListMIC != NULL) {
*ptr++ = CONTEXT | 0x03;
if (gssint_put_der_length(micTokenSize, &ptr,
tlen - (int)(ptr - t)) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
if (put_input_token(&ptr, mechListMIC,
tlen - (int)(ptr - t)) < 0) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto errout;
}
}
ret = GSS_S_COMPLETE;
errout:
if (ret != GSS_S_COMPLETE) {
if (t)
free(t);
} else {
outbuf->length = ptr - t;
outbuf->value = (void *) t;
}
return (ret);
}
/* determine size of token */
static int
g_token_size(gss_OID_const mech, unsigned int body_size)
{
int hdrsize;
/*
* Initialize the header size to the
* MECH_OID byte + the bytes needed to indicate the
* length of the OID + the OID itself.
*
* 0x06 [MECHLENFIELD] MECHDATA
*/
hdrsize = 1 + gssint_der_length_size(mech->length) + mech->length;
/*
* Now add the bytes needed for the initial header
* token bytes:
* 0x60 + [DER_LEN] + HDRSIZE
*/
hdrsize += 1 + gssint_der_length_size(body_size + hdrsize);
return (hdrsize + body_size);
}
/*
* generate token header.
*
* Use DER Definite Length method per RFC2478
* Use of indefinite length encoding will not be compatible
* with Microsoft or others that actually follow the spec.
*/
static int
g_make_token_header(gss_OID_const mech,
unsigned int body_size,
unsigned char **buf,
unsigned int totallen)
{
int ret = 0;
unsigned int hdrsize;
unsigned char *p = *buf;
hdrsize = 1 + gssint_der_length_size(mech->length) + mech->length;
*(*buf)++ = HEADER_ID;
if ((ret = gssint_put_der_length(hdrsize + body_size, buf, totallen)))
return (ret);
*(*buf)++ = MECH_OID;
if ((ret = gssint_put_der_length(mech->length, buf,
totallen - (int)(p - *buf))))
return (ret);
TWRITE_STR(*buf, mech->elements, mech->length);
return (0);
}
/*
* NOTE: This checks that the length returned by
* gssint_get_der_length() is not greater than the number of octets
* remaining, even though gssint_get_der_length() already checks, in
* theory.
*/
static int
g_get_tag_and_length(unsigned char **buf, int tag,
unsigned int buflen, unsigned int *outlen)
{
unsigned char *ptr = *buf;
int ret = -1; /* pessimists, assume failure ! */
unsigned int encoded_len;
int tmplen = 0;
*outlen = 0;
if (buflen > 1 && *ptr == tag) {
ptr++;
tmplen = gssint_get_der_length(&ptr, buflen - 1,
&encoded_len);
if (tmplen < 0) {
ret = -1;
} else if ((unsigned int)tmplen > buflen - (ptr - *buf)) {
ret = -1;
} else
ret = 0;
}
*outlen = tmplen;
*buf = ptr;
return (ret);
}
static int
g_verify_neg_token_init(unsigned char **buf_in, unsigned int cur_size)
{
unsigned char *buf = *buf_in;
unsigned char *endptr = buf + cur_size;
int seqsize;
int ret = 0;
unsigned int bytes;
/*
* Verify this is a NegotiationToken type token
* - check for a0(context specific identifier)
* - get length and verify that enoughd ata exists
*/
if (g_get_tag_and_length(&buf, CONTEXT, cur_size, &bytes) < 0)
return (G_BAD_TOK_HEADER);
cur_size = bytes; /* should indicate bytes remaining */
/*
* Verify the next piece, it should identify this as
* a strucure of type NegTokenInit.
*/
if (*buf++ == SEQUENCE) {
if ((seqsize = gssint_get_der_length(&buf, cur_size, &bytes)) < 0)
return (G_BAD_TOK_HEADER);
/*
* Make sure we have the entire buffer as described
*/
if (seqsize > endptr - buf)
return (G_BAD_TOK_HEADER);
} else {
return (G_BAD_TOK_HEADER);
}
cur_size = seqsize; /* should indicate bytes remaining */
/*
* Verify that the first blob is a sequence of mechTypes
*/
if (*buf++ == CONTEXT) {
if ((seqsize = gssint_get_der_length(&buf, cur_size, &bytes)) < 0)
return (G_BAD_TOK_HEADER);
/*
* Make sure we have the entire buffer as described
*/
if (seqsize > endptr - buf)
return (G_BAD_TOK_HEADER);
} else {
return (G_BAD_TOK_HEADER);
}
/*
* At this point, *buf should be at the beginning of the
* DER encoded list of mech types that are to be negotiated.
*/
*buf_in = buf;
return (ret);
}
/* verify token header. */
static int
g_verify_token_header(gss_OID_const mech,
unsigned int *body_size,
unsigned char **buf_in,
int tok_type,
unsigned int toksize)
{
unsigned char *buf = *buf_in;
int seqsize;
gss_OID_desc toid;
int ret = 0;
unsigned int bytes;
if (toksize-- < 1)
return (G_BAD_TOK_HEADER);
if (*buf++ != HEADER_ID)
return (G_BAD_TOK_HEADER);
if ((seqsize = gssint_get_der_length(&buf, toksize, &bytes)) < 0)
return (G_BAD_TOK_HEADER);
if ((seqsize + bytes) != toksize)
return (G_BAD_TOK_HEADER);
if (toksize-- < 1)
return (G_BAD_TOK_HEADER);
if (*buf++ != MECH_OID)
return (G_BAD_TOK_HEADER);
if (toksize-- < 1)
return (G_BAD_TOK_HEADER);
toid.length = *buf++;
if (toksize < toid.length)
return (G_BAD_TOK_HEADER);
else
toksize -= toid.length;
toid.elements = buf;
buf += toid.length;
if (!g_OID_equal(&toid, mech))
ret = G_WRONG_MECH;
/*
* G_WRONG_MECH is not returned immediately because it's more important
* to return G_BAD_TOK_HEADER if the token header is in fact bad
*/
if (toksize < 2)
return (G_BAD_TOK_HEADER);
else
toksize -= 2;
if (!ret) {
*buf_in = buf;
*body_size = toksize;
}
return (ret);
}
/*
* Return non-zero if the oid is one of the kerberos mech oids,
* otherwise return zero.
*
* N.B. There are 3 oids that represent the kerberos mech:
* RFC-specified GSS_MECH_KRB5_OID,
* Old pre-RFC GSS_MECH_KRB5_OLD_OID,
* Incorrect MS GSS_MECH_KRB5_WRONG_OID
*/
static int
is_kerb_mech(gss_OID oid)
{
int answer = 0;
OM_uint32 minor;
extern const gss_OID_set_desc * const gss_mech_set_krb5_both;
(void) gss_test_oid_set_member(&minor,
oid, (gss_OID_set)gss_mech_set_krb5_both, &answer);
return (answer);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_2199_0 |
crossvul-cpp_data_good_101_1 | /*
* fs/cifs/smb2pdu.c
*
* Copyright (C) International Business Machines Corp., 2009, 2013
* Etersoft, 2012
* Author(s): Steve French (sfrench@us.ibm.com)
* Pavel Shilovsky (pshilovsky@samba.org) 2012
*
* Contains the routines for constructing the SMB2 PDUs themselves
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
/* Note that there are handle based routines which must be */
/* treated slightly differently for reconnection purposes since we never */
/* want to reuse a stale file handle and only the caller knows the file info */
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/vfs.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/uaccess.h>
#include <linux/pagemap.h>
#include <linux/xattr.h>
#include "smb2pdu.h"
#include "cifsglob.h"
#include "cifsacl.h"
#include "cifsproto.h"
#include "smb2proto.h"
#include "cifs_unicode.h"
#include "cifs_debug.h"
#include "ntlmssp.h"
#include "smb2status.h"
#include "smb2glob.h"
#include "cifspdu.h"
#include "cifs_spnego.h"
/*
* The following table defines the expected "StructureSize" of SMB2 requests
* in order by SMB2 command. This is similar to "wct" in SMB/CIFS requests.
*
* Note that commands are defined in smb2pdu.h in le16 but the array below is
* indexed by command in host byte order.
*/
static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
/* SMB2_NEGOTIATE */ 36,
/* SMB2_SESSION_SETUP */ 25,
/* SMB2_LOGOFF */ 4,
/* SMB2_TREE_CONNECT */ 9,
/* SMB2_TREE_DISCONNECT */ 4,
/* SMB2_CREATE */ 57,
/* SMB2_CLOSE */ 24,
/* SMB2_FLUSH */ 24,
/* SMB2_READ */ 49,
/* SMB2_WRITE */ 49,
/* SMB2_LOCK */ 48,
/* SMB2_IOCTL */ 57,
/* SMB2_CANCEL */ 4,
/* SMB2_ECHO */ 4,
/* SMB2_QUERY_DIRECTORY */ 33,
/* SMB2_CHANGE_NOTIFY */ 32,
/* SMB2_QUERY_INFO */ 41,
/* SMB2_SET_INFO */ 33,
/* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
};
static int encryption_required(const struct cifs_tcon *tcon)
{
if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
(tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
return 1;
return 0;
}
static void
smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd,
const struct cifs_tcon *tcon)
{
shdr->ProtocolId = SMB2_PROTO_NUMBER;
shdr->StructureSize = cpu_to_le16(64);
shdr->Command = smb2_cmd;
if (tcon && tcon->ses && tcon->ses->server) {
struct TCP_Server_Info *server = tcon->ses->server;
spin_lock(&server->req_lock);
/* Request up to 2 credits but don't go over the limit. */
if (server->credits >= server->max_credits)
shdr->CreditRequest = cpu_to_le16(0);
else
shdr->CreditRequest = cpu_to_le16(
min_t(int, server->max_credits -
server->credits, 2));
spin_unlock(&server->req_lock);
} else {
shdr->CreditRequest = cpu_to_le16(2);
}
shdr->ProcessId = cpu_to_le32((__u16)current->tgid);
if (!tcon)
goto out;
/* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
/* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
if ((tcon->ses) && (tcon->ses->server) &&
(tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
shdr->CreditCharge = cpu_to_le16(1);
/* else CreditCharge MBZ */
shdr->TreeId = tcon->tid;
/* Uid is not converted */
if (tcon->ses)
shdr->SessionId = tcon->ses->Suid;
/*
* If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
* to pass the path on the Open SMB prefixed by \\server\share.
* Not sure when we would need to do the augmented path (if ever) and
* setting this flag breaks the SMB2 open operation since it is
* illegal to send an empty path name (without \\server\share prefix)
* when the DFS flag is set in the SMB open header. We could
* consider setting the flag on all operations other than open
* but it is safer to net set it for now.
*/
/* if (tcon->share_flags & SHI1005_FLAGS_DFS)
shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
if (tcon->ses && tcon->ses->server && tcon->ses->server->sign &&
!encryption_required(tcon))
shdr->Flags |= SMB2_FLAGS_SIGNED;
out:
return;
}
static int
smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
{
int rc = 0;
struct nls_table *nls_codepage;
struct cifs_ses *ses;
struct TCP_Server_Info *server;
/*
* SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
* check for tcp and smb session status done differently
* for those three - in the calling routine.
*/
if (tcon == NULL)
return rc;
if (smb2_command == SMB2_TREE_CONNECT)
return rc;
if (tcon->tidStatus == CifsExiting) {
/*
* only tree disconnect, open, and write,
* (and ulogoff which does not have tcon)
* are allowed as we start force umount.
*/
if ((smb2_command != SMB2_WRITE) &&
(smb2_command != SMB2_CREATE) &&
(smb2_command != SMB2_TREE_DISCONNECT)) {
cifs_dbg(FYI, "can not send cmd %d while umounting\n",
smb2_command);
return -ENODEV;
}
}
if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
(!tcon->ses->server))
return -EIO;
ses = tcon->ses;
server = ses->server;
/*
* Give demultiplex thread up to 10 seconds to reconnect, should be
* greater than cifs socket timeout which is 7 seconds
*/
while (server->tcpStatus == CifsNeedReconnect) {
/*
* Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
* here since they are implicitly done when session drops.
*/
switch (smb2_command) {
/*
* BB Should we keep oplock break and add flush to exceptions?
*/
case SMB2_TREE_DISCONNECT:
case SMB2_CANCEL:
case SMB2_CLOSE:
case SMB2_OPLOCK_BREAK:
return -EAGAIN;
}
wait_event_interruptible_timeout(server->response_q,
(server->tcpStatus != CifsNeedReconnect), 10 * HZ);
/* are we still trying to reconnect? */
if (server->tcpStatus != CifsNeedReconnect)
break;
/*
* on "soft" mounts we wait once. Hard mounts keep
* retrying until process is killed or server comes
* back on-line
*/
if (!tcon->retry) {
cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
return -EHOSTDOWN;
}
}
if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
return rc;
nls_codepage = load_nls_default();
/*
* need to prevent multiple threads trying to simultaneously reconnect
* the same SMB session
*/
mutex_lock(&tcon->ses->session_mutex);
rc = cifs_negotiate_protocol(0, tcon->ses);
if (!rc && tcon->ses->need_reconnect)
rc = cifs_setup_session(0, tcon->ses, nls_codepage);
if (rc || !tcon->need_reconnect) {
mutex_unlock(&tcon->ses->session_mutex);
goto out;
}
cifs_mark_open_files_invalid(tcon);
if (tcon->use_persistent)
tcon->need_reopen_files = true;
rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage);
mutex_unlock(&tcon->ses->session_mutex);
cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
if (rc)
goto out;
if (smb2_command != SMB2_INTERNAL_CMD)
queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
atomic_inc(&tconInfoReconnectCount);
out:
/*
* Check if handle based operation so we know whether we can continue
* or not without returning to caller to reset file handle.
*/
/*
* BB Is flush done by server on drop of tcp session? Should we special
* case it and skip above?
*/
switch (smb2_command) {
case SMB2_FLUSH:
case SMB2_READ:
case SMB2_WRITE:
case SMB2_LOCK:
case SMB2_IOCTL:
case SMB2_QUERY_DIRECTORY:
case SMB2_CHANGE_NOTIFY:
case SMB2_QUERY_INFO:
case SMB2_SET_INFO:
rc = -EAGAIN;
}
unload_nls(nls_codepage);
return rc;
}
static void
fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon, void *buf,
unsigned int *total_len)
{
struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf;
/* lookup word count ie StructureSize from table */
__u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
/*
* smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
* largest operations (Create)
*/
memset(buf, 0, 256);
smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon);
spdu->StructureSize2 = cpu_to_le16(parmsize);
*total_len = parmsize + sizeof(struct smb2_sync_hdr);
}
/* init request without RFC1001 length at the beginning */
static int
smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
void **request_buf, unsigned int *total_len)
{
int rc;
struct smb2_sync_hdr *shdr;
rc = smb2_reconnect(smb2_command, tcon);
if (rc)
return rc;
/* BB eventually switch this to SMB2 specific small buf size */
*request_buf = cifs_small_buf_get();
if (*request_buf == NULL) {
/* BB should we add a retry in here if not a writepage? */
return -ENOMEM;
}
shdr = (struct smb2_sync_hdr *)(*request_buf);
fill_small_buf(smb2_command, tcon, shdr, total_len);
if (tcon != NULL) {
#ifdef CONFIG_CIFS_STATS2
uint16_t com_code = le16_to_cpu(smb2_command);
cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
#endif
cifs_stats_inc(&tcon->num_smbs_sent);
}
return rc;
}
/*
* Allocate and return pointer to an SMB request hdr, and set basic
* SMB information in the SMB header. If the return code is zero, this
* function must have filled in request_buf pointer. The returned buffer
* has RFC1001 length at the beginning.
*/
static int
small_smb2_init(__le16 smb2_command, struct cifs_tcon *tcon,
void **request_buf)
{
int rc;
unsigned int total_len;
struct smb2_pdu *pdu;
rc = smb2_reconnect(smb2_command, tcon);
if (rc)
return rc;
/* BB eventually switch this to SMB2 specific small buf size */
*request_buf = cifs_small_buf_get();
if (*request_buf == NULL) {
/* BB should we add a retry in here if not a writepage? */
return -ENOMEM;
}
pdu = (struct smb2_pdu *)(*request_buf);
fill_small_buf(smb2_command, tcon, get_sync_hdr(pdu), &total_len);
/* Note this is only network field converted to big endian */
pdu->hdr.smb2_buf_length = cpu_to_be32(total_len);
if (tcon != NULL) {
#ifdef CONFIG_CIFS_STATS2
uint16_t com_code = le16_to_cpu(smb2_command);
cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
#endif
cifs_stats_inc(&tcon->num_smbs_sent);
}
return rc;
}
#ifdef CONFIG_CIFS_SMB311
/* offset is sizeof smb2_negotiate_req - 4 but rounded up to 8 bytes */
#define OFFSET_OF_NEG_CONTEXT 0x68 /* sizeof(struct smb2_negotiate_req) - 4 */
#define SMB2_PREAUTH_INTEGRITY_CAPABILITIES cpu_to_le16(1)
#define SMB2_ENCRYPTION_CAPABILITIES cpu_to_le16(2)
static void
build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
{
pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
pneg_ctxt->DataLength = cpu_to_le16(38);
pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
}
static void
build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
{
pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
pneg_ctxt->DataLength = cpu_to_le16(6);
pneg_ctxt->CipherCount = cpu_to_le16(2);
pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
}
static void
assemble_neg_contexts(struct smb2_negotiate_req *req)
{
/* +4 is to account for the RFC1001 len field */
char *pneg_ctxt = (char *)req + OFFSET_OF_NEG_CONTEXT + 4;
build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
/* Add 2 to size to round to 8 byte boundary */
pneg_ctxt += 2 + sizeof(struct smb2_preauth_neg_context);
build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
req->NegotiateContextOffset = cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
req->NegotiateContextCount = cpu_to_le16(2);
inc_rfc1001_len(req, 4 + sizeof(struct smb2_preauth_neg_context) + 2
+ sizeof(struct smb2_encryption_neg_context)); /* calculate hash */
}
#else
static void assemble_neg_contexts(struct smb2_negotiate_req *req)
{
return;
}
#endif /* SMB311 */
/*
*
* SMB2 Worker functions follow:
*
* The general structure of the worker functions is:
* 1) Call smb2_init (assembles SMB2 header)
* 2) Initialize SMB2 command specific fields in fixed length area of SMB
* 3) Call smb_sendrcv2 (sends request on socket and waits for response)
* 4) Decode SMB2 command specific fields in the fixed length area
* 5) Decode variable length data area (if any for this SMB2 command type)
* 6) Call free smb buffer
* 7) return
*
*/
int
SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
{
struct smb2_negotiate_req *req;
struct smb2_negotiate_rsp *rsp;
struct kvec iov[1];
struct kvec rsp_iov;
int rc = 0;
int resp_buftype;
struct TCP_Server_Info *server = ses->server;
int blob_offset, blob_length;
char *security_blob;
int flags = CIFS_NEG_OP;
cifs_dbg(FYI, "Negotiate protocol\n");
if (!server) {
WARN(1, "%s: server is NULL!\n", __func__);
return -EIO;
}
rc = small_smb2_init(SMB2_NEGOTIATE, NULL, (void **) &req);
if (rc)
return rc;
req->hdr.sync_hdr.SessionId = 0;
req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
req->DialectCount = cpu_to_le16(1); /* One vers= at a time for now */
inc_rfc1001_len(req, 2);
/* only one of SMB2 signing flags may be set in SMB2 request */
if (ses->sign)
req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
else if (global_secflags & CIFSSEC_MAY_SIGN)
req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
else
req->SecurityMode = 0;
req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
/* ClientGUID must be zero for SMB2.02 dialect */
if (ses->server->vals->protocol_id == SMB20_PROT_ID)
memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
else {
memcpy(req->ClientGUID, server->client_guid,
SMB2_CLIENT_GUID_SIZE);
if (ses->server->vals->protocol_id == SMB311_PROT_ID)
assemble_neg_contexts(req);
}
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field */
iov[0].iov_len = get_rfc1002_length(req) + 4;
rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
/*
* No tcon so can't do
* cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
*/
if (rc != 0)
goto neg_exit;
cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
/* BB we may eventually want to match the negotiated vs. requested
dialect, even though we are only requesting one at a time */
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
#ifdef CONFIG_CIFS_SMB311
else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
#endif /* SMB311 */
else {
cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
le16_to_cpu(rsp->DialectRevision));
rc = -EIO;
goto neg_exit;
}
server->dialect = le16_to_cpu(rsp->DialectRevision);
/* SMB2 only has an extended negflavor */
server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
/* set it to the maximum buffer size value we can send with 1 credit */
server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
SMB2_MAX_BUFFER_SIZE);
server->max_read = le32_to_cpu(rsp->MaxReadSize);
server->max_write = le32_to_cpu(rsp->MaxWriteSize);
/* BB Do we need to validate the SecurityMode? */
server->sec_mode = le16_to_cpu(rsp->SecurityMode);
server->capabilities = le32_to_cpu(rsp->Capabilities);
/* Internal types */
server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
&rsp->hdr);
/*
* See MS-SMB2 section 2.2.4: if no blob, client picks default which
* for us will be
* ses->sectype = RawNTLMSSP;
* but for time being this is our only auth choice so doesn't matter.
* We just found a server which sets blob length to zero expecting raw.
*/
if (blob_length == 0)
cifs_dbg(FYI, "missing security blob on negprot\n");
rc = cifs_enable_signing(server, ses->sign);
if (rc)
goto neg_exit;
if (blob_length) {
rc = decode_negTokenInit(security_blob, blob_length, server);
if (rc == 1)
rc = 0;
else if (rc == 0)
rc = -EIO;
}
neg_exit:
free_rsp_buf(resp_buftype, rsp);
return rc;
}
int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
{
int rc = 0;
struct validate_negotiate_info_req vneg_inbuf;
struct validate_negotiate_info_rsp *pneg_rsp;
u32 rsplen;
cifs_dbg(FYI, "validate negotiate\n");
/*
* validation ioctl must be signed, so no point sending this if we
* can not sign it. We could eventually change this to selectively
* sign just this, the first and only signed request on a connection.
* This is good enough for now since a user who wants better security
* would also enable signing on the mount. Having validation of
* negotiate info for signed connections helps reduce attack vectors
*/
if (tcon->ses->server->sign == false)
return 0; /* validation requires signing */
vneg_inbuf.Capabilities =
cpu_to_le32(tcon->ses->server->vals->req_capabilities);
memcpy(vneg_inbuf.Guid, tcon->ses->server->client_guid,
SMB2_CLIENT_GUID_SIZE);
if (tcon->ses->sign)
vneg_inbuf.SecurityMode =
cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
else if (global_secflags & CIFSSEC_MAY_SIGN)
vneg_inbuf.SecurityMode =
cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
else
vneg_inbuf.SecurityMode = 0;
vneg_inbuf.DialectCount = cpu_to_le16(1);
vneg_inbuf.Dialects[0] =
cpu_to_le16(tcon->ses->server->vals->protocol_id);
rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */,
(char *)&vneg_inbuf, sizeof(struct validate_negotiate_info_req),
(char **)&pneg_rsp, &rsplen);
if (rc != 0) {
cifs_dbg(VFS, "validate protocol negotiate failed: %d\n", rc);
return -EIO;
}
if (rsplen != sizeof(struct validate_negotiate_info_rsp)) {
cifs_dbg(VFS, "invalid size of protocol negotiate response\n");
return -EIO;
}
/* check validate negotiate info response matches what we got earlier */
if (pneg_rsp->Dialect !=
cpu_to_le16(tcon->ses->server->vals->protocol_id))
goto vneg_out;
if (pneg_rsp->SecurityMode != cpu_to_le16(tcon->ses->server->sec_mode))
goto vneg_out;
/* do not validate server guid because not saved at negprot time yet */
if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
SMB2_LARGE_FILES) != tcon->ses->server->capabilities)
goto vneg_out;
/* validate negotiate successful */
cifs_dbg(FYI, "validate negotiate info successful\n");
return 0;
vneg_out:
cifs_dbg(VFS, "protocol revalidation - security settings mismatch\n");
return -EIO;
}
struct SMB2_sess_data {
unsigned int xid;
struct cifs_ses *ses;
struct nls_table *nls_cp;
void (*func)(struct SMB2_sess_data *);
int result;
u64 previous_session;
/* we will send the SMB in three pieces:
* a fixed length beginning part, an optional
* SPNEGO blob (which can be zero length), and a
* last part which will include the strings
* and rest of bcc area. This allows us to avoid
* a large buffer 17K allocation
*/
int buf0_type;
struct kvec iov[2];
};
static int
SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
{
int rc;
struct cifs_ses *ses = sess_data->ses;
struct smb2_sess_setup_req *req;
struct TCP_Server_Info *server = ses->server;
rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req);
if (rc)
return rc;
/* First session, not a reauthenticate */
req->hdr.sync_hdr.SessionId = 0;
/* if reconnect, we need to send previous sess id, otherwise it is 0 */
req->PreviousSessionId = sess_data->previous_session;
req->Flags = 0; /* MBZ */
/* to enable echos and oplocks */
req->hdr.sync_hdr.CreditRequest = cpu_to_le16(3);
/* only one of SMB2 signing flags may be set in SMB2 request */
if (server->sign)
req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
else
req->SecurityMode = 0;
req->Capabilities = 0;
req->Channel = 0; /* MBZ */
sess_data->iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field and 1 for pad */
sess_data->iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
/*
* This variable will be used to clear the buffer
* allocated above in case of any error in the calling function.
*/
sess_data->buf0_type = CIFS_SMALL_BUFFER;
return 0;
}
static void
SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
{
free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base);
sess_data->buf0_type = CIFS_NO_BUFFER;
}
static int
SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
{
int rc;
struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
struct kvec rsp_iov = { NULL, 0 };
/* Testing shows that buffer offset must be at location of Buffer[0] */
req->SecurityBufferOffset =
cpu_to_le16(sizeof(struct smb2_sess_setup_req) -
1 /* pad */ - 4 /* rfc1001 len */);
req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
inc_rfc1001_len(req, sess_data->iov[1].iov_len - 1 /* pad */);
/* BB add code to build os and lm fields */
rc = SendReceive2(sess_data->xid, sess_data->ses,
sess_data->iov, 2,
&sess_data->buf0_type,
CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov);
cifs_small_buf_release(sess_data->iov[0].iov_base);
memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
return rc;
}
static int
SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
{
int rc = 0;
struct cifs_ses *ses = sess_data->ses;
mutex_lock(&ses->server->srv_mutex);
if (ses->server->ops->generate_signingkey) {
rc = ses->server->ops->generate_signingkey(ses);
if (rc) {
cifs_dbg(FYI,
"SMB3 session key generation failed\n");
mutex_unlock(&ses->server->srv_mutex);
return rc;
}
}
if (!ses->server->session_estab) {
ses->server->sequence_number = 0x2;
ses->server->session_estab = true;
}
mutex_unlock(&ses->server->srv_mutex);
cifs_dbg(FYI, "SMB2/3 session established successfully\n");
spin_lock(&GlobalMid_Lock);
ses->status = CifsGood;
ses->need_reconnect = false;
spin_unlock(&GlobalMid_Lock);
return rc;
}
#ifdef CONFIG_CIFS_UPCALL
static void
SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
{
int rc;
struct cifs_ses *ses = sess_data->ses;
struct cifs_spnego_msg *msg;
struct key *spnego_key = NULL;
struct smb2_sess_setup_rsp *rsp = NULL;
rc = SMB2_sess_alloc_buffer(sess_data);
if (rc)
goto out;
spnego_key = cifs_get_spnego_key(ses);
if (IS_ERR(spnego_key)) {
rc = PTR_ERR(spnego_key);
spnego_key = NULL;
goto out;
}
msg = spnego_key->payload.data[0];
/*
* check version field to make sure that cifs.upcall is
* sending us a response in an expected form
*/
if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
cifs_dbg(VFS,
"bad cifs.upcall version. Expected %d got %d",
CIFS_SPNEGO_UPCALL_VERSION, msg->version);
rc = -EKEYREJECTED;
goto out_put_spnego_key;
}
ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
GFP_KERNEL);
if (!ses->auth_key.response) {
cifs_dbg(VFS,
"Kerberos can't allocate (%u bytes) memory",
msg->sesskey_len);
rc = -ENOMEM;
goto out_put_spnego_key;
}
ses->auth_key.len = msg->sesskey_len;
sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
sess_data->iov[1].iov_len = msg->secblob_len;
rc = SMB2_sess_sendreceive(sess_data);
if (rc)
goto out_put_spnego_key;
rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
ses->Suid = rsp->hdr.sync_hdr.SessionId;
ses->session_flags = le16_to_cpu(rsp->SessionFlags);
if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
cifs_dbg(VFS, "SMB3 encryption not supported yet\n");
rc = SMB2_sess_establish_session(sess_data);
out_put_spnego_key:
key_invalidate(spnego_key);
key_put(spnego_key);
out:
sess_data->result = rc;
sess_data->func = NULL;
SMB2_sess_free_buffer(sess_data);
}
#else
static void
SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
{
cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
sess_data->result = -EOPNOTSUPP;
sess_data->func = NULL;
}
#endif
static void
SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
static void
SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
{
int rc;
struct cifs_ses *ses = sess_data->ses;
struct smb2_sess_setup_rsp *rsp = NULL;
char *ntlmssp_blob = NULL;
bool use_spnego = false; /* else use raw ntlmssp */
u16 blob_length = 0;
/*
* If memory allocation is successful, caller of this function
* frees it.
*/
ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
if (!ses->ntlmssp) {
rc = -ENOMEM;
goto out_err;
}
ses->ntlmssp->sesskey_per_smbsess = true;
rc = SMB2_sess_alloc_buffer(sess_data);
if (rc)
goto out_err;
ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
GFP_KERNEL);
if (ntlmssp_blob == NULL) {
rc = -ENOMEM;
goto out;
}
build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
if (use_spnego) {
/* BB eventually need to add this */
cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
rc = -EOPNOTSUPP;
goto out;
} else {
blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
/* with raw NTLMSSP we don't encapsulate in SPNEGO */
}
sess_data->iov[1].iov_base = ntlmssp_blob;
sess_data->iov[1].iov_len = blob_length;
rc = SMB2_sess_sendreceive(sess_data);
rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
/* If true, rc here is expected and not an error */
if (sess_data->buf0_type != CIFS_NO_BUFFER &&
rsp->hdr.sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
rc = 0;
if (rc)
goto out;
if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 !=
le16_to_cpu(rsp->SecurityBufferOffset)) {
cifs_dbg(VFS, "Invalid security buffer offset %d\n",
le16_to_cpu(rsp->SecurityBufferOffset));
rc = -EIO;
goto out;
}
rc = decode_ntlmssp_challenge(rsp->Buffer,
le16_to_cpu(rsp->SecurityBufferLength), ses);
if (rc)
goto out;
cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
ses->Suid = rsp->hdr.sync_hdr.SessionId;
ses->session_flags = le16_to_cpu(rsp->SessionFlags);
if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
cifs_dbg(VFS, "SMB3 encryption not supported yet\n");
out:
kfree(ntlmssp_blob);
SMB2_sess_free_buffer(sess_data);
if (!rc) {
sess_data->result = 0;
sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
return;
}
out_err:
kfree(ses->ntlmssp);
ses->ntlmssp = NULL;
sess_data->result = rc;
sess_data->func = NULL;
}
static void
SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
{
int rc;
struct cifs_ses *ses = sess_data->ses;
struct smb2_sess_setup_req *req;
struct smb2_sess_setup_rsp *rsp = NULL;
unsigned char *ntlmssp_blob = NULL;
bool use_spnego = false; /* else use raw ntlmssp */
u16 blob_length = 0;
rc = SMB2_sess_alloc_buffer(sess_data);
if (rc)
goto out;
req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
req->hdr.sync_hdr.SessionId = ses->Suid;
rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
sess_data->nls_cp);
if (rc) {
cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
goto out;
}
if (use_spnego) {
/* BB eventually need to add this */
cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
rc = -EOPNOTSUPP;
goto out;
}
sess_data->iov[1].iov_base = ntlmssp_blob;
sess_data->iov[1].iov_len = blob_length;
rc = SMB2_sess_sendreceive(sess_data);
if (rc)
goto out;
rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
ses->Suid = rsp->hdr.sync_hdr.SessionId;
ses->session_flags = le16_to_cpu(rsp->SessionFlags);
if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
cifs_dbg(VFS, "SMB3 encryption not supported yet\n");
rc = SMB2_sess_establish_session(sess_data);
out:
kfree(ntlmssp_blob);
SMB2_sess_free_buffer(sess_data);
kfree(ses->ntlmssp);
ses->ntlmssp = NULL;
sess_data->result = rc;
sess_data->func = NULL;
}
static int
SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data)
{
if (ses->sectype != Kerberos && ses->sectype != RawNTLMSSP)
ses->sectype = RawNTLMSSP;
switch (ses->sectype) {
case Kerberos:
sess_data->func = SMB2_auth_kerberos;
break;
case RawNTLMSSP:
sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
break;
default:
cifs_dbg(VFS, "secType %d not supported!\n", ses->sectype);
return -EOPNOTSUPP;
}
return 0;
}
int
SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
const struct nls_table *nls_cp)
{
int rc = 0;
struct TCP_Server_Info *server = ses->server;
struct SMB2_sess_data *sess_data;
cifs_dbg(FYI, "Session Setup\n");
if (!server) {
WARN(1, "%s: server is NULL!\n", __func__);
return -EIO;
}
sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
if (!sess_data)
return -ENOMEM;
rc = SMB2_select_sec(ses, sess_data);
if (rc)
goto out;
sess_data->xid = xid;
sess_data->ses = ses;
sess_data->buf0_type = CIFS_NO_BUFFER;
sess_data->nls_cp = (struct nls_table *) nls_cp;
while (sess_data->func)
sess_data->func(sess_data);
rc = sess_data->result;
out:
kfree(sess_data);
return rc;
}
int
SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
{
struct smb2_logoff_req *req; /* response is also trivial struct */
int rc = 0;
struct TCP_Server_Info *server;
int flags = 0;
cifs_dbg(FYI, "disconnect session %p\n", ses);
if (ses && (ses->server))
server = ses->server;
else
return -EIO;
/* no need to send SMB logoff if uid already closed due to reconnect */
if (ses->need_reconnect)
goto smb2_session_already_dead;
rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req);
if (rc)
return rc;
/* since no tcon, smb2_init can not do this, so do here */
req->hdr.sync_hdr.SessionId = ses->Suid;
if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
flags |= CIFS_TRANSFORM_REQ;
else if (server->sign)
req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
rc = SendReceiveNoRsp(xid, ses, (char *) req, flags);
cifs_small_buf_release(req);
/*
* No tcon so can't do
* cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
*/
smb2_session_already_dead:
return rc;
}
static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
{
cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
}
#define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
/* These are similar values to what Windows uses */
static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
{
tcon->max_chunks = 256;
tcon->max_bytes_chunk = 1048576;
tcon->max_bytes_copy = 16777216;
}
int
SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
struct cifs_tcon *tcon, const struct nls_table *cp)
{
struct smb2_tree_connect_req *req;
struct smb2_tree_connect_rsp *rsp = NULL;
struct kvec iov[2];
struct kvec rsp_iov;
int rc = 0;
int resp_buftype;
int unc_path_len;
struct TCP_Server_Info *server;
__le16 *unc_path = NULL;
int flags = 0;
cifs_dbg(FYI, "TCON\n");
if ((ses->server) && tree)
server = ses->server;
else
return -EIO;
if (tcon && tcon->bad_network_name)
return -ENOENT;
if ((tcon && tcon->seal) &&
((ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) == 0)) {
cifs_dbg(VFS, "encryption requested but no server support");
return -EOPNOTSUPP;
}
unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
if (unc_path == NULL)
return -ENOMEM;
unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
unc_path_len *= 2;
if (unc_path_len < 2) {
kfree(unc_path);
return -EINVAL;
}
rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
if (rc) {
kfree(unc_path);
return rc;
}
if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
flags |= CIFS_TRANSFORM_REQ;
if (tcon == NULL) {
/* since no tcon, smb2_init can not do this, so do here */
req->hdr.sync_hdr.SessionId = ses->Suid;
/* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
}
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field and 1 for pad */
iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
/* Testing shows that buffer offset must be at location of Buffer[0] */
req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
- 1 /* pad */ - 4 /* do not count rfc1001 len field */);
req->PathLength = cpu_to_le16(unc_path_len - 2);
iov[1].iov_base = unc_path;
iov[1].iov_len = unc_path_len;
inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
if (rc != 0) {
if (tcon) {
cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
tcon->need_reconnect = true;
}
goto tcon_error_exit;
}
if (tcon == NULL) {
ses->ipc_tid = rsp->hdr.sync_hdr.TreeId;
goto tcon_exit;
}
if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
cifs_dbg(FYI, "connection to disk share\n");
else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
tcon->ipc = true;
cifs_dbg(FYI, "connection to pipe share\n");
} else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
tcon->print = true;
cifs_dbg(FYI, "connection to printer\n");
} else {
cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
rc = -EOPNOTSUPP;
goto tcon_error_exit;
}
tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
tcon->tidStatus = CifsGood;
tcon->need_reconnect = false;
tcon->tid = rsp->hdr.sync_hdr.TreeId;
strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
init_copy_chunk_defaults(tcon);
if (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA)
cifs_dbg(VFS, "Encrypted shares not supported");
if (tcon->ses->server->ops->validate_negotiate)
rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
tcon_exit:
free_rsp_buf(resp_buftype, rsp);
kfree(unc_path);
return rc;
tcon_error_exit:
if (rsp->hdr.sync_hdr.Status == STATUS_BAD_NETWORK_NAME) {
cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
if (tcon)
tcon->bad_network_name = true;
}
goto tcon_exit;
}
int
SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
{
struct smb2_tree_disconnect_req *req; /* response is trivial */
int rc = 0;
struct TCP_Server_Info *server;
struct cifs_ses *ses = tcon->ses;
int flags = 0;
cifs_dbg(FYI, "Tree Disconnect\n");
if (ses && (ses->server))
server = ses->server;
else
return -EIO;
if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
return 0;
rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
rc = SendReceiveNoRsp(xid, ses, (char *)req, flags);
cifs_small_buf_release(req);
if (rc)
cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
return rc;
}
static struct create_durable *
create_durable_buf(void)
{
struct create_durable *buf;
buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
if (!buf)
return NULL;
buf->ccontext.DataOffset = cpu_to_le16(offsetof
(struct create_durable, Data));
buf->ccontext.DataLength = cpu_to_le32(16);
buf->ccontext.NameOffset = cpu_to_le16(offsetof
(struct create_durable, Name));
buf->ccontext.NameLength = cpu_to_le16(4);
/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
buf->Name[0] = 'D';
buf->Name[1] = 'H';
buf->Name[2] = 'n';
buf->Name[3] = 'Q';
return buf;
}
static struct create_durable *
create_reconnect_durable_buf(struct cifs_fid *fid)
{
struct create_durable *buf;
buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
if (!buf)
return NULL;
buf->ccontext.DataOffset = cpu_to_le16(offsetof
(struct create_durable, Data));
buf->ccontext.DataLength = cpu_to_le32(16);
buf->ccontext.NameOffset = cpu_to_le16(offsetof
(struct create_durable, Name));
buf->ccontext.NameLength = cpu_to_le16(4);
buf->Data.Fid.PersistentFileId = fid->persistent_fid;
buf->Data.Fid.VolatileFileId = fid->volatile_fid;
/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
buf->Name[0] = 'D';
buf->Name[1] = 'H';
buf->Name[2] = 'n';
buf->Name[3] = 'C';
return buf;
}
static __u8
parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp,
unsigned int *epoch)
{
char *data_offset;
struct create_context *cc;
unsigned int next;
unsigned int remaining;
char *name;
data_offset = (char *)rsp + 4 + le32_to_cpu(rsp->CreateContextsOffset);
remaining = le32_to_cpu(rsp->CreateContextsLength);
cc = (struct create_context *)data_offset;
while (remaining >= sizeof(struct create_context)) {
name = le16_to_cpu(cc->NameOffset) + (char *)cc;
if (le16_to_cpu(cc->NameLength) == 4 &&
strncmp(name, "RqLs", 4) == 0)
return server->ops->parse_lease_buf(cc, epoch);
next = le32_to_cpu(cc->Next);
if (!next)
break;
remaining -= next;
cc = (struct create_context *)((char *)cc + next);
}
return 0;
}
static int
add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
unsigned int *num_iovec, __u8 *oplock)
{
struct smb2_create_req *req = iov[0].iov_base;
unsigned int num = *num_iovec;
iov[num].iov_base = server->ops->create_lease_buf(oplock+1, *oplock);
if (iov[num].iov_base == NULL)
return -ENOMEM;
iov[num].iov_len = server->vals->create_lease_size;
req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
if (!req->CreateContextsOffset)
req->CreateContextsOffset = cpu_to_le32(
sizeof(struct smb2_create_req) - 4 +
iov[num - 1].iov_len);
le32_add_cpu(&req->CreateContextsLength,
server->vals->create_lease_size);
inc_rfc1001_len(&req->hdr, server->vals->create_lease_size);
*num_iovec = num + 1;
return 0;
}
static struct create_durable_v2 *
create_durable_v2_buf(struct cifs_fid *pfid)
{
struct create_durable_v2 *buf;
buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
if (!buf)
return NULL;
buf->ccontext.DataOffset = cpu_to_le16(offsetof
(struct create_durable_v2, dcontext));
buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
buf->ccontext.NameOffset = cpu_to_le16(offsetof
(struct create_durable_v2, Name));
buf->ccontext.NameLength = cpu_to_le16(4);
buf->dcontext.Timeout = 0; /* Should this be configurable by workload */
buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
generate_random_uuid(buf->dcontext.CreateGuid);
memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
buf->Name[0] = 'D';
buf->Name[1] = 'H';
buf->Name[2] = '2';
buf->Name[3] = 'Q';
return buf;
}
static struct create_durable_handle_reconnect_v2 *
create_reconnect_durable_v2_buf(struct cifs_fid *fid)
{
struct create_durable_handle_reconnect_v2 *buf;
buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
GFP_KERNEL);
if (!buf)
return NULL;
buf->ccontext.DataOffset =
cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
dcontext));
buf->ccontext.DataLength =
cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
buf->ccontext.NameOffset =
cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
Name));
buf->ccontext.NameLength = cpu_to_le16(4);
buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
buf->Name[0] = 'D';
buf->Name[1] = 'H';
buf->Name[2] = '2';
buf->Name[3] = 'C';
return buf;
}
static int
add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
struct cifs_open_parms *oparms)
{
struct smb2_create_req *req = iov[0].iov_base;
unsigned int num = *num_iovec;
iov[num].iov_base = create_durable_v2_buf(oparms->fid);
if (iov[num].iov_base == NULL)
return -ENOMEM;
iov[num].iov_len = sizeof(struct create_durable_v2);
if (!req->CreateContextsOffset)
req->CreateContextsOffset =
cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
iov[1].iov_len);
le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
inc_rfc1001_len(&req->hdr, sizeof(struct create_durable_v2));
*num_iovec = num + 1;
return 0;
}
static int
add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
struct cifs_open_parms *oparms)
{
struct smb2_create_req *req = iov[0].iov_base;
unsigned int num = *num_iovec;
/* indicate that we don't need to relock the file */
oparms->reconnect = false;
iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
if (iov[num].iov_base == NULL)
return -ENOMEM;
iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
if (!req->CreateContextsOffset)
req->CreateContextsOffset =
cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
iov[1].iov_len);
le32_add_cpu(&req->CreateContextsLength,
sizeof(struct create_durable_handle_reconnect_v2));
inc_rfc1001_len(&req->hdr,
sizeof(struct create_durable_handle_reconnect_v2));
*num_iovec = num + 1;
return 0;
}
static int
add_durable_context(struct kvec *iov, unsigned int *num_iovec,
struct cifs_open_parms *oparms, bool use_persistent)
{
struct smb2_create_req *req = iov[0].iov_base;
unsigned int num = *num_iovec;
if (use_persistent) {
if (oparms->reconnect)
return add_durable_reconnect_v2_context(iov, num_iovec,
oparms);
else
return add_durable_v2_context(iov, num_iovec, oparms);
}
if (oparms->reconnect) {
iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
/* indicate that we don't need to relock the file */
oparms->reconnect = false;
} else
iov[num].iov_base = create_durable_buf();
if (iov[num].iov_base == NULL)
return -ENOMEM;
iov[num].iov_len = sizeof(struct create_durable);
if (!req->CreateContextsOffset)
req->CreateContextsOffset =
cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
iov[1].iov_len);
le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
inc_rfc1001_len(&req->hdr, sizeof(struct create_durable));
*num_iovec = num + 1;
return 0;
}
int
SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
__u8 *oplock, struct smb2_file_all_info *buf,
struct smb2_err_rsp **err_buf)
{
struct smb2_create_req *req;
struct smb2_create_rsp *rsp;
struct TCP_Server_Info *server;
struct cifs_tcon *tcon = oparms->tcon;
struct cifs_ses *ses = tcon->ses;
struct kvec iov[4];
struct kvec rsp_iov;
int resp_buftype;
int uni_path_len;
__le16 *copy_path = NULL;
int copy_size;
int rc = 0;
unsigned int n_iov = 2;
__u32 file_attributes = 0;
char *dhc_buf = NULL, *lc_buf = NULL;
int flags = 0;
cifs_dbg(FYI, "create/open\n");
if (ses && (ses->server))
server = ses->server;
else
return -EIO;
rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
if (oparms->create_options & CREATE_OPTION_READONLY)
file_attributes |= ATTR_READONLY;
if (oparms->create_options & CREATE_OPTION_SPECIAL)
file_attributes |= ATTR_SYSTEM;
req->ImpersonationLevel = IL_IMPERSONATION;
req->DesiredAccess = cpu_to_le32(oparms->desired_access);
/* File attributes ignored on open (used in create though) */
req->FileAttributes = cpu_to_le32(file_attributes);
req->ShareAccess = FILE_SHARE_ALL_LE;
req->CreateDisposition = cpu_to_le32(oparms->disposition);
req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
/* do not count rfc1001 len field */
req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req) - 4);
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field */
iov[0].iov_len = get_rfc1002_length(req) + 4;
/* MUST set path len (NameLength) to 0 opening root of share */
req->NameLength = cpu_to_le16(uni_path_len - 2);
/* -1 since last byte is buf[0] which is sent below (path) */
iov[0].iov_len--;
if (uni_path_len % 8 != 0) {
copy_size = uni_path_len / 8 * 8;
if (copy_size < uni_path_len)
copy_size += 8;
copy_path = kzalloc(copy_size, GFP_KERNEL);
if (!copy_path)
return -ENOMEM;
memcpy((char *)copy_path, (const char *)path,
uni_path_len);
uni_path_len = copy_size;
path = copy_path;
}
iov[1].iov_len = uni_path_len;
iov[1].iov_base = path;
/* -1 since last byte is buf[0] which was counted in smb2_buf_len */
inc_rfc1001_len(req, uni_path_len - 1);
if (!server->oplocks)
*oplock = SMB2_OPLOCK_LEVEL_NONE;
if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
*oplock == SMB2_OPLOCK_LEVEL_NONE)
req->RequestedOplockLevel = *oplock;
else {
rc = add_lease_context(server, iov, &n_iov, oplock);
if (rc) {
cifs_small_buf_release(req);
kfree(copy_path);
return rc;
}
lc_buf = iov[n_iov-1].iov_base;
}
if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
/* need to set Next field of lease context if we request it */
if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
struct create_context *ccontext =
(struct create_context *)iov[n_iov-1].iov_base;
ccontext->Next =
cpu_to_le32(server->vals->create_lease_size);
}
rc = add_durable_context(iov, &n_iov, oparms,
tcon->use_persistent);
if (rc) {
cifs_small_buf_release(req);
kfree(copy_path);
kfree(lc_buf);
return rc;
}
dhc_buf = iov[n_iov-1].iov_base;
}
rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
if (rc != 0) {
cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
if (err_buf)
*err_buf = kmemdup(rsp, get_rfc1002_length(rsp) + 4,
GFP_KERNEL);
goto creat_exit;
}
oparms->fid->persistent_fid = rsp->PersistentFileId;
oparms->fid->volatile_fid = rsp->VolatileFileId;
if (buf) {
memcpy(buf, &rsp->CreationTime, 32);
buf->AllocationSize = rsp->AllocationSize;
buf->EndOfFile = rsp->EndofFile;
buf->Attributes = rsp->FileAttributes;
buf->NumberOfLinks = cpu_to_le32(1);
buf->DeletePending = 0;
}
if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE)
*oplock = parse_lease_state(server, rsp, &oparms->fid->epoch);
else
*oplock = rsp->OplockLevel;
creat_exit:
kfree(copy_path);
kfree(lc_buf);
kfree(dhc_buf);
free_rsp_buf(resp_buftype, rsp);
return rc;
}
/*
* SMB2 IOCTL is used for both IOCTLs and FSCTLs
*/
int
SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
u64 volatile_fid, u32 opcode, bool is_fsctl, char *in_data,
u32 indatalen, char **out_data, u32 *plen /* returned data len */)
{
struct smb2_ioctl_req *req;
struct smb2_ioctl_rsp *rsp;
struct smb2_sync_hdr *shdr;
struct TCP_Server_Info *server;
struct cifs_ses *ses;
struct kvec iov[2];
struct kvec rsp_iov;
int resp_buftype;
int n_iov;
int rc = 0;
int flags = 0;
cifs_dbg(FYI, "SMB2 IOCTL\n");
if (out_data != NULL)
*out_data = NULL;
/* zero out returned data len, in case of error */
if (plen)
*plen = 0;
if (tcon)
ses = tcon->ses;
else
return -EIO;
if (ses && (ses->server))
server = ses->server;
else
return -EIO;
rc = small_smb2_init(SMB2_IOCTL, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
req->CtlCode = cpu_to_le32(opcode);
req->PersistentFileId = persistent_fid;
req->VolatileFileId = volatile_fid;
if (indatalen) {
req->InputCount = cpu_to_le32(indatalen);
/* do not set InputOffset if no input data */
req->InputOffset =
cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer) - 4);
iov[1].iov_base = in_data;
iov[1].iov_len = indatalen;
n_iov = 2;
} else
n_iov = 1;
req->OutputOffset = 0;
req->OutputCount = 0; /* MBZ */
/*
* Could increase MaxOutputResponse, but that would require more
* than one credit. Windows typically sets this smaller, but for some
* ioctls it may be useful to allow server to send more. No point
* limiting what the server can send as long as fits in one credit
*/
req->MaxOutputResponse = cpu_to_le32(0xFF00); /* < 64K uses 1 credit */
if (is_fsctl)
req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
else
req->Flags = 0;
iov[0].iov_base = (char *)req;
/*
* If no input data, the size of ioctl struct in
* protocol spec still includes a 1 byte data buffer,
* but if input data passed to ioctl, we do not
* want to double count this, so we do not send
* the dummy one byte of data in iovec[0] if sending
* input data (in iovec[1]). We also must add 4 bytes
* in first iovec to allow for rfc1002 length field.
*/
if (indatalen) {
iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
inc_rfc1001_len(req, indatalen - 1);
} else
iov[0].iov_len = get_rfc1002_length(req) + 4;
rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
if ((rc != 0) && (rc != -EINVAL)) {
cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
goto ioctl_exit;
} else if (rc == -EINVAL) {
if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
(opcode != FSCTL_SRV_COPYCHUNK)) {
cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
goto ioctl_exit;
}
}
/* check if caller wants to look at return data or just return rc */
if ((plen == NULL) || (out_data == NULL))
goto ioctl_exit;
*plen = le32_to_cpu(rsp->OutputCount);
/* We check for obvious errors in the output buffer length and offset */
if (*plen == 0)
goto ioctl_exit; /* server returned no data */
else if (*plen > 0xFF00) {
cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
*plen = 0;
rc = -EIO;
goto ioctl_exit;
}
if (get_rfc1002_length(rsp) < le32_to_cpu(rsp->OutputOffset) + *plen) {
cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
le32_to_cpu(rsp->OutputOffset));
*plen = 0;
rc = -EIO;
goto ioctl_exit;
}
*out_data = kmalloc(*plen, GFP_KERNEL);
if (*out_data == NULL) {
rc = -ENOMEM;
goto ioctl_exit;
}
shdr = get_sync_hdr(rsp);
memcpy(*out_data, (char *)shdr + le32_to_cpu(rsp->OutputOffset), *plen);
ioctl_exit:
free_rsp_buf(resp_buftype, rsp);
return rc;
}
/*
* Individual callers to ioctl worker function follow
*/
int
SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid)
{
int rc;
struct compress_ioctl fsctl_input;
char *ret_data = NULL;
fsctl_input.CompressionState =
cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
FSCTL_SET_COMPRESSION, true /* is_fsctl */,
(char *)&fsctl_input /* data input */,
2 /* in data len */, &ret_data /* out data */, NULL);
cifs_dbg(FYI, "set compression rc %d\n", rc);
return rc;
}
int
SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid)
{
struct smb2_close_req *req;
struct smb2_close_rsp *rsp;
struct TCP_Server_Info *server;
struct cifs_ses *ses = tcon->ses;
struct kvec iov[1];
struct kvec rsp_iov;
int resp_buftype;
int rc = 0;
int flags = 0;
cifs_dbg(FYI, "Close\n");
if (ses && (ses->server))
server = ses->server;
else
return -EIO;
rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
req->PersistentFileId = persistent_fid;
req->VolatileFileId = volatile_fid;
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field */
iov[0].iov_len = get_rfc1002_length(req) + 4;
rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
if (rc != 0) {
cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
goto close_exit;
}
/* BB FIXME - decode close response, update inode for caching */
close_exit:
free_rsp_buf(resp_buftype, rsp);
return rc;
}
static int
validate_buf(unsigned int offset, unsigned int buffer_length,
struct smb2_hdr *hdr, unsigned int min_buf_size)
{
unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length);
char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr;
char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
char *end_of_buf = begin_of_buf + buffer_length;
if (buffer_length < min_buf_size) {
cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
buffer_length, min_buf_size);
return -EINVAL;
}
/* check if beyond RFC1001 maximum length */
if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
buffer_length, smb_len);
return -EINVAL;
}
if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
cifs_dbg(VFS, "illegal server response, bad offset to data\n");
return -EINVAL;
}
return 0;
}
/*
* If SMB buffer fields are valid, copy into temporary buffer to hold result.
* Caller must free buffer.
*/
static int
validate_and_copy_buf(unsigned int offset, unsigned int buffer_length,
struct smb2_hdr *hdr, unsigned int minbufsize,
char *data)
{
char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
int rc;
if (!data)
return -EINVAL;
rc = validate_buf(offset, buffer_length, hdr, minbufsize);
if (rc)
return rc;
memcpy(data, begin_of_buf, buffer_length);
return 0;
}
static int
query_info(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, u8 info_class,
size_t output_len, size_t min_len, void *data)
{
struct smb2_query_info_req *req;
struct smb2_query_info_rsp *rsp = NULL;
struct kvec iov[2];
struct kvec rsp_iov;
int rc = 0;
int resp_buftype;
struct TCP_Server_Info *server;
struct cifs_ses *ses = tcon->ses;
int flags = 0;
cifs_dbg(FYI, "Query Info\n");
if (ses && (ses->server))
server = ses->server;
else
return -EIO;
rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
req->InfoType = SMB2_O_INFO_FILE;
req->FileInfoClass = info_class;
req->PersistentFileId = persistent_fid;
req->VolatileFileId = volatile_fid;
/* 4 for rfc1002 length field and 1 for Buffer */
req->InputBufferOffset =
cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
req->OutputBufferLength = cpu_to_le32(output_len);
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field */
iov[0].iov_len = get_rfc1002_length(req) + 4;
rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
if (rc) {
cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
goto qinf_exit;
}
rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset),
le32_to_cpu(rsp->OutputBufferLength),
&rsp->hdr, min_len, data);
qinf_exit:
free_rsp_buf(resp_buftype, rsp);
return rc;
}
int
SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid,
struct smb2_file_all_info *data)
{
return query_info(xid, tcon, persistent_fid, volatile_fid,
FILE_ALL_INFORMATION,
sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
sizeof(struct smb2_file_all_info), data);
}
int
SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
{
return query_info(xid, tcon, persistent_fid, volatile_fid,
FILE_INTERNAL_INFORMATION,
sizeof(struct smb2_file_internal_info),
sizeof(struct smb2_file_internal_info), uniqueid);
}
/*
* This is a no-op for now. We're not really interested in the reply, but
* rather in the fact that the server sent one and that server->lstrp
* gets updated.
*
* FIXME: maybe we should consider checking that the reply matches request?
*/
static void
smb2_echo_callback(struct mid_q_entry *mid)
{
struct TCP_Server_Info *server = mid->callback_data;
struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
unsigned int credits_received = 1;
if (mid->mid_state == MID_RESPONSE_RECEIVED)
credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest);
mutex_lock(&server->srv_mutex);
DeleteMidQEntry(mid);
mutex_unlock(&server->srv_mutex);
add_credits(server, credits_received, CIFS_ECHO_OP);
}
void smb2_reconnect_server(struct work_struct *work)
{
struct TCP_Server_Info *server = container_of(work,
struct TCP_Server_Info, reconnect.work);
struct cifs_ses *ses;
struct cifs_tcon *tcon, *tcon2;
struct list_head tmp_list;
int tcon_exist = false;
/* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
mutex_lock(&server->reconnect_mutex);
INIT_LIST_HEAD(&tmp_list);
cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
spin_lock(&cifs_tcp_ses_lock);
list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
if (tcon->need_reconnect || tcon->need_reopen_files) {
tcon->tc_count++;
list_add_tail(&tcon->rlist, &tmp_list);
tcon_exist = true;
}
}
}
/*
* Get the reference to server struct to be sure that the last call of
* cifs_put_tcon() in the loop below won't release the server pointer.
*/
if (tcon_exist)
server->srv_count++;
spin_unlock(&cifs_tcp_ses_lock);
list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
if (!smb2_reconnect(SMB2_INTERNAL_CMD, tcon))
cifs_reopen_persistent_handles(tcon);
list_del_init(&tcon->rlist);
cifs_put_tcon(tcon);
}
cifs_dbg(FYI, "Reconnecting tcons finished\n");
mutex_unlock(&server->reconnect_mutex);
/* now we can safely release srv struct */
if (tcon_exist)
cifs_put_tcp_session(server, 1);
}
int
SMB2_echo(struct TCP_Server_Info *server)
{
struct smb2_echo_req *req;
int rc = 0;
struct kvec iov[2];
struct smb_rqst rqst = { .rq_iov = iov,
.rq_nvec = 2 };
cifs_dbg(FYI, "In echo request\n");
if (server->tcpStatus == CifsNeedNegotiate) {
/* No need to send echo on newly established connections */
queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
return rc;
}
rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req);
if (rc)
return rc;
req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1);
/* 4 for rfc1002 length field */
iov[0].iov_len = 4;
iov[0].iov_base = (char *)req;
iov[1].iov_len = get_rfc1002_length(req);
iov[1].iov_base = (char *)req + 4;
rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, server,
CIFS_ECHO_OP);
if (rc)
cifs_dbg(FYI, "Echo request failed: %d\n", rc);
cifs_small_buf_release(req);
return rc;
}
int
SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
u64 volatile_fid)
{
struct smb2_flush_req *req;
struct TCP_Server_Info *server;
struct cifs_ses *ses = tcon->ses;
struct kvec iov[1];
struct kvec rsp_iov;
int resp_buftype;
int rc = 0;
int flags = 0;
cifs_dbg(FYI, "Flush\n");
if (ses && (ses->server))
server = ses->server;
else
return -EIO;
rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
req->PersistentFileId = persistent_fid;
req->VolatileFileId = volatile_fid;
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field */
iov[0].iov_len = get_rfc1002_length(req) + 4;
rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
if (rc != 0)
cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
return rc;
}
/*
* To form a chain of read requests, any read requests after the first should
* have the end_of_chain boolean set to true.
*/
static int
smb2_new_read_req(void **buf, unsigned int *total_len,
struct cifs_io_parms *io_parms, unsigned int remaining_bytes,
int request_type)
{
int rc = -EACCES;
struct smb2_read_plain_req *req = NULL;
struct smb2_sync_hdr *shdr;
rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, (void **) &req,
total_len);
if (rc)
return rc;
if (io_parms->tcon->ses->server == NULL)
return -ECONNABORTED;
shdr = &req->sync_hdr;
shdr->ProcessId = cpu_to_le32(io_parms->pid);
req->PersistentFileId = io_parms->persistent_fid;
req->VolatileFileId = io_parms->volatile_fid;
req->ReadChannelInfoOffset = 0; /* reserved */
req->ReadChannelInfoLength = 0; /* reserved */
req->Channel = 0; /* reserved */
req->MinimumCount = 0;
req->Length = cpu_to_le32(io_parms->length);
req->Offset = cpu_to_le64(io_parms->offset);
if (request_type & CHAINED_REQUEST) {
if (!(request_type & END_OF_CHAIN)) {
/* next 8-byte aligned request */
*total_len = DIV_ROUND_UP(*total_len, 8) * 8;
shdr->NextCommand = cpu_to_le32(*total_len);
} else /* END_OF_CHAIN */
shdr->NextCommand = 0;
if (request_type & RELATED_REQUEST) {
shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
/*
* Related requests use info from previous read request
* in chain.
*/
shdr->SessionId = 0xFFFFFFFF;
shdr->TreeId = 0xFFFFFFFF;
req->PersistentFileId = 0xFFFFFFFF;
req->VolatileFileId = 0xFFFFFFFF;
}
}
if (remaining_bytes > io_parms->length)
req->RemainingBytes = cpu_to_le32(remaining_bytes);
else
req->RemainingBytes = 0;
*buf = req;
return rc;
}
static void
smb2_readv_callback(struct mid_q_entry *mid)
{
struct cifs_readdata *rdata = mid->callback_data;
struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
struct TCP_Server_Info *server = tcon->ses->server;
struct smb2_sync_hdr *shdr =
(struct smb2_sync_hdr *)rdata->iov[1].iov_base;
unsigned int credits_received = 1;
struct smb_rqst rqst = { .rq_iov = rdata->iov,
.rq_nvec = 2,
.rq_pages = rdata->pages,
.rq_npages = rdata->nr_pages,
.rq_pagesz = rdata->pagesz,
.rq_tailsz = rdata->tailsz };
cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
__func__, mid->mid, mid->mid_state, rdata->result,
rdata->bytes);
switch (mid->mid_state) {
case MID_RESPONSE_RECEIVED:
credits_received = le16_to_cpu(shdr->CreditRequest);
/* result already set, check signature */
if (server->sign) {
int rc;
rc = smb2_verify_signature(&rqst, server);
if (rc)
cifs_dbg(VFS, "SMB signature verification returned error = %d\n",
rc);
}
/* FIXME: should this be counted toward the initiating task? */
task_io_account_read(rdata->got_bytes);
cifs_stats_bytes_read(tcon, rdata->got_bytes);
break;
case MID_REQUEST_SUBMITTED:
case MID_RETRY_NEEDED:
rdata->result = -EAGAIN;
if (server->sign && rdata->got_bytes)
/* reset bytes number since we can not check a sign */
rdata->got_bytes = 0;
/* FIXME: should this be counted toward the initiating task? */
task_io_account_read(rdata->got_bytes);
cifs_stats_bytes_read(tcon, rdata->got_bytes);
break;
default:
if (rdata->result != -ENODATA)
rdata->result = -EIO;
}
if (rdata->result)
cifs_stats_fail_inc(tcon, SMB2_READ_HE);
queue_work(cifsiod_wq, &rdata->work);
mutex_lock(&server->srv_mutex);
DeleteMidQEntry(mid);
mutex_unlock(&server->srv_mutex);
add_credits(server, credits_received, 0);
}
/* smb2_async_readv - send an async read, and set up mid to handle result */
int
smb2_async_readv(struct cifs_readdata *rdata)
{
int rc, flags = 0;
char *buf;
struct smb2_sync_hdr *shdr;
struct cifs_io_parms io_parms;
struct smb_rqst rqst = { .rq_iov = rdata->iov,
.rq_nvec = 2 };
struct TCP_Server_Info *server;
unsigned int total_len;
__be32 req_len;
cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
__func__, rdata->offset, rdata->bytes);
io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
io_parms.offset = rdata->offset;
io_parms.length = rdata->bytes;
io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
io_parms.pid = rdata->pid;
server = io_parms.tcon->ses->server;
rc = smb2_new_read_req((void **) &buf, &total_len, &io_parms, 0, 0);
if (rc) {
if (rc == -EAGAIN && rdata->credits) {
/* credits was reset by reconnect */
rdata->credits = 0;
/* reduce in_flight value since we won't send the req */
spin_lock(&server->req_lock);
server->in_flight--;
spin_unlock(&server->req_lock);
}
return rc;
}
if (encryption_required(io_parms.tcon))
flags |= CIFS_TRANSFORM_REQ;
req_len = cpu_to_be32(total_len);
rdata->iov[0].iov_base = &req_len;
rdata->iov[0].iov_len = sizeof(__be32);
rdata->iov[1].iov_base = buf;
rdata->iov[1].iov_len = total_len;
shdr = (struct smb2_sync_hdr *)buf;
if (rdata->credits) {
shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
SMB2_MAX_BUFFER_SIZE));
shdr->CreditRequest = shdr->CreditCharge;
spin_lock(&server->req_lock);
server->credits += rdata->credits -
le16_to_cpu(shdr->CreditCharge);
spin_unlock(&server->req_lock);
wake_up(&server->request_q);
flags |= CIFS_HAS_CREDITS;
}
kref_get(&rdata->refcount);
rc = cifs_call_async(io_parms.tcon->ses->server, &rqst,
cifs_readv_receive, smb2_readv_callback,
rdata, flags);
if (rc) {
kref_put(&rdata->refcount, cifs_readdata_release);
cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
}
cifs_small_buf_release(buf);
return rc;
}
int
SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
unsigned int *nbytes, char **buf, int *buf_type)
{
int resp_buftype, rc = -EACCES;
struct smb2_read_plain_req *req = NULL;
struct smb2_read_rsp *rsp = NULL;
struct smb2_sync_hdr *shdr;
struct kvec iov[2];
struct kvec rsp_iov;
unsigned int total_len;
__be32 req_len;
struct smb_rqst rqst = { .rq_iov = iov,
.rq_nvec = 2 };
int flags = CIFS_LOG_ERROR;
struct cifs_ses *ses = io_parms->tcon->ses;
*nbytes = 0;
rc = smb2_new_read_req((void **)&req, &total_len, io_parms, 0, 0);
if (rc)
return rc;
if (encryption_required(io_parms->tcon))
flags |= CIFS_TRANSFORM_REQ;
req_len = cpu_to_be32(total_len);
iov[0].iov_base = &req_len;
iov[0].iov_len = sizeof(__be32);
iov[1].iov_base = req;
iov[1].iov_len = total_len;
rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
shdr = get_sync_hdr(rsp);
if (shdr->Status == STATUS_END_OF_FILE) {
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
return 0;
}
if (rc) {
cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
cifs_dbg(VFS, "Send error in read = %d\n", rc);
} else {
*nbytes = le32_to_cpu(rsp->DataLength);
if ((*nbytes > CIFS_MAX_MSGSIZE) ||
(*nbytes > io_parms->length)) {
cifs_dbg(FYI, "bad length %d for count %d\n",
*nbytes, io_parms->length);
rc = -EIO;
*nbytes = 0;
}
}
if (*buf) {
memcpy(*buf, (char *)shdr + rsp->DataOffset, *nbytes);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
} else if (resp_buftype != CIFS_NO_BUFFER) {
*buf = rsp_iov.iov_base;
if (resp_buftype == CIFS_SMALL_BUFFER)
*buf_type = CIFS_SMALL_BUFFER;
else if (resp_buftype == CIFS_LARGE_BUFFER)
*buf_type = CIFS_LARGE_BUFFER;
}
return rc;
}
/*
* Check the mid_state and signature on received buffer (if any), and queue the
* workqueue completion task.
*/
static void
smb2_writev_callback(struct mid_q_entry *mid)
{
struct cifs_writedata *wdata = mid->callback_data;
struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
struct TCP_Server_Info *server = tcon->ses->server;
unsigned int written;
struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
unsigned int credits_received = 1;
switch (mid->mid_state) {
case MID_RESPONSE_RECEIVED:
credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest);
wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
if (wdata->result != 0)
break;
written = le32_to_cpu(rsp->DataLength);
/*
* Mask off high 16 bits when bytes written as returned
* by the server is greater than bytes requested by the
* client. OS/2 servers are known to set incorrect
* CountHigh values.
*/
if (written > wdata->bytes)
written &= 0xFFFF;
if (written < wdata->bytes)
wdata->result = -ENOSPC;
else
wdata->bytes = written;
break;
case MID_REQUEST_SUBMITTED:
case MID_RETRY_NEEDED:
wdata->result = -EAGAIN;
break;
default:
wdata->result = -EIO;
break;
}
if (wdata->result)
cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
queue_work(cifsiod_wq, &wdata->work);
mutex_lock(&server->srv_mutex);
DeleteMidQEntry(mid);
mutex_unlock(&server->srv_mutex);
add_credits(tcon->ses->server, credits_received, 0);
}
/* smb2_async_writev - send an async write, and set up mid to handle result */
int
smb2_async_writev(struct cifs_writedata *wdata,
void (*release)(struct kref *kref))
{
int rc = -EACCES, flags = 0;
struct smb2_write_req *req = NULL;
struct smb2_sync_hdr *shdr;
struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
struct TCP_Server_Info *server = tcon->ses->server;
struct kvec iov[2];
struct smb_rqst rqst = { };
rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req);
if (rc) {
if (rc == -EAGAIN && wdata->credits) {
/* credits was reset by reconnect */
wdata->credits = 0;
/* reduce in_flight value since we won't send the req */
spin_lock(&server->req_lock);
server->in_flight--;
spin_unlock(&server->req_lock);
}
goto async_writev_out;
}
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
shdr = get_sync_hdr(req);
shdr->ProcessId = cpu_to_le32(wdata->cfile->pid);
req->PersistentFileId = wdata->cfile->fid.persistent_fid;
req->VolatileFileId = wdata->cfile->fid.volatile_fid;
req->WriteChannelInfoOffset = 0;
req->WriteChannelInfoLength = 0;
req->Channel = 0;
req->Offset = cpu_to_le64(wdata->offset);
/* 4 for rfc1002 length field */
req->DataOffset = cpu_to_le16(
offsetof(struct smb2_write_req, Buffer) - 4);
req->RemainingBytes = 0;
/* 4 for rfc1002 length field and 1 for Buffer */
iov[0].iov_len = 4;
iov[0].iov_base = req;
iov[1].iov_len = get_rfc1002_length(req) - 1;
iov[1].iov_base = (char *)req + 4;
rqst.rq_iov = iov;
rqst.rq_nvec = 2;
rqst.rq_pages = wdata->pages;
rqst.rq_npages = wdata->nr_pages;
rqst.rq_pagesz = wdata->pagesz;
rqst.rq_tailsz = wdata->tailsz;
cifs_dbg(FYI, "async write at %llu %u bytes\n",
wdata->offset, wdata->bytes);
req->Length = cpu_to_le32(wdata->bytes);
inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */);
if (wdata->credits) {
shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
SMB2_MAX_BUFFER_SIZE));
shdr->CreditRequest = shdr->CreditCharge;
spin_lock(&server->req_lock);
server->credits += wdata->credits -
le16_to_cpu(shdr->CreditCharge);
spin_unlock(&server->req_lock);
wake_up(&server->request_q);
flags |= CIFS_HAS_CREDITS;
}
kref_get(&wdata->refcount);
rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, wdata,
flags);
if (rc) {
kref_put(&wdata->refcount, release);
cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
}
async_writev_out:
cifs_small_buf_release(req);
return rc;
}
/*
* SMB2_write function gets iov pointer to kvec array with n_vec as a length.
* The length field from io_parms must be at least 1 and indicates a number of
* elements with data to write that begins with position 1 in iov array. All
* data length is specified by count.
*/
int
SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
unsigned int *nbytes, struct kvec *iov, int n_vec)
{
int rc = 0;
struct smb2_write_req *req = NULL;
struct smb2_write_rsp *rsp = NULL;
int resp_buftype;
struct kvec rsp_iov;
int flags = 0;
*nbytes = 0;
if (n_vec < 1)
return rc;
rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req);
if (rc)
return rc;
if (io_parms->tcon->ses->server == NULL)
return -ECONNABORTED;
if (encryption_required(io_parms->tcon))
flags |= CIFS_TRANSFORM_REQ;
req->hdr.sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);
req->PersistentFileId = io_parms->persistent_fid;
req->VolatileFileId = io_parms->volatile_fid;
req->WriteChannelInfoOffset = 0;
req->WriteChannelInfoLength = 0;
req->Channel = 0;
req->Length = cpu_to_le32(io_parms->length);
req->Offset = cpu_to_le64(io_parms->offset);
/* 4 for rfc1002 length field */
req->DataOffset = cpu_to_le16(
offsetof(struct smb2_write_req, Buffer) - 4);
req->RemainingBytes = 0;
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field and 1 for Buffer */
iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
/* length of entire message including data to be written */
inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */);
rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1,
&resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
if (rc) {
cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
cifs_dbg(VFS, "Send error in write = %d\n", rc);
} else
*nbytes = le32_to_cpu(rsp->DataLength);
free_rsp_buf(resp_buftype, rsp);
return rc;
}
static unsigned int
num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size)
{
int len;
unsigned int entrycount = 0;
unsigned int next_offset = 0;
FILE_DIRECTORY_INFO *entryptr;
if (bufstart == NULL)
return 0;
entryptr = (FILE_DIRECTORY_INFO *)bufstart;
while (1) {
entryptr = (FILE_DIRECTORY_INFO *)
((char *)entryptr + next_offset);
if ((char *)entryptr + size > end_of_buf) {
cifs_dbg(VFS, "malformed search entry would overflow\n");
break;
}
len = le32_to_cpu(entryptr->FileNameLength);
if ((char *)entryptr + len + size > end_of_buf) {
cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
end_of_buf);
break;
}
*lastentry = (char *)entryptr;
entrycount++;
next_offset = le32_to_cpu(entryptr->NextEntryOffset);
if (!next_offset)
break;
}
return entrycount;
}
/*
* Readdir/FindFirst
*/
int
SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, int index,
struct cifs_search_info *srch_inf)
{
struct smb2_query_directory_req *req;
struct smb2_query_directory_rsp *rsp = NULL;
struct kvec iov[2];
struct kvec rsp_iov;
int rc = 0;
int len;
int resp_buftype = CIFS_NO_BUFFER;
unsigned char *bufptr;
struct TCP_Server_Info *server;
struct cifs_ses *ses = tcon->ses;
__le16 asteriks = cpu_to_le16('*');
char *end_of_smb;
unsigned int output_size = CIFSMaxBufSize;
size_t info_buf_size;
int flags = 0;
if (ses && (ses->server))
server = ses->server;
else
return -EIO;
rc = small_smb2_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
switch (srch_inf->info_level) {
case SMB_FIND_FILE_DIRECTORY_INFO:
req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
break;
case SMB_FIND_FILE_ID_FULL_DIR_INFO:
req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
break;
default:
cifs_dbg(VFS, "info level %u isn't supported\n",
srch_inf->info_level);
rc = -EINVAL;
goto qdir_exit;
}
req->FileIndex = cpu_to_le32(index);
req->PersistentFileId = persistent_fid;
req->VolatileFileId = volatile_fid;
len = 0x2;
bufptr = req->Buffer;
memcpy(bufptr, &asteriks, len);
req->FileNameOffset =
cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1 - 4);
req->FileNameLength = cpu_to_le16(len);
/*
* BB could be 30 bytes or so longer if we used SMB2 specific
* buffer lengths, but this is safe and close enough.
*/
output_size = min_t(unsigned int, output_size, server->maxBuf);
output_size = min_t(unsigned int, output_size, 2 << 15);
req->OutputBufferLength = cpu_to_le32(output_size);
iov[0].iov_base = (char *)req;
/* 4 for RFC1001 length and 1 for Buffer */
iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
iov[1].iov_base = (char *)(req->Buffer);
iov[1].iov_len = len;
inc_rfc1001_len(req, len - 1 /* Buffer */);
rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
if (rc) {
if (rc == -ENODATA &&
rsp->hdr.sync_hdr.Status == STATUS_NO_MORE_FILES) {
srch_inf->endOfSearch = true;
rc = 0;
}
cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
goto qdir_exit;
}
rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
info_buf_size);
if (rc)
goto qdir_exit;
srch_inf->unicode = true;
if (srch_inf->ntwrk_buf_start) {
if (srch_inf->smallBuf)
cifs_small_buf_release(srch_inf->ntwrk_buf_start);
else
cifs_buf_release(srch_inf->ntwrk_buf_start);
}
srch_inf->ntwrk_buf_start = (char *)rsp;
srch_inf->srch_entries_start = srch_inf->last_entry = 4 /* rfclen */ +
(char *)&rsp->hdr + le16_to_cpu(rsp->OutputBufferOffset);
/* 4 for rfc1002 length field */
end_of_smb = get_rfc1002_length(rsp) + 4 + (char *)&rsp->hdr;
srch_inf->entries_in_buffer =
num_entries(srch_inf->srch_entries_start, end_of_smb,
&srch_inf->last_entry, info_buf_size);
srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
srch_inf->srch_entries_start, srch_inf->last_entry);
if (resp_buftype == CIFS_LARGE_BUFFER)
srch_inf->smallBuf = false;
else if (resp_buftype == CIFS_SMALL_BUFFER)
srch_inf->smallBuf = true;
else
cifs_dbg(VFS, "illegal search buffer type\n");
return rc;
qdir_exit:
free_rsp_buf(resp_buftype, rsp);
return rc;
}
static int
send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, u32 pid, int info_class,
unsigned int num, void **data, unsigned int *size)
{
struct smb2_set_info_req *req;
struct smb2_set_info_rsp *rsp = NULL;
struct kvec *iov;
struct kvec rsp_iov;
int rc = 0;
int resp_buftype;
unsigned int i;
struct TCP_Server_Info *server;
struct cifs_ses *ses = tcon->ses;
int flags = 0;
if (ses && (ses->server))
server = ses->server;
else
return -EIO;
if (!num)
return -EINVAL;
iov = kmalloc(sizeof(struct kvec) * num, GFP_KERNEL);
if (!iov)
return -ENOMEM;
rc = small_smb2_init(SMB2_SET_INFO, tcon, (void **) &req);
if (rc) {
kfree(iov);
return rc;
}
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid);
req->InfoType = SMB2_O_INFO_FILE;
req->FileInfoClass = info_class;
req->PersistentFileId = persistent_fid;
req->VolatileFileId = volatile_fid;
/* 4 for RFC1001 length and 1 for Buffer */
req->BufferOffset =
cpu_to_le16(sizeof(struct smb2_set_info_req) - 1 - 4);
req->BufferLength = cpu_to_le32(*size);
inc_rfc1001_len(req, *size - 1 /* Buffer */);
memcpy(req->Buffer, *data, *size);
iov[0].iov_base = (char *)req;
/* 4 for RFC1001 length */
iov[0].iov_len = get_rfc1002_length(req) + 4;
for (i = 1; i < num; i++) {
inc_rfc1001_len(req, size[i]);
le32_add_cpu(&req->BufferLength, size[i]);
iov[i].iov_base = (char *)data[i];
iov[i].iov_len = size[i];
}
rc = SendReceive2(xid, ses, iov, num, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
if (rc != 0)
cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
free_rsp_buf(resp_buftype, rsp);
kfree(iov);
return rc;
}
int
SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
{
struct smb2_file_rename_info info;
void **data;
unsigned int size[2];
int rc;
int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
if (!data)
return -ENOMEM;
info.ReplaceIfExists = 1; /* 1 = replace existing target with new */
/* 0 = fail if target already exists */
info.RootDirectory = 0; /* MBZ for network ops (why does spec say?) */
info.FileNameLength = cpu_to_le32(len);
data[0] = &info;
size[0] = sizeof(struct smb2_file_rename_info);
data[1] = target_file;
size[1] = len + 2 /* null */;
rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
current->tgid, FILE_RENAME_INFORMATION, 2, data,
size);
kfree(data);
return rc;
}
int
SMB2_rmdir(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid)
{
__u8 delete_pending = 1;
void *data;
unsigned int size;
data = &delete_pending;
size = 1; /* sizeof __u8 */
return send_set_info(xid, tcon, persistent_fid, volatile_fid,
current->tgid, FILE_DISPOSITION_INFORMATION, 1, &data,
&size);
}
int
SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
{
struct smb2_file_link_info info;
void **data;
unsigned int size[2];
int rc;
int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
if (!data)
return -ENOMEM;
info.ReplaceIfExists = 0; /* 1 = replace existing link with new */
/* 0 = fail if link already exists */
info.RootDirectory = 0; /* MBZ for network ops (why does spec say?) */
info.FileNameLength = cpu_to_le32(len);
data[0] = &info;
size[0] = sizeof(struct smb2_file_link_info);
data[1] = target_file;
size[1] = len + 2 /* null */;
rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
current->tgid, FILE_LINK_INFORMATION, 2, data, size);
kfree(data);
return rc;
}
int
SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
u64 volatile_fid, u32 pid, __le64 *eof, bool is_falloc)
{
struct smb2_file_eof_info info;
void *data;
unsigned int size;
info.EndOfFile = *eof;
data = &info;
size = sizeof(struct smb2_file_eof_info);
if (is_falloc)
return send_set_info(xid, tcon, persistent_fid, volatile_fid,
pid, FILE_ALLOCATION_INFORMATION, 1, &data, &size);
else
return send_set_info(xid, tcon, persistent_fid, volatile_fid,
pid, FILE_END_OF_FILE_INFORMATION, 1, &data, &size);
}
int
SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf)
{
unsigned int size;
size = sizeof(FILE_BASIC_INFO);
return send_set_info(xid, tcon, persistent_fid, volatile_fid,
current->tgid, FILE_BASIC_INFORMATION, 1,
(void **)&buf, &size);
}
int
SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
const u64 persistent_fid, const u64 volatile_fid,
__u8 oplock_level)
{
int rc;
struct smb2_oplock_break *req = NULL;
int flags = CIFS_OBREAK_OP;
cifs_dbg(FYI, "SMB2_oplock_break\n");
rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
req->VolatileFid = volatile_fid;
req->PersistentFid = persistent_fid;
req->OplockLevel = oplock_level;
req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1);
rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags);
cifs_small_buf_release(req);
if (rc) {
cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
}
return rc;
}
static void
copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
struct kstatfs *kst)
{
kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
kst->f_bfree = le64_to_cpu(pfs_inf->ActualAvailableAllocationUnits);
kst->f_bavail = le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
return;
}
static int
build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level,
int outbuf_len, u64 persistent_fid, u64 volatile_fid)
{
int rc;
struct smb2_query_info_req *req;
cifs_dbg(FYI, "Query FSInfo level %d\n", level);
if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
return -EIO;
rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
if (rc)
return rc;
req->InfoType = SMB2_O_INFO_FILESYSTEM;
req->FileInfoClass = level;
req->PersistentFileId = persistent_fid;
req->VolatileFileId = volatile_fid;
/* 4 for rfc1002 length field and 1 for pad */
req->InputBufferOffset =
cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
req->OutputBufferLength = cpu_to_le32(
outbuf_len + sizeof(struct smb2_query_info_rsp) - 1 - 4);
iov->iov_base = (char *)req;
/* 4 for rfc1002 length field */
iov->iov_len = get_rfc1002_length(req) + 4;
return 0;
}
int
SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
{
struct smb2_query_info_rsp *rsp = NULL;
struct kvec iov;
struct kvec rsp_iov;
int rc = 0;
int resp_buftype;
struct cifs_ses *ses = tcon->ses;
struct smb2_fs_full_size_info *info = NULL;
int flags = 0;
rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION,
sizeof(struct smb2_fs_full_size_info),
persistent_fid, volatile_fid);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(iov.iov_base);
if (rc) {
cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
goto qfsinf_exit;
}
rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
info = (struct smb2_fs_full_size_info *)(4 /* RFC1001 len */ +
le16_to_cpu(rsp->OutputBufferOffset) + (char *)&rsp->hdr);
rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
sizeof(struct smb2_fs_full_size_info));
if (!rc)
copy_fs_info_to_kstatfs(info, fsdata);
qfsinf_exit:
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
return rc;
}
int
SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, int level)
{
struct smb2_query_info_rsp *rsp = NULL;
struct kvec iov;
struct kvec rsp_iov;
int rc = 0;
int resp_buftype, max_len, min_len;
struct cifs_ses *ses = tcon->ses;
unsigned int rsp_len, offset;
int flags = 0;
if (level == FS_DEVICE_INFORMATION) {
max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
} else if (level == FS_ATTRIBUTE_INFORMATION) {
max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
min_len = MIN_FS_ATTR_INFO_SIZE;
} else if (level == FS_SECTOR_SIZE_INFORMATION) {
max_len = sizeof(struct smb3_fs_ss_info);
min_len = sizeof(struct smb3_fs_ss_info);
} else {
cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
return -EINVAL;
}
rc = build_qfs_info_req(&iov, tcon, level, max_len,
persistent_fid, volatile_fid);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(iov.iov_base);
if (rc) {
cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
goto qfsattr_exit;
}
rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
rsp_len = le32_to_cpu(rsp->OutputBufferLength);
offset = le16_to_cpu(rsp->OutputBufferOffset);
rc = validate_buf(offset, rsp_len, &rsp->hdr, min_len);
if (rc)
goto qfsattr_exit;
if (level == FS_ATTRIBUTE_INFORMATION)
memcpy(&tcon->fsAttrInfo, 4 /* RFC1001 len */ + offset
+ (char *)&rsp->hdr, min_t(unsigned int,
rsp_len, max_len));
else if (level == FS_DEVICE_INFORMATION)
memcpy(&tcon->fsDevInfo, 4 /* RFC1001 len */ + offset
+ (char *)&rsp->hdr, sizeof(FILE_SYSTEM_DEVICE_INFO));
else if (level == FS_SECTOR_SIZE_INFORMATION) {
struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
(4 /* RFC1001 len */ + offset + (char *)&rsp->hdr);
tcon->ss_flags = le32_to_cpu(ss_info->Flags);
tcon->perf_sector_size =
le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
}
qfsattr_exit:
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
return rc;
}
int
smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
const __u32 num_lock, struct smb2_lock_element *buf)
{
int rc = 0;
struct smb2_lock_req *req = NULL;
struct kvec iov[2];
struct kvec rsp_iov;
int resp_buf_type;
unsigned int count;
int flags = CIFS_NO_RESP;
cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
rc = small_smb2_init(SMB2_LOCK, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid);
req->LockCount = cpu_to_le16(num_lock);
req->PersistentFileId = persist_fid;
req->VolatileFileId = volatile_fid;
count = num_lock * sizeof(struct smb2_lock_element);
inc_rfc1001_len(req, count - sizeof(struct smb2_lock_element));
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field and count for all locks */
iov[0].iov_len = get_rfc1002_length(req) + 4 - count;
iov[1].iov_base = (char *)buf;
iov[1].iov_len = count;
cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
rc = SendReceive2(xid, tcon->ses, iov, 2, &resp_buf_type, flags,
&rsp_iov);
cifs_small_buf_release(req);
if (rc) {
cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
}
return rc;
}
int
SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
const __u64 length, const __u64 offset, const __u32 lock_flags,
const bool wait)
{
struct smb2_lock_element lock;
lock.Offset = cpu_to_le64(offset);
lock.Length = cpu_to_le64(length);
lock.Flags = cpu_to_le32(lock_flags);
if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
}
int
SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
__u8 *lease_key, const __le32 lease_state)
{
int rc;
struct smb2_lease_ack *req = NULL;
int flags = CIFS_OBREAK_OP;
cifs_dbg(FYI, "SMB2_lease_break\n");
rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
if (rc)
return rc;
if (encryption_required(tcon))
flags |= CIFS_TRANSFORM_REQ;
req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1);
req->StructureSize = cpu_to_le16(36);
inc_rfc1001_len(req, 12);
memcpy(req->LeaseKey, lease_key, 16);
req->LeaseState = lease_state;
rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags);
cifs_small_buf_release(req);
if (rc) {
cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
}
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_101_1 |
crossvul-cpp_data_good_623_2 | /*
* NET3 Protocol independent device support routines.
*
* 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.
*
* Derived from the non IP parts of dev.c 1.0.19
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Mark Evans, <evansmp@uhura.aston.ac.uk>
*
* Additional Authors:
* Florian la Roche <rzsfl@rz.uni-sb.de>
* Alan Cox <gw4pts@gw4pts.ampr.org>
* David Hinds <dahinds@users.sourceforge.net>
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
* Adam Sulmicki <adam@cfar.umd.edu>
* Pekka Riikonen <priikone@poesidon.pspt.fi>
*
* Changes:
* D.J. Barrow : Fixed bug where dev->refcnt gets set
* to 2 if register_netdev gets called
* before net_dev_init & also removed a
* few lines of code in the process.
* Alan Cox : device private ioctl copies fields back.
* Alan Cox : Transmit queue code does relevant
* stunts to keep the queue safe.
* Alan Cox : Fixed double lock.
* Alan Cox : Fixed promisc NULL pointer trap
* ???????? : Support the full private ioctl range
* Alan Cox : Moved ioctl permission check into
* drivers
* Tim Kordas : SIOCADDMULTI/SIOCDELMULTI
* Alan Cox : 100 backlog just doesn't cut it when
* you start doing multicast video 8)
* Alan Cox : Rewrote net_bh and list manager.
* Alan Cox : Fix ETH_P_ALL echoback lengths.
* Alan Cox : Took out transmit every packet pass
* Saved a few bytes in the ioctl handler
* Alan Cox : Network driver sets packet type before
* calling netif_rx. Saves a function
* call a packet.
* Alan Cox : Hashed net_bh()
* Richard Kooijman: Timestamp fixes.
* Alan Cox : Wrong field in SIOCGIFDSTADDR
* Alan Cox : Device lock protection.
* Alan Cox : Fixed nasty side effect of device close
* changes.
* Rudi Cilibrasi : Pass the right thing to
* set_mac_address()
* Dave Miller : 32bit quantity for the device lock to
* make it work out on a Sparc.
* Bjorn Ekwall : Added KERNELD hack.
* Alan Cox : Cleaned up the backlog initialise.
* Craig Metz : SIOCGIFCONF fix if space for under
* 1 device.
* Thomas Bogendoerfer : Return ENODEV for dev_open, if there
* is no device open function.
* Andi Kleen : Fix error reporting for SIOCGIFCONF
* Michael Chastain : Fix signed/unsigned for SIOCGIFCONF
* Cyrus Durgin : Cleaned for KMOD
* Adam Sulmicki : Bug Fix : Network Device Unload
* A network device unload needs to purge
* the backlog queue.
* Paul Rusty Russell : SIOCSIFNAME
* Pekka Riikonen : Netdev boot-time settings code
* Andrew Morton : Make unregister_netdevice wait
* indefinitely on dev->refcnt
* J Hadi Salim : - Backlog queue sampling
* - netif_rx() feedback
*/
#include <linux/uaccess.h>
#include <linux/bitops.h>
#include <linux/capability.h>
#include <linux/cpu.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/hash.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/sched/mm.h>
#include <linux/mutex.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/if_ether.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/notifier.h>
#include <linux/skbuff.h>
#include <linux/bpf.h>
#include <linux/bpf_trace.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/busy_poll.h>
#include <linux/rtnetlink.h>
#include <linux/stat.h>
#include <net/dst.h>
#include <net/dst_metadata.h>
#include <net/pkt_sched.h>
#include <net/pkt_cls.h>
#include <net/checksum.h>
#include <net/xfrm.h>
#include <linux/highmem.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/netpoll.h>
#include <linux/rcupdate.h>
#include <linux/delay.h>
#include <net/iw_handler.h>
#include <asm/current.h>
#include <linux/audit.h>
#include <linux/dmaengine.h>
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/if_arp.h>
#include <linux/if_vlan.h>
#include <linux/ip.h>
#include <net/ip.h>
#include <net/mpls.h>
#include <linux/ipv6.h>
#include <linux/in.h>
#include <linux/jhash.h>
#include <linux/random.h>
#include <trace/events/napi.h>
#include <trace/events/net.h>
#include <trace/events/skb.h>
#include <linux/pci.h>
#include <linux/inetdevice.h>
#include <linux/cpu_rmap.h>
#include <linux/static_key.h>
#include <linux/hashtable.h>
#include <linux/vmalloc.h>
#include <linux/if_macvlan.h>
#include <linux/errqueue.h>
#include <linux/hrtimer.h>
#include <linux/netfilter_ingress.h>
#include <linux/crash_dump.h>
#include <linux/sctp.h>
#include <net/udp_tunnel.h>
#include "net-sysfs.h"
/* Instead of increasing this, you should create a hash table. */
#define MAX_GRO_SKBS 8
/* This should be increased if a protocol with a bigger head is added. */
#define GRO_MAX_HEAD (MAX_HEADER + 128)
static DEFINE_SPINLOCK(ptype_lock);
static DEFINE_SPINLOCK(offload_lock);
struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
struct list_head ptype_all __read_mostly; /* Taps */
static struct list_head offload_base __read_mostly;
static int netif_rx_internal(struct sk_buff *skb);
static int call_netdevice_notifiers_info(unsigned long val,
struct net_device *dev,
struct netdev_notifier_info *info);
static struct napi_struct *napi_by_id(unsigned int napi_id);
/*
* The @dev_base_head list is protected by @dev_base_lock and the rtnl
* semaphore.
*
* Pure readers hold dev_base_lock for reading, or rcu_read_lock()
*
* Writers must hold the rtnl semaphore while they loop through the
* dev_base_head list, and hold dev_base_lock for writing when they do the
* actual updates. This allows pure readers to access the list even
* while a writer is preparing to update it.
*
* To put it another way, dev_base_lock is held for writing only to
* protect against pure readers; the rtnl semaphore provides the
* protection against other writers.
*
* See, for example usages, register_netdevice() and
* unregister_netdevice(), which must be called with the rtnl
* semaphore held.
*/
DEFINE_RWLOCK(dev_base_lock);
EXPORT_SYMBOL(dev_base_lock);
/* protects napi_hash addition/deletion and napi_gen_id */
static DEFINE_SPINLOCK(napi_hash_lock);
static unsigned int napi_gen_id = NR_CPUS;
static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
static seqcount_t devnet_rename_seq;
static inline void dev_base_seq_inc(struct net *net)
{
while (++net->dev_base_seq == 0)
;
}
static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
{
unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
}
static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
{
return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
}
static inline void rps_lock(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
spin_lock(&sd->input_pkt_queue.lock);
#endif
}
static inline void rps_unlock(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
spin_unlock(&sd->input_pkt_queue.lock);
#endif
}
/* Device list insertion */
static void list_netdevice(struct net_device *dev)
{
struct net *net = dev_net(dev);
ASSERT_RTNL();
write_lock_bh(&dev_base_lock);
list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
hlist_add_head_rcu(&dev->index_hlist,
dev_index_hash(net, dev->ifindex));
write_unlock_bh(&dev_base_lock);
dev_base_seq_inc(net);
}
/* Device list removal
* caller must respect a RCU grace period before freeing/reusing dev
*/
static void unlist_netdevice(struct net_device *dev)
{
ASSERT_RTNL();
/* Unlink dev from the device chain */
write_lock_bh(&dev_base_lock);
list_del_rcu(&dev->dev_list);
hlist_del_rcu(&dev->name_hlist);
hlist_del_rcu(&dev->index_hlist);
write_unlock_bh(&dev_base_lock);
dev_base_seq_inc(dev_net(dev));
}
/*
* Our notifier list
*/
static RAW_NOTIFIER_HEAD(netdev_chain);
/*
* Device drivers call our routines to queue packets here. We empty the
* queue in the local softnet handler.
*/
DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
EXPORT_PER_CPU_SYMBOL(softnet_data);
#ifdef CONFIG_LOCKDEP
/*
* register_netdevice() inits txq->_xmit_lock and sets lockdep class
* according to dev->type
*/
static const unsigned short netdev_lock_type[] = {
ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
static const char *const netdev_lock_name[] = {
"_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
"_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
"_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
"_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
"_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
"_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
"_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
"_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
"_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
"_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
"_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
"_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
"_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
"_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
"_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
static inline unsigned short netdev_lock_pos(unsigned short dev_type)
{
int i;
for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
if (netdev_lock_type[i] == dev_type)
return i;
/* the last key is used by default */
return ARRAY_SIZE(netdev_lock_type) - 1;
}
static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
unsigned short dev_type)
{
int i;
i = netdev_lock_pos(dev_type);
lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
netdev_lock_name[i]);
}
static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
{
int i;
i = netdev_lock_pos(dev->type);
lockdep_set_class_and_name(&dev->addr_list_lock,
&netdev_addr_lock_key[i],
netdev_lock_name[i]);
}
#else
static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
unsigned short dev_type)
{
}
static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
{
}
#endif
/*******************************************************************************
*
* Protocol management and registration routines
*
*******************************************************************************/
/*
* Add a protocol ID to the list. Now that the input handler is
* smarter we can dispense with all the messy stuff that used to be
* here.
*
* BEWARE!!! Protocol handlers, mangling input packets,
* MUST BE last in hash buckets and checking protocol handlers
* MUST start from promiscuous ptype_all chain in net_bh.
* It is true now, do not change it.
* Explanation follows: if protocol handler, mangling packet, will
* be the first on list, it is not able to sense, that packet
* is cloned and should be copied-on-write, so that it will
* change it and subsequent readers will get broken packet.
* --ANK (980803)
*/
static inline struct list_head *ptype_head(const struct packet_type *pt)
{
if (pt->type == htons(ETH_P_ALL))
return pt->dev ? &pt->dev->ptype_all : &ptype_all;
else
return pt->dev ? &pt->dev->ptype_specific :
&ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
}
/**
* dev_add_pack - add packet handler
* @pt: packet type declaration
*
* Add a protocol handler to the networking stack. The passed &packet_type
* is linked into kernel lists and may not be freed until it has been
* removed from the kernel lists.
*
* This call does not sleep therefore it can not
* guarantee all CPU's that are in middle of receiving packets
* will see the new packet type (until the next received packet).
*/
void dev_add_pack(struct packet_type *pt)
{
struct list_head *head = ptype_head(pt);
spin_lock(&ptype_lock);
list_add_rcu(&pt->list, head);
spin_unlock(&ptype_lock);
}
EXPORT_SYMBOL(dev_add_pack);
/**
* __dev_remove_pack - remove packet handler
* @pt: packet type declaration
*
* Remove a protocol handler that was previously added to the kernel
* protocol handlers by dev_add_pack(). The passed &packet_type is removed
* from the kernel lists and can be freed or reused once this function
* returns.
*
* The packet type might still be in use by receivers
* and must not be freed until after all the CPU's have gone
* through a quiescent state.
*/
void __dev_remove_pack(struct packet_type *pt)
{
struct list_head *head = ptype_head(pt);
struct packet_type *pt1;
spin_lock(&ptype_lock);
list_for_each_entry(pt1, head, list) {
if (pt == pt1) {
list_del_rcu(&pt->list);
goto out;
}
}
pr_warn("dev_remove_pack: %p not found\n", pt);
out:
spin_unlock(&ptype_lock);
}
EXPORT_SYMBOL(__dev_remove_pack);
/**
* dev_remove_pack - remove packet handler
* @pt: packet type declaration
*
* Remove a protocol handler that was previously added to the kernel
* protocol handlers by dev_add_pack(). The passed &packet_type is removed
* from the kernel lists and can be freed or reused once this function
* returns.
*
* This call sleeps to guarantee that no CPU is looking at the packet
* type after return.
*/
void dev_remove_pack(struct packet_type *pt)
{
__dev_remove_pack(pt);
synchronize_net();
}
EXPORT_SYMBOL(dev_remove_pack);
/**
* dev_add_offload - register offload handlers
* @po: protocol offload declaration
*
* Add protocol offload handlers to the networking stack. The passed
* &proto_offload is linked into kernel lists and may not be freed until
* it has been removed from the kernel lists.
*
* This call does not sleep therefore it can not
* guarantee all CPU's that are in middle of receiving packets
* will see the new offload handlers (until the next received packet).
*/
void dev_add_offload(struct packet_offload *po)
{
struct packet_offload *elem;
spin_lock(&offload_lock);
list_for_each_entry(elem, &offload_base, list) {
if (po->priority < elem->priority)
break;
}
list_add_rcu(&po->list, elem->list.prev);
spin_unlock(&offload_lock);
}
EXPORT_SYMBOL(dev_add_offload);
/**
* __dev_remove_offload - remove offload handler
* @po: packet offload declaration
*
* Remove a protocol offload handler that was previously added to the
* kernel offload handlers by dev_add_offload(). The passed &offload_type
* is removed from the kernel lists and can be freed or reused once this
* function returns.
*
* The packet type might still be in use by receivers
* and must not be freed until after all the CPU's have gone
* through a quiescent state.
*/
static void __dev_remove_offload(struct packet_offload *po)
{
struct list_head *head = &offload_base;
struct packet_offload *po1;
spin_lock(&offload_lock);
list_for_each_entry(po1, head, list) {
if (po == po1) {
list_del_rcu(&po->list);
goto out;
}
}
pr_warn("dev_remove_offload: %p not found\n", po);
out:
spin_unlock(&offload_lock);
}
/**
* dev_remove_offload - remove packet offload handler
* @po: packet offload declaration
*
* Remove a packet offload handler that was previously added to the kernel
* offload handlers by dev_add_offload(). The passed &offload_type is
* removed from the kernel lists and can be freed or reused once this
* function returns.
*
* This call sleeps to guarantee that no CPU is looking at the packet
* type after return.
*/
void dev_remove_offload(struct packet_offload *po)
{
__dev_remove_offload(po);
synchronize_net();
}
EXPORT_SYMBOL(dev_remove_offload);
/******************************************************************************
*
* Device Boot-time Settings Routines
*
******************************************************************************/
/* Boot time configuration table */
static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
/**
* netdev_boot_setup_add - add new setup entry
* @name: name of the device
* @map: configured settings for the device
*
* Adds new setup entry to the dev_boot_setup list. The function
* returns 0 on error and 1 on success. This is a generic routine to
* all netdevices.
*/
static int netdev_boot_setup_add(char *name, struct ifmap *map)
{
struct netdev_boot_setup *s;
int i;
s = dev_boot_setup;
for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
memset(s[i].name, 0, sizeof(s[i].name));
strlcpy(s[i].name, name, IFNAMSIZ);
memcpy(&s[i].map, map, sizeof(s[i].map));
break;
}
}
return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
}
/**
* netdev_boot_setup_check - check boot time settings
* @dev: the netdevice
*
* Check boot time settings for the device.
* The found settings are set for the device to be used
* later in the device probing.
* Returns 0 if no settings found, 1 if they are.
*/
int netdev_boot_setup_check(struct net_device *dev)
{
struct netdev_boot_setup *s = dev_boot_setup;
int i;
for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
!strcmp(dev->name, s[i].name)) {
dev->irq = s[i].map.irq;
dev->base_addr = s[i].map.base_addr;
dev->mem_start = s[i].map.mem_start;
dev->mem_end = s[i].map.mem_end;
return 1;
}
}
return 0;
}
EXPORT_SYMBOL(netdev_boot_setup_check);
/**
* netdev_boot_base - get address from boot time settings
* @prefix: prefix for network device
* @unit: id for network device
*
* Check boot time settings for the base address of device.
* The found settings are set for the device to be used
* later in the device probing.
* Returns 0 if no settings found.
*/
unsigned long netdev_boot_base(const char *prefix, int unit)
{
const struct netdev_boot_setup *s = dev_boot_setup;
char name[IFNAMSIZ];
int i;
sprintf(name, "%s%d", prefix, unit);
/*
* If device already registered then return base of 1
* to indicate not to probe for this interface
*/
if (__dev_get_by_name(&init_net, name))
return 1;
for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
if (!strcmp(name, s[i].name))
return s[i].map.base_addr;
return 0;
}
/*
* Saves at boot time configured settings for any netdevice.
*/
int __init netdev_boot_setup(char *str)
{
int ints[5];
struct ifmap map;
str = get_options(str, ARRAY_SIZE(ints), ints);
if (!str || !*str)
return 0;
/* Save settings */
memset(&map, 0, sizeof(map));
if (ints[0] > 0)
map.irq = ints[1];
if (ints[0] > 1)
map.base_addr = ints[2];
if (ints[0] > 2)
map.mem_start = ints[3];
if (ints[0] > 3)
map.mem_end = ints[4];
/* Add new entry to the list */
return netdev_boot_setup_add(str, &map);
}
__setup("netdev=", netdev_boot_setup);
/*******************************************************************************
*
* Device Interface Subroutines
*
*******************************************************************************/
/**
* dev_get_iflink - get 'iflink' value of a interface
* @dev: targeted interface
*
* Indicates the ifindex the interface is linked to.
* Physical interfaces have the same 'ifindex' and 'iflink' values.
*/
int dev_get_iflink(const struct net_device *dev)
{
if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
return dev->netdev_ops->ndo_get_iflink(dev);
return dev->ifindex;
}
EXPORT_SYMBOL(dev_get_iflink);
/**
* dev_fill_metadata_dst - Retrieve tunnel egress information.
* @dev: targeted interface
* @skb: The packet.
*
* For better visibility of tunnel traffic OVS needs to retrieve
* egress tunnel information for a packet. Following API allows
* user to get this info.
*/
int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
{
struct ip_tunnel_info *info;
if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
return -EINVAL;
info = skb_tunnel_info_unclone(skb);
if (!info)
return -ENOMEM;
if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
return -EINVAL;
return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
}
EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
/**
* __dev_get_by_name - find a device by its name
* @net: the applicable net namespace
* @name: name to find
*
* Find an interface by name. Must be called under RTNL semaphore
* or @dev_base_lock. If the name is found a pointer to the device
* is returned. If the name is not found then %NULL is returned. The
* reference counters are not incremented so the caller must be
* careful with locks.
*/
struct net_device *__dev_get_by_name(struct net *net, const char *name)
{
struct net_device *dev;
struct hlist_head *head = dev_name_hash(net, name);
hlist_for_each_entry(dev, head, name_hlist)
if (!strncmp(dev->name, name, IFNAMSIZ))
return dev;
return NULL;
}
EXPORT_SYMBOL(__dev_get_by_name);
/**
* dev_get_by_name_rcu - find a device by its name
* @net: the applicable net namespace
* @name: name to find
*
* Find an interface by name.
* If the name is found a pointer to the device is returned.
* If the name is not found then %NULL is returned.
* The reference counters are not incremented so the caller must be
* careful with locks. The caller must hold RCU lock.
*/
struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
{
struct net_device *dev;
struct hlist_head *head = dev_name_hash(net, name);
hlist_for_each_entry_rcu(dev, head, name_hlist)
if (!strncmp(dev->name, name, IFNAMSIZ))
return dev;
return NULL;
}
EXPORT_SYMBOL(dev_get_by_name_rcu);
/**
* dev_get_by_name - find a device by its name
* @net: the applicable net namespace
* @name: name to find
*
* Find an interface by name. This can be called from any
* context and does its own locking. The returned handle has
* the usage count incremented and the caller must use dev_put() to
* release it when it is no longer needed. %NULL is returned if no
* matching device is found.
*/
struct net_device *dev_get_by_name(struct net *net, const char *name)
{
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, name);
if (dev)
dev_hold(dev);
rcu_read_unlock();
return dev;
}
EXPORT_SYMBOL(dev_get_by_name);
/**
* __dev_get_by_index - find a device by its ifindex
* @net: the applicable net namespace
* @ifindex: index of device
*
* Search for an interface by index. Returns %NULL if the device
* is not found or a pointer to the device. The device has not
* had its reference counter increased so the caller must be careful
* about locking. The caller must hold either the RTNL semaphore
* or @dev_base_lock.
*/
struct net_device *__dev_get_by_index(struct net *net, int ifindex)
{
struct net_device *dev;
struct hlist_head *head = dev_index_hash(net, ifindex);
hlist_for_each_entry(dev, head, index_hlist)
if (dev->ifindex == ifindex)
return dev;
return NULL;
}
EXPORT_SYMBOL(__dev_get_by_index);
/**
* dev_get_by_index_rcu - find a device by its ifindex
* @net: the applicable net namespace
* @ifindex: index of device
*
* Search for an interface by index. Returns %NULL if the device
* is not found or a pointer to the device. The device has not
* had its reference counter increased so the caller must be careful
* about locking. The caller must hold RCU lock.
*/
struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
{
struct net_device *dev;
struct hlist_head *head = dev_index_hash(net, ifindex);
hlist_for_each_entry_rcu(dev, head, index_hlist)
if (dev->ifindex == ifindex)
return dev;
return NULL;
}
EXPORT_SYMBOL(dev_get_by_index_rcu);
/**
* dev_get_by_index - find a device by its ifindex
* @net: the applicable net namespace
* @ifindex: index of device
*
* Search for an interface by index. Returns NULL if the device
* is not found or a pointer to the device. The device returned has
* had a reference added and the pointer is safe until the user calls
* dev_put to indicate they have finished with it.
*/
struct net_device *dev_get_by_index(struct net *net, int ifindex)
{
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_index_rcu(net, ifindex);
if (dev)
dev_hold(dev);
rcu_read_unlock();
return dev;
}
EXPORT_SYMBOL(dev_get_by_index);
/**
* dev_get_by_napi_id - find a device by napi_id
* @napi_id: ID of the NAPI struct
*
* Search for an interface by NAPI ID. Returns %NULL if the device
* is not found or a pointer to the device. The device has not had
* its reference counter increased so the caller must be careful
* about locking. The caller must hold RCU lock.
*/
struct net_device *dev_get_by_napi_id(unsigned int napi_id)
{
struct napi_struct *napi;
WARN_ON_ONCE(!rcu_read_lock_held());
if (napi_id < MIN_NAPI_ID)
return NULL;
napi = napi_by_id(napi_id);
return napi ? napi->dev : NULL;
}
EXPORT_SYMBOL(dev_get_by_napi_id);
/**
* netdev_get_name - get a netdevice name, knowing its ifindex.
* @net: network namespace
* @name: a pointer to the buffer where the name will be stored.
* @ifindex: the ifindex of the interface to get the name from.
*
* The use of raw_seqcount_begin() and cond_resched() before
* retrying is required as we want to give the writers a chance
* to complete when CONFIG_PREEMPT is not set.
*/
int netdev_get_name(struct net *net, char *name, int ifindex)
{
struct net_device *dev;
unsigned int seq;
retry:
seq = raw_seqcount_begin(&devnet_rename_seq);
rcu_read_lock();
dev = dev_get_by_index_rcu(net, ifindex);
if (!dev) {
rcu_read_unlock();
return -ENODEV;
}
strcpy(name, dev->name);
rcu_read_unlock();
if (read_seqcount_retry(&devnet_rename_seq, seq)) {
cond_resched();
goto retry;
}
return 0;
}
/**
* dev_getbyhwaddr_rcu - find a device by its hardware address
* @net: the applicable net namespace
* @type: media type of device
* @ha: hardware address
*
* Search for an interface by MAC address. Returns NULL if the device
* is not found or a pointer to the device.
* The caller must hold RCU or RTNL.
* The returned device has not had its ref count increased
* and the caller must therefore be careful about locking
*
*/
struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
const char *ha)
{
struct net_device *dev;
for_each_netdev_rcu(net, dev)
if (dev->type == type &&
!memcmp(dev->dev_addr, ha, dev->addr_len))
return dev;
return NULL;
}
EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
{
struct net_device *dev;
ASSERT_RTNL();
for_each_netdev(net, dev)
if (dev->type == type)
return dev;
return NULL;
}
EXPORT_SYMBOL(__dev_getfirstbyhwtype);
struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
{
struct net_device *dev, *ret = NULL;
rcu_read_lock();
for_each_netdev_rcu(net, dev)
if (dev->type == type) {
dev_hold(dev);
ret = dev;
break;
}
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL(dev_getfirstbyhwtype);
/**
* __dev_get_by_flags - find any device with given flags
* @net: the applicable net namespace
* @if_flags: IFF_* values
* @mask: bitmask of bits in if_flags to check
*
* Search for any interface with the given flags. Returns NULL if a device
* is not found or a pointer to the device. Must be called inside
* rtnl_lock(), and result refcount is unchanged.
*/
struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
unsigned short mask)
{
struct net_device *dev, *ret;
ASSERT_RTNL();
ret = NULL;
for_each_netdev(net, dev) {
if (((dev->flags ^ if_flags) & mask) == 0) {
ret = dev;
break;
}
}
return ret;
}
EXPORT_SYMBOL(__dev_get_by_flags);
/**
* dev_valid_name - check if name is okay for network device
* @name: name string
*
* Network device names need to be valid file names to
* to allow sysfs to work. We also disallow any kind of
* whitespace.
*/
bool dev_valid_name(const char *name)
{
if (*name == '\0')
return false;
if (strlen(name) >= IFNAMSIZ)
return false;
if (!strcmp(name, ".") || !strcmp(name, ".."))
return false;
while (*name) {
if (*name == '/' || *name == ':' || isspace(*name))
return false;
name++;
}
return true;
}
EXPORT_SYMBOL(dev_valid_name);
/**
* __dev_alloc_name - allocate a name for a device
* @net: network namespace to allocate the device name in
* @name: name format string
* @buf: scratch buffer and result name string
*
* Passed a format string - eg "lt%d" it will try and find a suitable
* id. It scans list of devices to build up a free map, then chooses
* the first empty slot. The caller must hold the dev_base or rtnl lock
* while allocating the name and adding the device in order to avoid
* duplicates.
* Limited to bits_per_byte * page size devices (ie 32K on most platforms).
* Returns the number of the unit assigned or a negative errno code.
*/
static int __dev_alloc_name(struct net *net, const char *name, char *buf)
{
int i = 0;
const char *p;
const int max_netdevices = 8*PAGE_SIZE;
unsigned long *inuse;
struct net_device *d;
p = strnchr(name, IFNAMSIZ-1, '%');
if (p) {
/*
* Verify the string as this thing may have come from
* the user. There must be either one "%d" and no other "%"
* characters.
*/
if (p[1] != 'd' || strchr(p + 2, '%'))
return -EINVAL;
/* Use one page as a bit array of possible slots */
inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
if (!inuse)
return -ENOMEM;
for_each_netdev(net, d) {
if (!sscanf(d->name, name, &i))
continue;
if (i < 0 || i >= max_netdevices)
continue;
/* avoid cases where sscanf is not exact inverse of printf */
snprintf(buf, IFNAMSIZ, name, i);
if (!strncmp(buf, d->name, IFNAMSIZ))
set_bit(i, inuse);
}
i = find_first_zero_bit(inuse, max_netdevices);
free_page((unsigned long) inuse);
}
if (buf != name)
snprintf(buf, IFNAMSIZ, name, i);
if (!__dev_get_by_name(net, buf))
return i;
/* It is possible to run out of possible slots
* when the name is long and there isn't enough space left
* for the digits, or if all bits are used.
*/
return -ENFILE;
}
/**
* dev_alloc_name - allocate a name for a device
* @dev: device
* @name: name format string
*
* Passed a format string - eg "lt%d" it will try and find a suitable
* id. It scans list of devices to build up a free map, then chooses
* the first empty slot. The caller must hold the dev_base or rtnl lock
* while allocating the name and adding the device in order to avoid
* duplicates.
* Limited to bits_per_byte * page size devices (ie 32K on most platforms).
* Returns the number of the unit assigned or a negative errno code.
*/
int dev_alloc_name(struct net_device *dev, const char *name)
{
char buf[IFNAMSIZ];
struct net *net;
int ret;
BUG_ON(!dev_net(dev));
net = dev_net(dev);
ret = __dev_alloc_name(net, name, buf);
if (ret >= 0)
strlcpy(dev->name, buf, IFNAMSIZ);
return ret;
}
EXPORT_SYMBOL(dev_alloc_name);
static int dev_alloc_name_ns(struct net *net,
struct net_device *dev,
const char *name)
{
char buf[IFNAMSIZ];
int ret;
ret = __dev_alloc_name(net, name, buf);
if (ret >= 0)
strlcpy(dev->name, buf, IFNAMSIZ);
return ret;
}
int dev_get_valid_name(struct net *net, struct net_device *dev,
const char *name)
{
BUG_ON(!net);
if (!dev_valid_name(name))
return -EINVAL;
if (strchr(name, '%'))
return dev_alloc_name_ns(net, dev, name);
else if (__dev_get_by_name(net, name))
return -EEXIST;
else if (dev->name != name)
strlcpy(dev->name, name, IFNAMSIZ);
return 0;
}
EXPORT_SYMBOL(dev_get_valid_name);
/**
* dev_change_name - change name of a device
* @dev: device
* @newname: name (or format string) must be at least IFNAMSIZ
*
* Change name of a device, can pass format strings "eth%d".
* for wildcarding.
*/
int dev_change_name(struct net_device *dev, const char *newname)
{
unsigned char old_assign_type;
char oldname[IFNAMSIZ];
int err = 0;
int ret;
struct net *net;
ASSERT_RTNL();
BUG_ON(!dev_net(dev));
net = dev_net(dev);
if (dev->flags & IFF_UP)
return -EBUSY;
write_seqcount_begin(&devnet_rename_seq);
if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
write_seqcount_end(&devnet_rename_seq);
return 0;
}
memcpy(oldname, dev->name, IFNAMSIZ);
err = dev_get_valid_name(net, dev, newname);
if (err < 0) {
write_seqcount_end(&devnet_rename_seq);
return err;
}
if (oldname[0] && !strchr(oldname, '%'))
netdev_info(dev, "renamed from %s\n", oldname);
old_assign_type = dev->name_assign_type;
dev->name_assign_type = NET_NAME_RENAMED;
rollback:
ret = device_rename(&dev->dev, dev->name);
if (ret) {
memcpy(dev->name, oldname, IFNAMSIZ);
dev->name_assign_type = old_assign_type;
write_seqcount_end(&devnet_rename_seq);
return ret;
}
write_seqcount_end(&devnet_rename_seq);
netdev_adjacent_rename_links(dev, oldname);
write_lock_bh(&dev_base_lock);
hlist_del_rcu(&dev->name_hlist);
write_unlock_bh(&dev_base_lock);
synchronize_rcu();
write_lock_bh(&dev_base_lock);
hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
write_unlock_bh(&dev_base_lock);
ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
ret = notifier_to_errno(ret);
if (ret) {
/* err >= 0 after dev_alloc_name() or stores the first errno */
if (err >= 0) {
err = ret;
write_seqcount_begin(&devnet_rename_seq);
memcpy(dev->name, oldname, IFNAMSIZ);
memcpy(oldname, newname, IFNAMSIZ);
dev->name_assign_type = old_assign_type;
old_assign_type = NET_NAME_RENAMED;
goto rollback;
} else {
pr_err("%s: name change rollback failed: %d\n",
dev->name, ret);
}
}
return err;
}
/**
* dev_set_alias - change ifalias of a device
* @dev: device
* @alias: name up to IFALIASZ
* @len: limit of bytes to copy from info
*
* Set ifalias for a device,
*/
int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
{
char *new_ifalias;
ASSERT_RTNL();
if (len >= IFALIASZ)
return -EINVAL;
if (!len) {
kfree(dev->ifalias);
dev->ifalias = NULL;
return 0;
}
new_ifalias = krealloc(dev->ifalias, len + 1, GFP_KERNEL);
if (!new_ifalias)
return -ENOMEM;
dev->ifalias = new_ifalias;
memcpy(dev->ifalias, alias, len);
dev->ifalias[len] = 0;
return len;
}
/**
* netdev_features_change - device changes features
* @dev: device to cause notification
*
* Called to indicate a device has changed features.
*/
void netdev_features_change(struct net_device *dev)
{
call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
}
EXPORT_SYMBOL(netdev_features_change);
/**
* netdev_state_change - device changes state
* @dev: device to cause notification
*
* Called to indicate a device has changed state. This function calls
* the notifier chains for netdev_chain and sends a NEWLINK message
* to the routing socket.
*/
void netdev_state_change(struct net_device *dev)
{
if (dev->flags & IFF_UP) {
struct netdev_notifier_change_info change_info;
change_info.flags_changed = 0;
call_netdevice_notifiers_info(NETDEV_CHANGE, dev,
&change_info.info);
rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
}
}
EXPORT_SYMBOL(netdev_state_change);
/**
* netdev_notify_peers - notify network peers about existence of @dev
* @dev: network device
*
* Generate traffic such that interested network peers are aware of
* @dev, such as by generating a gratuitous ARP. This may be used when
* a device wants to inform the rest of the network about some sort of
* reconfiguration such as a failover event or virtual machine
* migration.
*/
void netdev_notify_peers(struct net_device *dev)
{
rtnl_lock();
call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
rtnl_unlock();
}
EXPORT_SYMBOL(netdev_notify_peers);
static int __dev_open(struct net_device *dev)
{
const struct net_device_ops *ops = dev->netdev_ops;
int ret;
ASSERT_RTNL();
if (!netif_device_present(dev))
return -ENODEV;
/* Block netpoll from trying to do any rx path servicing.
* If we don't do this there is a chance ndo_poll_controller
* or ndo_poll may be running while we open the device
*/
netpoll_poll_disable(dev);
ret = call_netdevice_notifiers(NETDEV_PRE_UP, dev);
ret = notifier_to_errno(ret);
if (ret)
return ret;
set_bit(__LINK_STATE_START, &dev->state);
if (ops->ndo_validate_addr)
ret = ops->ndo_validate_addr(dev);
if (!ret && ops->ndo_open)
ret = ops->ndo_open(dev);
netpoll_poll_enable(dev);
if (ret)
clear_bit(__LINK_STATE_START, &dev->state);
else {
dev->flags |= IFF_UP;
dev_set_rx_mode(dev);
dev_activate(dev);
add_device_randomness(dev->dev_addr, dev->addr_len);
}
return ret;
}
/**
* dev_open - prepare an interface for use.
* @dev: device to open
*
* Takes a device from down to up state. The device's private open
* function is invoked and then the multicast lists are loaded. Finally
* the device is moved into the up state and a %NETDEV_UP message is
* sent to the netdev notifier chain.
*
* Calling this function on an active interface is a nop. On a failure
* a negative errno code is returned.
*/
int dev_open(struct net_device *dev)
{
int ret;
if (dev->flags & IFF_UP)
return 0;
ret = __dev_open(dev);
if (ret < 0)
return ret;
rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
call_netdevice_notifiers(NETDEV_UP, dev);
return ret;
}
EXPORT_SYMBOL(dev_open);
static void __dev_close_many(struct list_head *head)
{
struct net_device *dev;
ASSERT_RTNL();
might_sleep();
list_for_each_entry(dev, head, close_list) {
/* Temporarily disable netpoll until the interface is down */
netpoll_poll_disable(dev);
call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
clear_bit(__LINK_STATE_START, &dev->state);
/* Synchronize to scheduled poll. We cannot touch poll list, it
* can be even on different cpu. So just clear netif_running().
*
* dev->stop() will invoke napi_disable() on all of it's
* napi_struct instances on this device.
*/
smp_mb__after_atomic(); /* Commit netif_running(). */
}
dev_deactivate_many(head);
list_for_each_entry(dev, head, close_list) {
const struct net_device_ops *ops = dev->netdev_ops;
/*
* Call the device specific close. This cannot fail.
* Only if device is UP
*
* We allow it to be called even after a DETACH hot-plug
* event.
*/
if (ops->ndo_stop)
ops->ndo_stop(dev);
dev->flags &= ~IFF_UP;
netpoll_poll_enable(dev);
}
}
static void __dev_close(struct net_device *dev)
{
LIST_HEAD(single);
list_add(&dev->close_list, &single);
__dev_close_many(&single);
list_del(&single);
}
void dev_close_many(struct list_head *head, bool unlink)
{
struct net_device *dev, *tmp;
/* Remove the devices that don't need to be closed */
list_for_each_entry_safe(dev, tmp, head, close_list)
if (!(dev->flags & IFF_UP))
list_del_init(&dev->close_list);
__dev_close_many(head);
list_for_each_entry_safe(dev, tmp, head, close_list) {
rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
call_netdevice_notifiers(NETDEV_DOWN, dev);
if (unlink)
list_del_init(&dev->close_list);
}
}
EXPORT_SYMBOL(dev_close_many);
/**
* dev_close - shutdown an interface.
* @dev: device to shutdown
*
* This function moves an active device into down state. A
* %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
* is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
* chain.
*/
void dev_close(struct net_device *dev)
{
if (dev->flags & IFF_UP) {
LIST_HEAD(single);
list_add(&dev->close_list, &single);
dev_close_many(&single, true);
list_del(&single);
}
}
EXPORT_SYMBOL(dev_close);
/**
* dev_disable_lro - disable Large Receive Offload on a device
* @dev: device
*
* Disable Large Receive Offload (LRO) on a net device. Must be
* called under RTNL. This is needed if received packets may be
* forwarded to another interface.
*/
void dev_disable_lro(struct net_device *dev)
{
struct net_device *lower_dev;
struct list_head *iter;
dev->wanted_features &= ~NETIF_F_LRO;
netdev_update_features(dev);
if (unlikely(dev->features & NETIF_F_LRO))
netdev_WARN(dev, "failed to disable LRO!\n");
netdev_for_each_lower_dev(dev, lower_dev, iter)
dev_disable_lro(lower_dev);
}
EXPORT_SYMBOL(dev_disable_lro);
static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
struct net_device *dev)
{
struct netdev_notifier_info info;
netdev_notifier_info_init(&info, dev);
return nb->notifier_call(nb, val, &info);
}
static int dev_boot_phase = 1;
/**
* register_netdevice_notifier - register a network notifier block
* @nb: notifier
*
* Register a notifier to be called when network device events occur.
* The notifier passed is linked into the kernel structures and must
* not be reused until it has been unregistered. A negative errno code
* is returned on a failure.
*
* When registered all registration and up events are replayed
* to the new notifier to allow device to have a race free
* view of the network device list.
*/
int register_netdevice_notifier(struct notifier_block *nb)
{
struct net_device *dev;
struct net_device *last;
struct net *net;
int err;
rtnl_lock();
err = raw_notifier_chain_register(&netdev_chain, nb);
if (err)
goto unlock;
if (dev_boot_phase)
goto unlock;
for_each_net(net) {
for_each_netdev(net, dev) {
err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
err = notifier_to_errno(err);
if (err)
goto rollback;
if (!(dev->flags & IFF_UP))
continue;
call_netdevice_notifier(nb, NETDEV_UP, dev);
}
}
unlock:
rtnl_unlock();
return err;
rollback:
last = dev;
for_each_net(net) {
for_each_netdev(net, dev) {
if (dev == last)
goto outroll;
if (dev->flags & IFF_UP) {
call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
dev);
call_netdevice_notifier(nb, NETDEV_DOWN, dev);
}
call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
}
}
outroll:
raw_notifier_chain_unregister(&netdev_chain, nb);
goto unlock;
}
EXPORT_SYMBOL(register_netdevice_notifier);
/**
* unregister_netdevice_notifier - unregister a network notifier block
* @nb: notifier
*
* Unregister a notifier previously registered by
* register_netdevice_notifier(). The notifier is unlinked into the
* kernel structures and may then be reused. A negative errno code
* is returned on a failure.
*
* After unregistering unregister and down device events are synthesized
* for all devices on the device list to the removed notifier to remove
* the need for special case cleanup code.
*/
int unregister_netdevice_notifier(struct notifier_block *nb)
{
struct net_device *dev;
struct net *net;
int err;
rtnl_lock();
err = raw_notifier_chain_unregister(&netdev_chain, nb);
if (err)
goto unlock;
for_each_net(net) {
for_each_netdev(net, dev) {
if (dev->flags & IFF_UP) {
call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
dev);
call_netdevice_notifier(nb, NETDEV_DOWN, dev);
}
call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
}
}
unlock:
rtnl_unlock();
return err;
}
EXPORT_SYMBOL(unregister_netdevice_notifier);
/**
* call_netdevice_notifiers_info - call all network notifier blocks
* @val: value passed unmodified to notifier function
* @dev: net_device pointer passed unmodified to notifier function
* @info: notifier information data
*
* Call all network notifier blocks. Parameters and return value
* are as for raw_notifier_call_chain().
*/
static int call_netdevice_notifiers_info(unsigned long val,
struct net_device *dev,
struct netdev_notifier_info *info)
{
ASSERT_RTNL();
netdev_notifier_info_init(info, dev);
return raw_notifier_call_chain(&netdev_chain, val, info);
}
/**
* call_netdevice_notifiers - call all network notifier blocks
* @val: value passed unmodified to notifier function
* @dev: net_device pointer passed unmodified to notifier function
*
* Call all network notifier blocks. Parameters and return value
* are as for raw_notifier_call_chain().
*/
int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
{
struct netdev_notifier_info info;
return call_netdevice_notifiers_info(val, dev, &info);
}
EXPORT_SYMBOL(call_netdevice_notifiers);
#ifdef CONFIG_NET_INGRESS
static struct static_key ingress_needed __read_mostly;
void net_inc_ingress_queue(void)
{
static_key_slow_inc(&ingress_needed);
}
EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
void net_dec_ingress_queue(void)
{
static_key_slow_dec(&ingress_needed);
}
EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
#endif
#ifdef CONFIG_NET_EGRESS
static struct static_key egress_needed __read_mostly;
void net_inc_egress_queue(void)
{
static_key_slow_inc(&egress_needed);
}
EXPORT_SYMBOL_GPL(net_inc_egress_queue);
void net_dec_egress_queue(void)
{
static_key_slow_dec(&egress_needed);
}
EXPORT_SYMBOL_GPL(net_dec_egress_queue);
#endif
static struct static_key netstamp_needed __read_mostly;
#ifdef HAVE_JUMP_LABEL
static atomic_t netstamp_needed_deferred;
static atomic_t netstamp_wanted;
static void netstamp_clear(struct work_struct *work)
{
int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
int wanted;
wanted = atomic_add_return(deferred, &netstamp_wanted);
if (wanted > 0)
static_key_enable(&netstamp_needed);
else
static_key_disable(&netstamp_needed);
}
static DECLARE_WORK(netstamp_work, netstamp_clear);
#endif
void net_enable_timestamp(void)
{
#ifdef HAVE_JUMP_LABEL
int wanted;
while (1) {
wanted = atomic_read(&netstamp_wanted);
if (wanted <= 0)
break;
if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
return;
}
atomic_inc(&netstamp_needed_deferred);
schedule_work(&netstamp_work);
#else
static_key_slow_inc(&netstamp_needed);
#endif
}
EXPORT_SYMBOL(net_enable_timestamp);
void net_disable_timestamp(void)
{
#ifdef HAVE_JUMP_LABEL
int wanted;
while (1) {
wanted = atomic_read(&netstamp_wanted);
if (wanted <= 1)
break;
if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
return;
}
atomic_dec(&netstamp_needed_deferred);
schedule_work(&netstamp_work);
#else
static_key_slow_dec(&netstamp_needed);
#endif
}
EXPORT_SYMBOL(net_disable_timestamp);
static inline void net_timestamp_set(struct sk_buff *skb)
{
skb->tstamp = 0;
if (static_key_false(&netstamp_needed))
__net_timestamp(skb);
}
#define net_timestamp_check(COND, SKB) \
if (static_key_false(&netstamp_needed)) { \
if ((COND) && !(SKB)->tstamp) \
__net_timestamp(SKB); \
} \
bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
{
unsigned int len;
if (!(dev->flags & IFF_UP))
return false;
len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
if (skb->len <= len)
return true;
/* if TSO is enabled, we don't care about the length as the packet
* could be forwarded without being segmented before
*/
if (skb_is_gso(skb))
return true;
return false;
}
EXPORT_SYMBOL_GPL(is_skb_forwardable);
int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
{
int ret = ____dev_forward_skb(dev, skb);
if (likely(!ret)) {
skb->protocol = eth_type_trans(skb, dev);
skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
}
return ret;
}
EXPORT_SYMBOL_GPL(__dev_forward_skb);
/**
* dev_forward_skb - loopback an skb to another netif
*
* @dev: destination network device
* @skb: buffer to forward
*
* return values:
* NET_RX_SUCCESS (no congestion)
* NET_RX_DROP (packet was dropped, but freed)
*
* dev_forward_skb can be used for injecting an skb from the
* start_xmit function of one device into the receive queue
* of another device.
*
* The receiving device may be in another namespace, so
* we have to clear all information in the skb that could
* impact namespace isolation.
*/
int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
{
return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
}
EXPORT_SYMBOL_GPL(dev_forward_skb);
static inline int deliver_skb(struct sk_buff *skb,
struct packet_type *pt_prev,
struct net_device *orig_dev)
{
if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
return -ENOMEM;
refcount_inc(&skb->users);
return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
}
static inline void deliver_ptype_list_skb(struct sk_buff *skb,
struct packet_type **pt,
struct net_device *orig_dev,
__be16 type,
struct list_head *ptype_list)
{
struct packet_type *ptype, *pt_prev = *pt;
list_for_each_entry_rcu(ptype, ptype_list, list) {
if (ptype->type != type)
continue;
if (pt_prev)
deliver_skb(skb, pt_prev, orig_dev);
pt_prev = ptype;
}
*pt = pt_prev;
}
static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
{
if (!ptype->af_packet_priv || !skb->sk)
return false;
if (ptype->id_match)
return ptype->id_match(ptype, skb->sk);
else if ((struct sock *)ptype->af_packet_priv == skb->sk)
return true;
return false;
}
/*
* Support routine. Sends outgoing frames to any network
* taps currently in use.
*/
void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
{
struct packet_type *ptype;
struct sk_buff *skb2 = NULL;
struct packet_type *pt_prev = NULL;
struct list_head *ptype_list = &ptype_all;
rcu_read_lock();
again:
list_for_each_entry_rcu(ptype, ptype_list, list) {
/* Never send packets back to the socket
* they originated from - MvS (miquels@drinkel.ow.org)
*/
if (skb_loop_sk(ptype, skb))
continue;
if (pt_prev) {
deliver_skb(skb2, pt_prev, skb->dev);
pt_prev = ptype;
continue;
}
/* need to clone skb, done only once */
skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
goto out_unlock;
net_timestamp_set(skb2);
/* skb->nh should be correctly
* set by sender, so that the second statement is
* just protection against buggy protocols.
*/
skb_reset_mac_header(skb2);
if (skb_network_header(skb2) < skb2->data ||
skb_network_header(skb2) > skb_tail_pointer(skb2)) {
net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
ntohs(skb2->protocol),
dev->name);
skb_reset_network_header(skb2);
}
skb2->transport_header = skb2->network_header;
skb2->pkt_type = PACKET_OUTGOING;
pt_prev = ptype;
}
if (ptype_list == &ptype_all) {
ptype_list = &dev->ptype_all;
goto again;
}
out_unlock:
if (pt_prev) {
if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
else
kfree_skb(skb2);
}
rcu_read_unlock();
}
EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
/**
* netif_setup_tc - Handle tc mappings on real_num_tx_queues change
* @dev: Network device
* @txq: number of queues available
*
* If real_num_tx_queues is changed the tc mappings may no longer be
* valid. To resolve this verify the tc mapping remains valid and if
* not NULL the mapping. With no priorities mapping to this
* offset/count pair it will no longer be used. In the worst case TC0
* is invalid nothing can be done so disable priority mappings. If is
* expected that drivers will fix this mapping if they can before
* calling netif_set_real_num_tx_queues.
*/
static void netif_setup_tc(struct net_device *dev, unsigned int txq)
{
int i;
struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
/* If TC0 is invalidated disable TC mapping */
if (tc->offset + tc->count > txq) {
pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
dev->num_tc = 0;
return;
}
/* Invalidated prio to tc mappings set to TC0 */
for (i = 1; i < TC_BITMASK + 1; i++) {
int q = netdev_get_prio_tc_map(dev, i);
tc = &dev->tc_to_txq[q];
if (tc->offset + tc->count > txq) {
pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
i, q);
netdev_set_prio_tc_map(dev, i, 0);
}
}
}
int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
{
if (dev->num_tc) {
struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
int i;
for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
if ((txq - tc->offset) < tc->count)
return i;
}
return -1;
}
return 0;
}
#ifdef CONFIG_XPS
static DEFINE_MUTEX(xps_map_mutex);
#define xmap_dereference(P) \
rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
int tci, u16 index)
{
struct xps_map *map = NULL;
int pos;
if (dev_maps)
map = xmap_dereference(dev_maps->cpu_map[tci]);
if (!map)
return false;
for (pos = map->len; pos--;) {
if (map->queues[pos] != index)
continue;
if (map->len > 1) {
map->queues[pos] = map->queues[--map->len];
break;
}
RCU_INIT_POINTER(dev_maps->cpu_map[tci], NULL);
kfree_rcu(map, rcu);
return false;
}
return true;
}
static bool remove_xps_queue_cpu(struct net_device *dev,
struct xps_dev_maps *dev_maps,
int cpu, u16 offset, u16 count)
{
int num_tc = dev->num_tc ? : 1;
bool active = false;
int tci;
for (tci = cpu * num_tc; num_tc--; tci++) {
int i, j;
for (i = count, j = offset; i--; j++) {
if (!remove_xps_queue(dev_maps, cpu, j))
break;
}
active |= i < 0;
}
return active;
}
static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
u16 count)
{
struct xps_dev_maps *dev_maps;
int cpu, i;
bool active = false;
mutex_lock(&xps_map_mutex);
dev_maps = xmap_dereference(dev->xps_maps);
if (!dev_maps)
goto out_no_maps;
for_each_possible_cpu(cpu)
active |= remove_xps_queue_cpu(dev, dev_maps, cpu,
offset, count);
if (!active) {
RCU_INIT_POINTER(dev->xps_maps, NULL);
kfree_rcu(dev_maps, rcu);
}
for (i = offset + (count - 1); count--; i--)
netdev_queue_numa_node_write(netdev_get_tx_queue(dev, i),
NUMA_NO_NODE);
out_no_maps:
mutex_unlock(&xps_map_mutex);
}
static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
{
netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
}
static struct xps_map *expand_xps_map(struct xps_map *map,
int cpu, u16 index)
{
struct xps_map *new_map;
int alloc_len = XPS_MIN_MAP_ALLOC;
int i, pos;
for (pos = 0; map && pos < map->len; pos++) {
if (map->queues[pos] != index)
continue;
return map;
}
/* Need to add queue to this CPU's existing map */
if (map) {
if (pos < map->alloc_len)
return map;
alloc_len = map->alloc_len * 2;
}
/* Need to allocate new map to store queue on this CPU's map */
new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
cpu_to_node(cpu));
if (!new_map)
return NULL;
for (i = 0; i < pos; i++)
new_map->queues[i] = map->queues[i];
new_map->alloc_len = alloc_len;
new_map->len = pos;
return new_map;
}
int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
u16 index)
{
struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
int i, cpu, tci, numa_node_id = -2;
int maps_sz, num_tc = 1, tc = 0;
struct xps_map *map, *new_map;
bool active = false;
if (dev->num_tc) {
num_tc = dev->num_tc;
tc = netdev_txq_to_tc(dev, index);
if (tc < 0)
return -EINVAL;
}
maps_sz = XPS_DEV_MAPS_SIZE(num_tc);
if (maps_sz < L1_CACHE_BYTES)
maps_sz = L1_CACHE_BYTES;
mutex_lock(&xps_map_mutex);
dev_maps = xmap_dereference(dev->xps_maps);
/* allocate memory for queue storage */
for_each_cpu_and(cpu, cpu_online_mask, mask) {
if (!new_dev_maps)
new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
if (!new_dev_maps) {
mutex_unlock(&xps_map_mutex);
return -ENOMEM;
}
tci = cpu * num_tc + tc;
map = dev_maps ? xmap_dereference(dev_maps->cpu_map[tci]) :
NULL;
map = expand_xps_map(map, cpu, index);
if (!map)
goto error;
RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map);
}
if (!new_dev_maps)
goto out_no_new_maps;
for_each_possible_cpu(cpu) {
/* copy maps belonging to foreign traffic classes */
for (i = tc, tci = cpu * num_tc; dev_maps && i--; tci++) {
/* fill in the new device map from the old device map */
map = xmap_dereference(dev_maps->cpu_map[tci]);
RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map);
}
/* We need to explicitly update tci as prevous loop
* could break out early if dev_maps is NULL.
*/
tci = cpu * num_tc + tc;
if (cpumask_test_cpu(cpu, mask) && cpu_online(cpu)) {
/* add queue to CPU maps */
int pos = 0;
map = xmap_dereference(new_dev_maps->cpu_map[tci]);
while ((pos < map->len) && (map->queues[pos] != index))
pos++;
if (pos == map->len)
map->queues[map->len++] = index;
#ifdef CONFIG_NUMA
if (numa_node_id == -2)
numa_node_id = cpu_to_node(cpu);
else if (numa_node_id != cpu_to_node(cpu))
numa_node_id = -1;
#endif
} else if (dev_maps) {
/* fill in the new device map from the old device map */
map = xmap_dereference(dev_maps->cpu_map[tci]);
RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map);
}
/* copy maps belonging to foreign traffic classes */
for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
/* fill in the new device map from the old device map */
map = xmap_dereference(dev_maps->cpu_map[tci]);
RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map);
}
}
rcu_assign_pointer(dev->xps_maps, new_dev_maps);
/* Cleanup old maps */
if (!dev_maps)
goto out_no_old_maps;
for_each_possible_cpu(cpu) {
for (i = num_tc, tci = cpu * num_tc; i--; tci++) {
new_map = xmap_dereference(new_dev_maps->cpu_map[tci]);
map = xmap_dereference(dev_maps->cpu_map[tci]);
if (map && map != new_map)
kfree_rcu(map, rcu);
}
}
kfree_rcu(dev_maps, rcu);
out_no_old_maps:
dev_maps = new_dev_maps;
active = true;
out_no_new_maps:
/* update Tx queue numa node */
netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
(numa_node_id >= 0) ? numa_node_id :
NUMA_NO_NODE);
if (!dev_maps)
goto out_no_maps;
/* removes queue from unused CPUs */
for_each_possible_cpu(cpu) {
for (i = tc, tci = cpu * num_tc; i--; tci++)
active |= remove_xps_queue(dev_maps, tci, index);
if (!cpumask_test_cpu(cpu, mask) || !cpu_online(cpu))
active |= remove_xps_queue(dev_maps, tci, index);
for (i = num_tc - tc, tci++; --i; tci++)
active |= remove_xps_queue(dev_maps, tci, index);
}
/* free map if not active */
if (!active) {
RCU_INIT_POINTER(dev->xps_maps, NULL);
kfree_rcu(dev_maps, rcu);
}
out_no_maps:
mutex_unlock(&xps_map_mutex);
return 0;
error:
/* remove any maps that we added */
for_each_possible_cpu(cpu) {
for (i = num_tc, tci = cpu * num_tc; i--; tci++) {
new_map = xmap_dereference(new_dev_maps->cpu_map[tci]);
map = dev_maps ?
xmap_dereference(dev_maps->cpu_map[tci]) :
NULL;
if (new_map && new_map != map)
kfree(new_map);
}
}
mutex_unlock(&xps_map_mutex);
kfree(new_dev_maps);
return -ENOMEM;
}
EXPORT_SYMBOL(netif_set_xps_queue);
#endif
void netdev_reset_tc(struct net_device *dev)
{
#ifdef CONFIG_XPS
netif_reset_xps_queues_gt(dev, 0);
#endif
dev->num_tc = 0;
memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
}
EXPORT_SYMBOL(netdev_reset_tc);
int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
{
if (tc >= dev->num_tc)
return -EINVAL;
#ifdef CONFIG_XPS
netif_reset_xps_queues(dev, offset, count);
#endif
dev->tc_to_txq[tc].count = count;
dev->tc_to_txq[tc].offset = offset;
return 0;
}
EXPORT_SYMBOL(netdev_set_tc_queue);
int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
{
if (num_tc > TC_MAX_QUEUE)
return -EINVAL;
#ifdef CONFIG_XPS
netif_reset_xps_queues_gt(dev, 0);
#endif
dev->num_tc = num_tc;
return 0;
}
EXPORT_SYMBOL(netdev_set_num_tc);
/*
* Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
* greater then real_num_tx_queues stale skbs on the qdisc must be flushed.
*/
int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
{
int rc;
if (txq < 1 || txq > dev->num_tx_queues)
return -EINVAL;
if (dev->reg_state == NETREG_REGISTERED ||
dev->reg_state == NETREG_UNREGISTERING) {
ASSERT_RTNL();
rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
txq);
if (rc)
return rc;
if (dev->num_tc)
netif_setup_tc(dev, txq);
if (txq < dev->real_num_tx_queues) {
qdisc_reset_all_tx_gt(dev, txq);
#ifdef CONFIG_XPS
netif_reset_xps_queues_gt(dev, txq);
#endif
}
}
dev->real_num_tx_queues = txq;
return 0;
}
EXPORT_SYMBOL(netif_set_real_num_tx_queues);
#ifdef CONFIG_SYSFS
/**
* netif_set_real_num_rx_queues - set actual number of RX queues used
* @dev: Network device
* @rxq: Actual number of RX queues
*
* This must be called either with the rtnl_lock held or before
* registration of the net device. Returns 0 on success, or a
* negative error code. If called before registration, it always
* succeeds.
*/
int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
{
int rc;
if (rxq < 1 || rxq > dev->num_rx_queues)
return -EINVAL;
if (dev->reg_state == NETREG_REGISTERED) {
ASSERT_RTNL();
rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
rxq);
if (rc)
return rc;
}
dev->real_num_rx_queues = rxq;
return 0;
}
EXPORT_SYMBOL(netif_set_real_num_rx_queues);
#endif
/**
* netif_get_num_default_rss_queues - default number of RSS queues
*
* This routine should set an upper limit on the number of RSS queues
* used by default by multiqueue devices.
*/
int netif_get_num_default_rss_queues(void)
{
return is_kdump_kernel() ?
1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
}
EXPORT_SYMBOL(netif_get_num_default_rss_queues);
static void __netif_reschedule(struct Qdisc *q)
{
struct softnet_data *sd;
unsigned long flags;
local_irq_save(flags);
sd = this_cpu_ptr(&softnet_data);
q->next_sched = NULL;
*sd->output_queue_tailp = q;
sd->output_queue_tailp = &q->next_sched;
raise_softirq_irqoff(NET_TX_SOFTIRQ);
local_irq_restore(flags);
}
void __netif_schedule(struct Qdisc *q)
{
if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
__netif_reschedule(q);
}
EXPORT_SYMBOL(__netif_schedule);
struct dev_kfree_skb_cb {
enum skb_free_reason reason;
};
static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
{
return (struct dev_kfree_skb_cb *)skb->cb;
}
void netif_schedule_queue(struct netdev_queue *txq)
{
rcu_read_lock();
if (!(txq->state & QUEUE_STATE_ANY_XOFF)) {
struct Qdisc *q = rcu_dereference(txq->qdisc);
__netif_schedule(q);
}
rcu_read_unlock();
}
EXPORT_SYMBOL(netif_schedule_queue);
void netif_tx_wake_queue(struct netdev_queue *dev_queue)
{
if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
struct Qdisc *q;
rcu_read_lock();
q = rcu_dereference(dev_queue->qdisc);
__netif_schedule(q);
rcu_read_unlock();
}
}
EXPORT_SYMBOL(netif_tx_wake_queue);
void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
{
unsigned long flags;
if (unlikely(!skb))
return;
if (likely(refcount_read(&skb->users) == 1)) {
smp_rmb();
refcount_set(&skb->users, 0);
} else if (likely(!refcount_dec_and_test(&skb->users))) {
return;
}
get_kfree_skb_cb(skb)->reason = reason;
local_irq_save(flags);
skb->next = __this_cpu_read(softnet_data.completion_queue);
__this_cpu_write(softnet_data.completion_queue, skb);
raise_softirq_irqoff(NET_TX_SOFTIRQ);
local_irq_restore(flags);
}
EXPORT_SYMBOL(__dev_kfree_skb_irq);
void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
{
if (in_irq() || irqs_disabled())
__dev_kfree_skb_irq(skb, reason);
else
dev_kfree_skb(skb);
}
EXPORT_SYMBOL(__dev_kfree_skb_any);
/**
* netif_device_detach - mark device as removed
* @dev: network device
*
* Mark device as removed from system and therefore no longer available.
*/
void netif_device_detach(struct net_device *dev)
{
if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
netif_running(dev)) {
netif_tx_stop_all_queues(dev);
}
}
EXPORT_SYMBOL(netif_device_detach);
/**
* netif_device_attach - mark device as attached
* @dev: network device
*
* Mark device as attached from system and restart if needed.
*/
void netif_device_attach(struct net_device *dev)
{
if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
netif_running(dev)) {
netif_tx_wake_all_queues(dev);
__netdev_watchdog_up(dev);
}
}
EXPORT_SYMBOL(netif_device_attach);
/*
* Returns a Tx hash based on the given packet descriptor a Tx queues' number
* to be used as a distribution range.
*/
u16 __skb_tx_hash(const struct net_device *dev, struct sk_buff *skb,
unsigned int num_tx_queues)
{
u32 hash;
u16 qoffset = 0;
u16 qcount = num_tx_queues;
if (skb_rx_queue_recorded(skb)) {
hash = skb_get_rx_queue(skb);
while (unlikely(hash >= num_tx_queues))
hash -= num_tx_queues;
return hash;
}
if (dev->num_tc) {
u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
qoffset = dev->tc_to_txq[tc].offset;
qcount = dev->tc_to_txq[tc].count;
}
return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
}
EXPORT_SYMBOL(__skb_tx_hash);
static void skb_warn_bad_offload(const struct sk_buff *skb)
{
static const netdev_features_t null_features;
struct net_device *dev = skb->dev;
const char *name = "";
if (!net_ratelimit())
return;
if (dev) {
if (dev->dev.parent)
name = dev_driver_string(dev->dev.parent);
else
name = netdev_name(dev);
}
WARN(1, "%s: caps=(%pNF, %pNF) len=%d data_len=%d gso_size=%d "
"gso_type=%d ip_summed=%d\n",
name, dev ? &dev->features : &null_features,
skb->sk ? &skb->sk->sk_route_caps : &null_features,
skb->len, skb->data_len, skb_shinfo(skb)->gso_size,
skb_shinfo(skb)->gso_type, skb->ip_summed);
}
/*
* Invalidate hardware checksum when packet is to be mangled, and
* complete checksum manually on outgoing path.
*/
int skb_checksum_help(struct sk_buff *skb)
{
__wsum csum;
int ret = 0, offset;
if (skb->ip_summed == CHECKSUM_COMPLETE)
goto out_set_summed;
if (unlikely(skb_shinfo(skb)->gso_size)) {
skb_warn_bad_offload(skb);
return -EINVAL;
}
/* Before computing a checksum, we should make sure no frag could
* be modified by an external entity : checksum could be wrong.
*/
if (skb_has_shared_frag(skb)) {
ret = __skb_linearize(skb);
if (ret)
goto out;
}
offset = skb_checksum_start_offset(skb);
BUG_ON(offset >= skb_headlen(skb));
csum = skb_checksum(skb, offset, skb->len - offset, 0);
offset += skb->csum_offset;
BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
if (skb_cloned(skb) &&
!skb_clone_writable(skb, offset + sizeof(__sum16))) {
ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (ret)
goto out;
}
*(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
out_set_summed:
skb->ip_summed = CHECKSUM_NONE;
out:
return ret;
}
EXPORT_SYMBOL(skb_checksum_help);
int skb_crc32c_csum_help(struct sk_buff *skb)
{
__le32 crc32c_csum;
int ret = 0, offset, start;
if (skb->ip_summed != CHECKSUM_PARTIAL)
goto out;
if (unlikely(skb_is_gso(skb)))
goto out;
/* Before computing a checksum, we should make sure no frag could
* be modified by an external entity : checksum could be wrong.
*/
if (unlikely(skb_has_shared_frag(skb))) {
ret = __skb_linearize(skb);
if (ret)
goto out;
}
start = skb_checksum_start_offset(skb);
offset = start + offsetof(struct sctphdr, checksum);
if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
ret = -EINVAL;
goto out;
}
if (skb_cloned(skb) &&
!skb_clone_writable(skb, offset + sizeof(__le32))) {
ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (ret)
goto out;
}
crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
skb->len - start, ~(__u32)0,
crc32c_csum_stub));
*(__le32 *)(skb->data + offset) = crc32c_csum;
skb->ip_summed = CHECKSUM_NONE;
skb->csum_not_inet = 0;
out:
return ret;
}
__be16 skb_network_protocol(struct sk_buff *skb, int *depth)
{
__be16 type = skb->protocol;
/* Tunnel gso handlers can set protocol to ethernet. */
if (type == htons(ETH_P_TEB)) {
struct ethhdr *eth;
if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
return 0;
eth = (struct ethhdr *)skb_mac_header(skb);
type = eth->h_proto;
}
return __vlan_get_protocol(skb, type, depth);
}
/**
* skb_mac_gso_segment - mac layer segmentation handler.
* @skb: buffer to segment
* @features: features for the output path (see dev->features)
*/
struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
struct packet_offload *ptype;
int vlan_depth = skb->mac_len;
__be16 type = skb_network_protocol(skb, &vlan_depth);
if (unlikely(!type))
return ERR_PTR(-EINVAL);
__skb_pull(skb, vlan_depth);
rcu_read_lock();
list_for_each_entry_rcu(ptype, &offload_base, list) {
if (ptype->type == type && ptype->callbacks.gso_segment) {
segs = ptype->callbacks.gso_segment(skb, features);
break;
}
}
rcu_read_unlock();
__skb_push(skb, skb->data - skb_mac_header(skb));
return segs;
}
EXPORT_SYMBOL(skb_mac_gso_segment);
/* openvswitch calls this on rx path, so we need a different check.
*/
static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
{
if (tx_path)
return skb->ip_summed != CHECKSUM_PARTIAL;
return skb->ip_summed == CHECKSUM_NONE;
}
/**
* __skb_gso_segment - Perform segmentation on skb.
* @skb: buffer to segment
* @features: features for the output path (see dev->features)
* @tx_path: whether it is called in TX path
*
* This function segments the given skb and returns a list of segments.
*
* It may return NULL if the skb requires no segmentation. This is
* only possible when GSO is used for verifying header integrity.
*
* Segmentation preserves SKB_SGO_CB_OFFSET bytes of previous skb cb.
*/
struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
netdev_features_t features, bool tx_path)
{
struct sk_buff *segs;
if (unlikely(skb_needs_check(skb, tx_path))) {
int err;
/* We're going to init ->check field in TCP or UDP header */
err = skb_cow_head(skb, 0);
if (err < 0)
return ERR_PTR(err);
}
/* Only report GSO partial support if it will enable us to
* support segmentation on this frame without needing additional
* work.
*/
if (features & NETIF_F_GSO_PARTIAL) {
netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
struct net_device *dev = skb->dev;
partial_features |= dev->features & dev->gso_partial_features;
if (!skb_gso_ok(skb, features | partial_features))
features &= ~NETIF_F_GSO_PARTIAL;
}
BUILD_BUG_ON(SKB_SGO_CB_OFFSET +
sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
SKB_GSO_CB(skb)->encap_level = 0;
skb_reset_mac_header(skb);
skb_reset_mac_len(skb);
segs = skb_mac_gso_segment(skb, features);
if (unlikely(skb_needs_check(skb, tx_path)))
skb_warn_bad_offload(skb);
return segs;
}
EXPORT_SYMBOL(__skb_gso_segment);
/* Take action when hardware reception checksum errors are detected. */
#ifdef CONFIG_BUG
void netdev_rx_csum_fault(struct net_device *dev)
{
if (net_ratelimit()) {
pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
dump_stack();
}
}
EXPORT_SYMBOL(netdev_rx_csum_fault);
#endif
/* Actually, we should eliminate this check as soon as we know, that:
* 1. IOMMU is present and allows to map all the memory.
* 2. No high memory really exists on this machine.
*/
static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
{
#ifdef CONFIG_HIGHMEM
int i;
if (!(dev->features & NETIF_F_HIGHDMA)) {
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
if (PageHighMem(skb_frag_page(frag)))
return 1;
}
}
if (PCI_DMA_BUS_IS_PHYS) {
struct device *pdev = dev->dev.parent;
if (!pdev)
return 0;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
dma_addr_t addr = page_to_phys(skb_frag_page(frag));
if (!pdev->dma_mask || addr + PAGE_SIZE - 1 > *pdev->dma_mask)
return 1;
}
}
#endif
return 0;
}
/* If MPLS offload request, verify we are testing hardware MPLS features
* instead of standard features for the netdev.
*/
#if IS_ENABLED(CONFIG_NET_MPLS_GSO)
static netdev_features_t net_mpls_features(struct sk_buff *skb,
netdev_features_t features,
__be16 type)
{
if (eth_p_mpls(type))
features &= skb->dev->mpls_features;
return features;
}
#else
static netdev_features_t net_mpls_features(struct sk_buff *skb,
netdev_features_t features,
__be16 type)
{
return features;
}
#endif
static netdev_features_t harmonize_features(struct sk_buff *skb,
netdev_features_t features)
{
int tmp;
__be16 type;
type = skb_network_protocol(skb, &tmp);
features = net_mpls_features(skb, features, type);
if (skb->ip_summed != CHECKSUM_NONE &&
!can_checksum_protocol(features, type)) {
features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
}
if (illegal_highdma(skb->dev, skb))
features &= ~NETIF_F_SG;
return features;
}
netdev_features_t passthru_features_check(struct sk_buff *skb,
struct net_device *dev,
netdev_features_t features)
{
return features;
}
EXPORT_SYMBOL(passthru_features_check);
static netdev_features_t dflt_features_check(const struct sk_buff *skb,
struct net_device *dev,
netdev_features_t features)
{
return vlan_features_check(skb, features);
}
static netdev_features_t gso_features_check(const struct sk_buff *skb,
struct net_device *dev,
netdev_features_t features)
{
u16 gso_segs = skb_shinfo(skb)->gso_segs;
if (gso_segs > dev->gso_max_segs)
return features & ~NETIF_F_GSO_MASK;
/* Support for GSO partial features requires software
* intervention before we can actually process the packets
* so we need to strip support for any partial features now
* and we can pull them back in after we have partially
* segmented the frame.
*/
if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
features &= ~dev->gso_partial_features;
/* Make sure to clear the IPv4 ID mangling feature if the
* IPv4 header has the potential to be fragmented.
*/
if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
struct iphdr *iph = skb->encapsulation ?
inner_ip_hdr(skb) : ip_hdr(skb);
if (!(iph->frag_off & htons(IP_DF)))
features &= ~NETIF_F_TSO_MANGLEID;
}
return features;
}
netdev_features_t netif_skb_features(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
netdev_features_t features = dev->features;
if (skb_is_gso(skb))
features = gso_features_check(skb, dev, features);
/* If encapsulation offload request, verify we are testing
* hardware encapsulation features instead of standard
* features for the netdev
*/
if (skb->encapsulation)
features &= dev->hw_enc_features;
if (skb_vlan_tagged(skb))
features = netdev_intersect_features(features,
dev->vlan_features |
NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX);
if (dev->netdev_ops->ndo_features_check)
features &= dev->netdev_ops->ndo_features_check(skb, dev,
features);
else
features &= dflt_features_check(skb, dev, features);
return harmonize_features(skb, features);
}
EXPORT_SYMBOL(netif_skb_features);
static int xmit_one(struct sk_buff *skb, struct net_device *dev,
struct netdev_queue *txq, bool more)
{
unsigned int len;
int rc;
if (!list_empty(&ptype_all) || !list_empty(&dev->ptype_all))
dev_queue_xmit_nit(skb, dev);
len = skb->len;
trace_net_dev_start_xmit(skb, dev);
rc = netdev_start_xmit(skb, dev, txq, more);
trace_net_dev_xmit(skb, rc, dev, len);
return rc;
}
struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
struct netdev_queue *txq, int *ret)
{
struct sk_buff *skb = first;
int rc = NETDEV_TX_OK;
while (skb) {
struct sk_buff *next = skb->next;
skb->next = NULL;
rc = xmit_one(skb, dev, txq, next != NULL);
if (unlikely(!dev_xmit_complete(rc))) {
skb->next = next;
goto out;
}
skb = next;
if (netif_xmit_stopped(txq) && skb) {
rc = NETDEV_TX_BUSY;
break;
}
}
out:
*ret = rc;
return skb;
}
static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
netdev_features_t features)
{
if (skb_vlan_tag_present(skb) &&
!vlan_hw_offload_capable(features, skb->vlan_proto))
skb = __vlan_hwaccel_push_inside(skb);
return skb;
}
int skb_csum_hwoffload_help(struct sk_buff *skb,
const netdev_features_t features)
{
if (unlikely(skb->csum_not_inet))
return !!(features & NETIF_F_SCTP_CRC) ? 0 :
skb_crc32c_csum_help(skb);
return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
}
EXPORT_SYMBOL(skb_csum_hwoffload_help);
static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev)
{
netdev_features_t features;
features = netif_skb_features(skb);
skb = validate_xmit_vlan(skb, features);
if (unlikely(!skb))
goto out_null;
if (netif_needs_gso(skb, features)) {
struct sk_buff *segs;
segs = skb_gso_segment(skb, features);
if (IS_ERR(segs)) {
goto out_kfree_skb;
} else if (segs) {
consume_skb(skb);
skb = segs;
}
} else {
if (skb_needs_linearize(skb, features) &&
__skb_linearize(skb))
goto out_kfree_skb;
if (validate_xmit_xfrm(skb, features))
goto out_kfree_skb;
/* If packet is not checksummed and device does not
* support checksumming for this protocol, complete
* checksumming here.
*/
if (skb->ip_summed == CHECKSUM_PARTIAL) {
if (skb->encapsulation)
skb_set_inner_transport_header(skb,
skb_checksum_start_offset(skb));
else
skb_set_transport_header(skb,
skb_checksum_start_offset(skb));
if (skb_csum_hwoffload_help(skb, features))
goto out_kfree_skb;
}
}
return skb;
out_kfree_skb:
kfree_skb(skb);
out_null:
atomic_long_inc(&dev->tx_dropped);
return NULL;
}
struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev)
{
struct sk_buff *next, *head = NULL, *tail;
for (; skb != NULL; skb = next) {
next = skb->next;
skb->next = NULL;
/* in case skb wont be segmented, point to itself */
skb->prev = skb;
skb = validate_xmit_skb(skb, dev);
if (!skb)
continue;
if (!head)
head = skb;
else
tail->next = skb;
/* If skb was segmented, skb->prev points to
* the last segment. If not, it still contains skb.
*/
tail = skb->prev;
}
return head;
}
EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
static void qdisc_pkt_len_init(struct sk_buff *skb)
{
const struct skb_shared_info *shinfo = skb_shinfo(skb);
qdisc_skb_cb(skb)->pkt_len = skb->len;
/* To get more precise estimation of bytes sent on wire,
* we add to pkt_len the headers size of all segments
*/
if (shinfo->gso_size) {
unsigned int hdr_len;
u16 gso_segs = shinfo->gso_segs;
/* mac layer + network layer */
hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
/* + transport layer */
if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
hdr_len += tcp_hdrlen(skb);
else
hdr_len += sizeof(struct udphdr);
if (shinfo->gso_type & SKB_GSO_DODGY)
gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
shinfo->gso_size);
qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
}
}
static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
struct net_device *dev,
struct netdev_queue *txq)
{
spinlock_t *root_lock = qdisc_lock(q);
struct sk_buff *to_free = NULL;
bool contended;
int rc;
qdisc_calculate_pkt_len(skb, q);
/*
* Heuristic to force contended enqueues to serialize on a
* separate lock before trying to get qdisc main lock.
* This permits qdisc->running owner to get the lock more
* often and dequeue packets faster.
*/
contended = qdisc_is_running(q);
if (unlikely(contended))
spin_lock(&q->busylock);
spin_lock(root_lock);
if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
__qdisc_drop(skb, &to_free);
rc = NET_XMIT_DROP;
} else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
qdisc_run_begin(q)) {
/*
* This is a work-conserving queue; there are no old skbs
* waiting to be sent out; and the qdisc is not running -
* xmit the skb directly.
*/
qdisc_bstats_update(q, skb);
if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
if (unlikely(contended)) {
spin_unlock(&q->busylock);
contended = false;
}
__qdisc_run(q);
} else
qdisc_run_end(q);
rc = NET_XMIT_SUCCESS;
} else {
rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
if (qdisc_run_begin(q)) {
if (unlikely(contended)) {
spin_unlock(&q->busylock);
contended = false;
}
__qdisc_run(q);
}
}
spin_unlock(root_lock);
if (unlikely(to_free))
kfree_skb_list(to_free);
if (unlikely(contended))
spin_unlock(&q->busylock);
return rc;
}
#if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
static void skb_update_prio(struct sk_buff *skb)
{
struct netprio_map *map = rcu_dereference_bh(skb->dev->priomap);
if (!skb->priority && skb->sk && map) {
unsigned int prioidx =
sock_cgroup_prioidx(&skb->sk->sk_cgrp_data);
if (prioidx < map->priomap_len)
skb->priority = map->priomap[prioidx];
}
}
#else
#define skb_update_prio(skb)
#endif
DEFINE_PER_CPU(int, xmit_recursion);
EXPORT_SYMBOL(xmit_recursion);
/**
* dev_loopback_xmit - loop back @skb
* @net: network namespace this loopback is happening in
* @sk: sk needed to be a netfilter okfn
* @skb: buffer to transmit
*/
int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
{
skb_reset_mac_header(skb);
__skb_pull(skb, skb_network_offset(skb));
skb->pkt_type = PACKET_LOOPBACK;
skb->ip_summed = CHECKSUM_UNNECESSARY;
WARN_ON(!skb_dst(skb));
skb_dst_force(skb);
netif_rx_ni(skb);
return 0;
}
EXPORT_SYMBOL(dev_loopback_xmit);
#ifdef CONFIG_NET_EGRESS
static struct sk_buff *
sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
{
struct tcf_proto *cl = rcu_dereference_bh(dev->egress_cl_list);
struct tcf_result cl_res;
if (!cl)
return skb;
/* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
qdisc_bstats_cpu_update(cl->q, skb);
switch (tcf_classify(skb, cl, &cl_res, false)) {
case TC_ACT_OK:
case TC_ACT_RECLASSIFY:
skb->tc_index = TC_H_MIN(cl_res.classid);
break;
case TC_ACT_SHOT:
qdisc_qstats_cpu_drop(cl->q);
*ret = NET_XMIT_DROP;
kfree_skb(skb);
return NULL;
case TC_ACT_STOLEN:
case TC_ACT_QUEUED:
case TC_ACT_TRAP:
*ret = NET_XMIT_SUCCESS;
consume_skb(skb);
return NULL;
case TC_ACT_REDIRECT:
/* No need to push/pop skb's mac_header here on egress! */
skb_do_redirect(skb);
*ret = NET_XMIT_SUCCESS;
return NULL;
default:
break;
}
return skb;
}
#endif /* CONFIG_NET_EGRESS */
static inline int get_xps_queue(struct net_device *dev, struct sk_buff *skb)
{
#ifdef CONFIG_XPS
struct xps_dev_maps *dev_maps;
struct xps_map *map;
int queue_index = -1;
rcu_read_lock();
dev_maps = rcu_dereference(dev->xps_maps);
if (dev_maps) {
unsigned int tci = skb->sender_cpu - 1;
if (dev->num_tc) {
tci *= dev->num_tc;
tci += netdev_get_prio_tc_map(dev, skb->priority);
}
map = rcu_dereference(dev_maps->cpu_map[tci]);
if (map) {
if (map->len == 1)
queue_index = map->queues[0];
else
queue_index = map->queues[reciprocal_scale(skb_get_hash(skb),
map->len)];
if (unlikely(queue_index >= dev->real_num_tx_queues))
queue_index = -1;
}
}
rcu_read_unlock();
return queue_index;
#else
return -1;
#endif
}
static u16 __netdev_pick_tx(struct net_device *dev, struct sk_buff *skb)
{
struct sock *sk = skb->sk;
int queue_index = sk_tx_queue_get(sk);
if (queue_index < 0 || skb->ooo_okay ||
queue_index >= dev->real_num_tx_queues) {
int new_index = get_xps_queue(dev, skb);
if (new_index < 0)
new_index = skb_tx_hash(dev, skb);
if (queue_index != new_index && sk &&
sk_fullsock(sk) &&
rcu_access_pointer(sk->sk_dst_cache))
sk_tx_queue_set(sk, new_index);
queue_index = new_index;
}
return queue_index;
}
struct netdev_queue *netdev_pick_tx(struct net_device *dev,
struct sk_buff *skb,
void *accel_priv)
{
int queue_index = 0;
#ifdef CONFIG_XPS
u32 sender_cpu = skb->sender_cpu - 1;
if (sender_cpu >= (u32)NR_CPUS)
skb->sender_cpu = raw_smp_processor_id() + 1;
#endif
if (dev->real_num_tx_queues != 1) {
const struct net_device_ops *ops = dev->netdev_ops;
if (ops->ndo_select_queue)
queue_index = ops->ndo_select_queue(dev, skb, accel_priv,
__netdev_pick_tx);
else
queue_index = __netdev_pick_tx(dev, skb);
if (!accel_priv)
queue_index = netdev_cap_txqueue(dev, queue_index);
}
skb_set_queue_mapping(skb, queue_index);
return netdev_get_tx_queue(dev, queue_index);
}
/**
* __dev_queue_xmit - transmit a buffer
* @skb: buffer to transmit
* @accel_priv: private data used for L2 forwarding offload
*
* Queue a buffer for transmission to a network device. The caller must
* have set the device and priority and built the buffer before calling
* this function. The function can be called from an interrupt.
*
* A negative errno code is returned on a failure. A success does not
* guarantee the frame will be transmitted as it may be dropped due
* to congestion or traffic shaping.
*
* -----------------------------------------------------------------------------------
* I notice this method can also return errors from the queue disciplines,
* including NET_XMIT_DROP, which is a positive value. So, errors can also
* be positive.
*
* Regardless of the return value, the skb is consumed, so it is currently
* difficult to retry a send to this method. (You can bump the ref count
* before sending to hold a reference for retry if you are careful.)
*
* When calling this method, interrupts MUST be enabled. This is because
* the BH enable code must have IRQs enabled so that it will not deadlock.
* --BLG
*/
static int __dev_queue_xmit(struct sk_buff *skb, void *accel_priv)
{
struct net_device *dev = skb->dev;
struct netdev_queue *txq;
struct Qdisc *q;
int rc = -ENOMEM;
skb_reset_mac_header(skb);
if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
__skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
/* Disable soft irqs for various locks below. Also
* stops preemption for RCU.
*/
rcu_read_lock_bh();
skb_update_prio(skb);
qdisc_pkt_len_init(skb);
#ifdef CONFIG_NET_CLS_ACT
skb->tc_at_ingress = 0;
# ifdef CONFIG_NET_EGRESS
if (static_key_false(&egress_needed)) {
skb = sch_handle_egress(skb, &rc, dev);
if (!skb)
goto out;
}
# endif
#endif
/* If device/qdisc don't need skb->dst, release it right now while
* its hot in this cpu cache.
*/
if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
skb_dst_drop(skb);
else
skb_dst_force(skb);
txq = netdev_pick_tx(dev, skb, accel_priv);
q = rcu_dereference_bh(txq->qdisc);
trace_net_dev_queue(skb);
if (q->enqueue) {
rc = __dev_xmit_skb(skb, q, dev, txq);
goto out;
}
/* The device has no queue. Common case for software devices:
* loopback, all the sorts of tunnels...
* Really, it is unlikely that netif_tx_lock protection is necessary
* here. (f.e. loopback and IP tunnels are clean ignoring statistics
* counters.)
* However, it is possible, that they rely on protection
* made by us here.
* Check this and shot the lock. It is not prone from deadlocks.
*Either shot noqueue qdisc, it is even simpler 8)
*/
if (dev->flags & IFF_UP) {
int cpu = smp_processor_id(); /* ok because BHs are off */
if (txq->xmit_lock_owner != cpu) {
if (unlikely(__this_cpu_read(xmit_recursion) >
XMIT_RECURSION_LIMIT))
goto recursion_alert;
skb = validate_xmit_skb(skb, dev);
if (!skb)
goto out;
HARD_TX_LOCK(dev, txq, cpu);
if (!netif_xmit_stopped(txq)) {
__this_cpu_inc(xmit_recursion);
skb = dev_hard_start_xmit(skb, dev, txq, &rc);
__this_cpu_dec(xmit_recursion);
if (dev_xmit_complete(rc)) {
HARD_TX_UNLOCK(dev, txq);
goto out;
}
}
HARD_TX_UNLOCK(dev, txq);
net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
dev->name);
} else {
/* Recursion is detected! It is possible,
* unfortunately
*/
recursion_alert:
net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
dev->name);
}
}
rc = -ENETDOWN;
rcu_read_unlock_bh();
atomic_long_inc(&dev->tx_dropped);
kfree_skb_list(skb);
return rc;
out:
rcu_read_unlock_bh();
return rc;
}
int dev_queue_xmit(struct sk_buff *skb)
{
return __dev_queue_xmit(skb, NULL);
}
EXPORT_SYMBOL(dev_queue_xmit);
int dev_queue_xmit_accel(struct sk_buff *skb, void *accel_priv)
{
return __dev_queue_xmit(skb, accel_priv);
}
EXPORT_SYMBOL(dev_queue_xmit_accel);
/*************************************************************************
* Receiver routines
*************************************************************************/
int netdev_max_backlog __read_mostly = 1000;
EXPORT_SYMBOL(netdev_max_backlog);
int netdev_tstamp_prequeue __read_mostly = 1;
int netdev_budget __read_mostly = 300;
unsigned int __read_mostly netdev_budget_usecs = 2000;
int weight_p __read_mostly = 64; /* old backlog weight */
int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
int dev_rx_weight __read_mostly = 64;
int dev_tx_weight __read_mostly = 64;
/* Called with irq disabled */
static inline void ____napi_schedule(struct softnet_data *sd,
struct napi_struct *napi)
{
list_add_tail(&napi->poll_list, &sd->poll_list);
__raise_softirq_irqoff(NET_RX_SOFTIRQ);
}
#ifdef CONFIG_RPS
/* One global table that all flow-based protocols share. */
struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
EXPORT_SYMBOL(rps_sock_flow_table);
u32 rps_cpu_mask __read_mostly;
EXPORT_SYMBOL(rps_cpu_mask);
struct static_key rps_needed __read_mostly;
EXPORT_SYMBOL(rps_needed);
struct static_key rfs_needed __read_mostly;
EXPORT_SYMBOL(rfs_needed);
static struct rps_dev_flow *
set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
struct rps_dev_flow *rflow, u16 next_cpu)
{
if (next_cpu < nr_cpu_ids) {
#ifdef CONFIG_RFS_ACCEL
struct netdev_rx_queue *rxqueue;
struct rps_dev_flow_table *flow_table;
struct rps_dev_flow *old_rflow;
u32 flow_id;
u16 rxq_index;
int rc;
/* Should we steer this flow to a different hardware queue? */
if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
!(dev->features & NETIF_F_NTUPLE))
goto out;
rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
if (rxq_index == skb_get_rx_queue(skb))
goto out;
rxqueue = dev->_rx + rxq_index;
flow_table = rcu_dereference(rxqueue->rps_flow_table);
if (!flow_table)
goto out;
flow_id = skb_get_hash(skb) & flow_table->mask;
rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
rxq_index, flow_id);
if (rc < 0)
goto out;
old_rflow = rflow;
rflow = &flow_table->flows[flow_id];
rflow->filter = rc;
if (old_rflow->filter == rflow->filter)
old_rflow->filter = RPS_NO_FILTER;
out:
#endif
rflow->last_qtail =
per_cpu(softnet_data, next_cpu).input_queue_head;
}
rflow->cpu = next_cpu;
return rflow;
}
/*
* get_rps_cpu is called from netif_receive_skb and returns the target
* CPU from the RPS map of the receiving queue for a given skb.
* rcu_read_lock must be held on entry.
*/
static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
struct rps_dev_flow **rflowp)
{
const struct rps_sock_flow_table *sock_flow_table;
struct netdev_rx_queue *rxqueue = dev->_rx;
struct rps_dev_flow_table *flow_table;
struct rps_map *map;
int cpu = -1;
u32 tcpu;
u32 hash;
if (skb_rx_queue_recorded(skb)) {
u16 index = skb_get_rx_queue(skb);
if (unlikely(index >= dev->real_num_rx_queues)) {
WARN_ONCE(dev->real_num_rx_queues > 1,
"%s received packet on queue %u, but number "
"of RX queues is %u\n",
dev->name, index, dev->real_num_rx_queues);
goto done;
}
rxqueue += index;
}
/* Avoid computing hash if RFS/RPS is not active for this rxqueue */
flow_table = rcu_dereference(rxqueue->rps_flow_table);
map = rcu_dereference(rxqueue->rps_map);
if (!flow_table && !map)
goto done;
skb_reset_network_header(skb);
hash = skb_get_hash(skb);
if (!hash)
goto done;
sock_flow_table = rcu_dereference(rps_sock_flow_table);
if (flow_table && sock_flow_table) {
struct rps_dev_flow *rflow;
u32 next_cpu;
u32 ident;
/* First check into global flow table if there is a match */
ident = sock_flow_table->ents[hash & sock_flow_table->mask];
if ((ident ^ hash) & ~rps_cpu_mask)
goto try_rps;
next_cpu = ident & rps_cpu_mask;
/* OK, now we know there is a match,
* we can look at the local (per receive queue) flow table
*/
rflow = &flow_table->flows[hash & flow_table->mask];
tcpu = rflow->cpu;
/*
* If the desired CPU (where last recvmsg was done) is
* different from current CPU (one in the rx-queue flow
* table entry), switch if one of the following holds:
* - Current CPU is unset (>= nr_cpu_ids).
* - Current CPU is offline.
* - The current CPU's queue tail has advanced beyond the
* last packet that was enqueued using this table entry.
* This guarantees that all previous packets for the flow
* have been dequeued, thus preserving in order delivery.
*/
if (unlikely(tcpu != next_cpu) &&
(tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
((int)(per_cpu(softnet_data, tcpu).input_queue_head -
rflow->last_qtail)) >= 0)) {
tcpu = next_cpu;
rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
}
if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
*rflowp = rflow;
cpu = tcpu;
goto done;
}
}
try_rps:
if (map) {
tcpu = map->cpus[reciprocal_scale(hash, map->len)];
if (cpu_online(tcpu)) {
cpu = tcpu;
goto done;
}
}
done:
return cpu;
}
#ifdef CONFIG_RFS_ACCEL
/**
* rps_may_expire_flow - check whether an RFS hardware filter may be removed
* @dev: Device on which the filter was set
* @rxq_index: RX queue index
* @flow_id: Flow ID passed to ndo_rx_flow_steer()
* @filter_id: Filter ID returned by ndo_rx_flow_steer()
*
* Drivers that implement ndo_rx_flow_steer() should periodically call
* this function for each installed filter and remove the filters for
* which it returns %true.
*/
bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
u32 flow_id, u16 filter_id)
{
struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
struct rps_dev_flow_table *flow_table;
struct rps_dev_flow *rflow;
bool expire = true;
unsigned int cpu;
rcu_read_lock();
flow_table = rcu_dereference(rxqueue->rps_flow_table);
if (flow_table && flow_id <= flow_table->mask) {
rflow = &flow_table->flows[flow_id];
cpu = ACCESS_ONCE(rflow->cpu);
if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
((int)(per_cpu(softnet_data, cpu).input_queue_head -
rflow->last_qtail) <
(int)(10 * flow_table->mask)))
expire = false;
}
rcu_read_unlock();
return expire;
}
EXPORT_SYMBOL(rps_may_expire_flow);
#endif /* CONFIG_RFS_ACCEL */
/* Called from hardirq (IPI) context */
static void rps_trigger_softirq(void *data)
{
struct softnet_data *sd = data;
____napi_schedule(sd, &sd->backlog);
sd->received_rps++;
}
#endif /* CONFIG_RPS */
/*
* Check if this softnet_data structure is another cpu one
* If yes, queue it to our IPI list and return 1
* If no, return 0
*/
static int rps_ipi_queued(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
if (sd != mysd) {
sd->rps_ipi_next = mysd->rps_ipi_list;
mysd->rps_ipi_list = sd;
__raise_softirq_irqoff(NET_RX_SOFTIRQ);
return 1;
}
#endif /* CONFIG_RPS */
return 0;
}
#ifdef CONFIG_NET_FLOW_LIMIT
int netdev_flow_limit_table_len __read_mostly = (1 << 12);
#endif
static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
{
#ifdef CONFIG_NET_FLOW_LIMIT
struct sd_flow_limit *fl;
struct softnet_data *sd;
unsigned int old_flow, new_flow;
if (qlen < (netdev_max_backlog >> 1))
return false;
sd = this_cpu_ptr(&softnet_data);
rcu_read_lock();
fl = rcu_dereference(sd->flow_limit);
if (fl) {
new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
old_flow = fl->history[fl->history_head];
fl->history[fl->history_head] = new_flow;
fl->history_head++;
fl->history_head &= FLOW_LIMIT_HISTORY - 1;
if (likely(fl->buckets[old_flow]))
fl->buckets[old_flow]--;
if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
fl->count++;
rcu_read_unlock();
return true;
}
}
rcu_read_unlock();
#endif
return false;
}
/*
* enqueue_to_backlog is called to queue an skb to a per CPU backlog
* queue (may be a remote CPU queue).
*/
static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
unsigned int *qtail)
{
struct softnet_data *sd;
unsigned long flags;
unsigned int qlen;
sd = &per_cpu(softnet_data, cpu);
local_irq_save(flags);
rps_lock(sd);
if (!netif_running(skb->dev))
goto drop;
qlen = skb_queue_len(&sd->input_pkt_queue);
if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
if (qlen) {
enqueue:
__skb_queue_tail(&sd->input_pkt_queue, skb);
input_queue_tail_incr_save(sd, qtail);
rps_unlock(sd);
local_irq_restore(flags);
return NET_RX_SUCCESS;
}
/* Schedule NAPI for backlog device
* We can use non atomic operation since we own the queue lock
*/
if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
if (!rps_ipi_queued(sd))
____napi_schedule(sd, &sd->backlog);
}
goto enqueue;
}
drop:
sd->dropped++;
rps_unlock(sd);
local_irq_restore(flags);
atomic_long_inc(&skb->dev->rx_dropped);
kfree_skb(skb);
return NET_RX_DROP;
}
static u32 netif_receive_generic_xdp(struct sk_buff *skb,
struct bpf_prog *xdp_prog)
{
struct xdp_buff xdp;
u32 act = XDP_DROP;
void *orig_data;
int hlen, off;
u32 mac_len;
/* Reinjected packets coming from act_mirred or similar should
* not get XDP generic processing.
*/
if (skb_cloned(skb))
return XDP_PASS;
if (skb_linearize(skb))
goto do_drop;
/* The XDP program wants to see the packet starting at the MAC
* header.
*/
mac_len = skb->data - skb_mac_header(skb);
hlen = skb_headlen(skb) + mac_len;
xdp.data = skb->data - mac_len;
xdp.data_end = xdp.data + hlen;
xdp.data_hard_start = skb->data - skb_headroom(skb);
orig_data = xdp.data;
act = bpf_prog_run_xdp(xdp_prog, &xdp);
off = xdp.data - orig_data;
if (off > 0)
__skb_pull(skb, off);
else if (off < 0)
__skb_push(skb, -off);
skb->mac_header += off;
switch (act) {
case XDP_REDIRECT:
case XDP_TX:
__skb_push(skb, mac_len);
/* fall through */
case XDP_PASS:
break;
default:
bpf_warn_invalid_xdp_action(act);
/* fall through */
case XDP_ABORTED:
trace_xdp_exception(skb->dev, xdp_prog, act);
/* fall through */
case XDP_DROP:
do_drop:
kfree_skb(skb);
break;
}
return act;
}
/* When doing generic XDP we have to bypass the qdisc layer and the
* network taps in order to match in-driver-XDP behavior.
*/
void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
{
struct net_device *dev = skb->dev;
struct netdev_queue *txq;
bool free_skb = true;
int cpu, rc;
txq = netdev_pick_tx(dev, skb, NULL);
cpu = smp_processor_id();
HARD_TX_LOCK(dev, txq, cpu);
if (!netif_xmit_stopped(txq)) {
rc = netdev_start_xmit(skb, dev, txq, 0);
if (dev_xmit_complete(rc))
free_skb = false;
}
HARD_TX_UNLOCK(dev, txq);
if (free_skb) {
trace_xdp_exception(dev, xdp_prog, XDP_TX);
kfree_skb(skb);
}
}
EXPORT_SYMBOL_GPL(generic_xdp_tx);
static struct static_key generic_xdp_needed __read_mostly;
int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
{
if (xdp_prog) {
u32 act = netif_receive_generic_xdp(skb, xdp_prog);
int err;
if (act != XDP_PASS) {
switch (act) {
case XDP_REDIRECT:
err = xdp_do_generic_redirect(skb->dev, skb,
xdp_prog);
if (err)
goto out_redir;
/* fallthru to submit skb */
case XDP_TX:
generic_xdp_tx(skb, xdp_prog);
break;
}
return XDP_DROP;
}
}
return XDP_PASS;
out_redir:
kfree_skb(skb);
return XDP_DROP;
}
EXPORT_SYMBOL_GPL(do_xdp_generic);
static int netif_rx_internal(struct sk_buff *skb)
{
int ret;
net_timestamp_check(netdev_tstamp_prequeue, skb);
trace_netif_rx(skb);
if (static_key_false(&generic_xdp_needed)) {
int ret;
preempt_disable();
rcu_read_lock();
ret = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
rcu_read_unlock();
preempt_enable();
/* Consider XDP consuming the packet a success from
* the netdev point of view we do not want to count
* this as an error.
*/
if (ret != XDP_PASS)
return NET_RX_SUCCESS;
}
#ifdef CONFIG_RPS
if (static_key_false(&rps_needed)) {
struct rps_dev_flow voidflow, *rflow = &voidflow;
int cpu;
preempt_disable();
rcu_read_lock();
cpu = get_rps_cpu(skb->dev, skb, &rflow);
if (cpu < 0)
cpu = smp_processor_id();
ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
rcu_read_unlock();
preempt_enable();
} else
#endif
{
unsigned int qtail;
ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
put_cpu();
}
return ret;
}
/**
* netif_rx - post buffer to the network code
* @skb: buffer to post
*
* This function receives a packet from a device driver and queues it for
* the upper (protocol) levels to process. It always succeeds. The buffer
* may be dropped during processing for congestion control or by the
* protocol layers.
*
* return values:
* NET_RX_SUCCESS (no congestion)
* NET_RX_DROP (packet was dropped)
*
*/
int netif_rx(struct sk_buff *skb)
{
trace_netif_rx_entry(skb);
return netif_rx_internal(skb);
}
EXPORT_SYMBOL(netif_rx);
int netif_rx_ni(struct sk_buff *skb)
{
int err;
trace_netif_rx_ni_entry(skb);
preempt_disable();
err = netif_rx_internal(skb);
if (local_softirq_pending())
do_softirq();
preempt_enable();
return err;
}
EXPORT_SYMBOL(netif_rx_ni);
static __latent_entropy void net_tx_action(struct softirq_action *h)
{
struct softnet_data *sd = this_cpu_ptr(&softnet_data);
if (sd->completion_queue) {
struct sk_buff *clist;
local_irq_disable();
clist = sd->completion_queue;
sd->completion_queue = NULL;
local_irq_enable();
while (clist) {
struct sk_buff *skb = clist;
clist = clist->next;
WARN_ON(refcount_read(&skb->users));
if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
trace_consume_skb(skb);
else
trace_kfree_skb(skb, net_tx_action);
if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
__kfree_skb(skb);
else
__kfree_skb_defer(skb);
}
__kfree_skb_flush();
}
if (sd->output_queue) {
struct Qdisc *head;
local_irq_disable();
head = sd->output_queue;
sd->output_queue = NULL;
sd->output_queue_tailp = &sd->output_queue;
local_irq_enable();
while (head) {
struct Qdisc *q = head;
spinlock_t *root_lock;
head = head->next_sched;
root_lock = qdisc_lock(q);
spin_lock(root_lock);
/* We need to make sure head->next_sched is read
* before clearing __QDISC_STATE_SCHED
*/
smp_mb__before_atomic();
clear_bit(__QDISC_STATE_SCHED, &q->state);
qdisc_run(q);
spin_unlock(root_lock);
}
}
}
#if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
/* This hook is defined here for ATM LANE */
int (*br_fdb_test_addr_hook)(struct net_device *dev,
unsigned char *addr) __read_mostly;
EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
#endif
static inline struct sk_buff *
sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
struct net_device *orig_dev)
{
#ifdef CONFIG_NET_CLS_ACT
struct tcf_proto *cl = rcu_dereference_bh(skb->dev->ingress_cl_list);
struct tcf_result cl_res;
/* If there's at least one ingress present somewhere (so
* we get here via enabled static key), remaining devices
* that are not configured with an ingress qdisc will bail
* out here.
*/
if (!cl)
return skb;
if (*pt_prev) {
*ret = deliver_skb(skb, *pt_prev, orig_dev);
*pt_prev = NULL;
}
qdisc_skb_cb(skb)->pkt_len = skb->len;
skb->tc_at_ingress = 1;
qdisc_bstats_cpu_update(cl->q, skb);
switch (tcf_classify(skb, cl, &cl_res, false)) {
case TC_ACT_OK:
case TC_ACT_RECLASSIFY:
skb->tc_index = TC_H_MIN(cl_res.classid);
break;
case TC_ACT_SHOT:
qdisc_qstats_cpu_drop(cl->q);
kfree_skb(skb);
return NULL;
case TC_ACT_STOLEN:
case TC_ACT_QUEUED:
case TC_ACT_TRAP:
consume_skb(skb);
return NULL;
case TC_ACT_REDIRECT:
/* skb_mac_header check was done by cls/act_bpf, so
* we can safely push the L2 header back before
* redirecting to another netdev
*/
__skb_push(skb, skb->mac_len);
skb_do_redirect(skb);
return NULL;
default:
break;
}
#endif /* CONFIG_NET_CLS_ACT */
return skb;
}
/**
* netdev_is_rx_handler_busy - check if receive handler is registered
* @dev: device to check
*
* Check if a receive handler is already registered for a given device.
* Return true if there one.
*
* The caller must hold the rtnl_mutex.
*/
bool netdev_is_rx_handler_busy(struct net_device *dev)
{
ASSERT_RTNL();
return dev && rtnl_dereference(dev->rx_handler);
}
EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
/**
* netdev_rx_handler_register - register receive handler
* @dev: device to register a handler for
* @rx_handler: receive handler to register
* @rx_handler_data: data pointer that is used by rx handler
*
* Register a receive handler for a device. This handler will then be
* called from __netif_receive_skb. A negative errno code is returned
* on a failure.
*
* The caller must hold the rtnl_mutex.
*
* For a general description of rx_handler, see enum rx_handler_result.
*/
int netdev_rx_handler_register(struct net_device *dev,
rx_handler_func_t *rx_handler,
void *rx_handler_data)
{
if (netdev_is_rx_handler_busy(dev))
return -EBUSY;
/* Note: rx_handler_data must be set before rx_handler */
rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
rcu_assign_pointer(dev->rx_handler, rx_handler);
return 0;
}
EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
/**
* netdev_rx_handler_unregister - unregister receive handler
* @dev: device to unregister a handler from
*
* Unregister a receive handler from a device.
*
* The caller must hold the rtnl_mutex.
*/
void netdev_rx_handler_unregister(struct net_device *dev)
{
ASSERT_RTNL();
RCU_INIT_POINTER(dev->rx_handler, NULL);
/* a reader seeing a non NULL rx_handler in a rcu_read_lock()
* section has a guarantee to see a non NULL rx_handler_data
* as well.
*/
synchronize_net();
RCU_INIT_POINTER(dev->rx_handler_data, NULL);
}
EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
/*
* Limit the use of PFMEMALLOC reserves to those protocols that implement
* the special handling of PFMEMALLOC skbs.
*/
static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
{
switch (skb->protocol) {
case htons(ETH_P_ARP):
case htons(ETH_P_IP):
case htons(ETH_P_IPV6):
case htons(ETH_P_8021Q):
case htons(ETH_P_8021AD):
return true;
default:
return false;
}
}
static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
int *ret, struct net_device *orig_dev)
{
#ifdef CONFIG_NETFILTER_INGRESS
if (nf_hook_ingress_active(skb)) {
int ingress_retval;
if (*pt_prev) {
*ret = deliver_skb(skb, *pt_prev, orig_dev);
*pt_prev = NULL;
}
rcu_read_lock();
ingress_retval = nf_hook_ingress(skb);
rcu_read_unlock();
return ingress_retval;
}
#endif /* CONFIG_NETFILTER_INGRESS */
return 0;
}
static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc)
{
struct packet_type *ptype, *pt_prev;
rx_handler_func_t *rx_handler;
struct net_device *orig_dev;
bool deliver_exact = false;
int ret = NET_RX_DROP;
__be16 type;
net_timestamp_check(!netdev_tstamp_prequeue, skb);
trace_netif_receive_skb(skb);
orig_dev = skb->dev;
skb_reset_network_header(skb);
if (!skb_transport_header_was_set(skb))
skb_reset_transport_header(skb);
skb_reset_mac_len(skb);
pt_prev = NULL;
another_round:
skb->skb_iif = skb->dev->ifindex;
__this_cpu_inc(softnet_data.processed);
if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
skb = skb_vlan_untag(skb);
if (unlikely(!skb))
goto out;
}
if (skb_skip_tc_classify(skb))
goto skip_classify;
if (pfmemalloc)
goto skip_taps;
list_for_each_entry_rcu(ptype, &ptype_all, list) {
if (pt_prev)
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = ptype;
}
list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
if (pt_prev)
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = ptype;
}
skip_taps:
#ifdef CONFIG_NET_INGRESS
if (static_key_false(&ingress_needed)) {
skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev);
if (!skb)
goto out;
if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
goto out;
}
#endif
skb_reset_tc(skb);
skip_classify:
if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
goto drop;
if (skb_vlan_tag_present(skb)) {
if (pt_prev) {
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = NULL;
}
if (vlan_do_receive(&skb))
goto another_round;
else if (unlikely(!skb))
goto out;
}
rx_handler = rcu_dereference(skb->dev->rx_handler);
if (rx_handler) {
if (pt_prev) {
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = NULL;
}
switch (rx_handler(&skb)) {
case RX_HANDLER_CONSUMED:
ret = NET_RX_SUCCESS;
goto out;
case RX_HANDLER_ANOTHER:
goto another_round;
case RX_HANDLER_EXACT:
deliver_exact = true;
case RX_HANDLER_PASS:
break;
default:
BUG();
}
}
if (unlikely(skb_vlan_tag_present(skb))) {
if (skb_vlan_tag_get_id(skb))
skb->pkt_type = PACKET_OTHERHOST;
/* Note: we might in the future use prio bits
* and set skb->priority like in vlan_do_receive()
* For the time being, just ignore Priority Code Point
*/
skb->vlan_tci = 0;
}
type = skb->protocol;
/* deliver only exact match when indicated */
if (likely(!deliver_exact)) {
deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
&ptype_base[ntohs(type) &
PTYPE_HASH_MASK]);
}
deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
&orig_dev->ptype_specific);
if (unlikely(skb->dev != orig_dev)) {
deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
&skb->dev->ptype_specific);
}
if (pt_prev) {
if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
goto drop;
else
ret = pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
} else {
drop:
if (!deliver_exact)
atomic_long_inc(&skb->dev->rx_dropped);
else
atomic_long_inc(&skb->dev->rx_nohandler);
kfree_skb(skb);
/* Jamal, now you will not able to escape explaining
* me how you were going to use this. :-)
*/
ret = NET_RX_DROP;
}
out:
return ret;
}
static int __netif_receive_skb(struct sk_buff *skb)
{
int ret;
if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
unsigned int noreclaim_flag;
/*
* PFMEMALLOC skbs are special, they should
* - be delivered to SOCK_MEMALLOC sockets only
* - stay away from userspace
* - have bounded memory usage
*
* Use PF_MEMALLOC as this saves us from propagating the allocation
* context down to all allocation sites.
*/
noreclaim_flag = memalloc_noreclaim_save();
ret = __netif_receive_skb_core(skb, true);
memalloc_noreclaim_restore(noreclaim_flag);
} else
ret = __netif_receive_skb_core(skb, false);
return ret;
}
static int generic_xdp_install(struct net_device *dev, struct netdev_xdp *xdp)
{
struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
struct bpf_prog *new = xdp->prog;
int ret = 0;
switch (xdp->command) {
case XDP_SETUP_PROG:
rcu_assign_pointer(dev->xdp_prog, new);
if (old)
bpf_prog_put(old);
if (old && !new) {
static_key_slow_dec(&generic_xdp_needed);
} else if (new && !old) {
static_key_slow_inc(&generic_xdp_needed);
dev_disable_lro(dev);
}
break;
case XDP_QUERY_PROG:
xdp->prog_attached = !!old;
xdp->prog_id = old ? old->aux->id : 0;
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int netif_receive_skb_internal(struct sk_buff *skb)
{
int ret;
net_timestamp_check(netdev_tstamp_prequeue, skb);
if (skb_defer_rx_timestamp(skb))
return NET_RX_SUCCESS;
if (static_key_false(&generic_xdp_needed)) {
int ret;
preempt_disable();
rcu_read_lock();
ret = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
rcu_read_unlock();
preempt_enable();
if (ret != XDP_PASS)
return NET_RX_DROP;
}
rcu_read_lock();
#ifdef CONFIG_RPS
if (static_key_false(&rps_needed)) {
struct rps_dev_flow voidflow, *rflow = &voidflow;
int cpu = get_rps_cpu(skb->dev, skb, &rflow);
if (cpu >= 0) {
ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
rcu_read_unlock();
return ret;
}
}
#endif
ret = __netif_receive_skb(skb);
rcu_read_unlock();
return ret;
}
/**
* netif_receive_skb - process receive buffer from network
* @skb: buffer to process
*
* netif_receive_skb() is the main receive data processing function.
* It always succeeds. The buffer may be dropped during processing
* for congestion control or by the protocol layers.
*
* This function may only be called from softirq context and interrupts
* should be enabled.
*
* Return values (usually ignored):
* NET_RX_SUCCESS: no congestion
* NET_RX_DROP: packet was dropped
*/
int netif_receive_skb(struct sk_buff *skb)
{
trace_netif_receive_skb_entry(skb);
return netif_receive_skb_internal(skb);
}
EXPORT_SYMBOL(netif_receive_skb);
DEFINE_PER_CPU(struct work_struct, flush_works);
/* Network device is going away, flush any packets still pending */
static void flush_backlog(struct work_struct *work)
{
struct sk_buff *skb, *tmp;
struct softnet_data *sd;
local_bh_disable();
sd = this_cpu_ptr(&softnet_data);
local_irq_disable();
rps_lock(sd);
skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
if (skb->dev->reg_state == NETREG_UNREGISTERING) {
__skb_unlink(skb, &sd->input_pkt_queue);
kfree_skb(skb);
input_queue_head_incr(sd);
}
}
rps_unlock(sd);
local_irq_enable();
skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
if (skb->dev->reg_state == NETREG_UNREGISTERING) {
__skb_unlink(skb, &sd->process_queue);
kfree_skb(skb);
input_queue_head_incr(sd);
}
}
local_bh_enable();
}
static void flush_all_backlogs(void)
{
unsigned int cpu;
get_online_cpus();
for_each_online_cpu(cpu)
queue_work_on(cpu, system_highpri_wq,
per_cpu_ptr(&flush_works, cpu));
for_each_online_cpu(cpu)
flush_work(per_cpu_ptr(&flush_works, cpu));
put_online_cpus();
}
static int napi_gro_complete(struct sk_buff *skb)
{
struct packet_offload *ptype;
__be16 type = skb->protocol;
struct list_head *head = &offload_base;
int err = -ENOENT;
BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
if (NAPI_GRO_CB(skb)->count == 1) {
skb_shinfo(skb)->gso_size = 0;
goto out;
}
rcu_read_lock();
list_for_each_entry_rcu(ptype, head, list) {
if (ptype->type != type || !ptype->callbacks.gro_complete)
continue;
err = ptype->callbacks.gro_complete(skb, 0);
break;
}
rcu_read_unlock();
if (err) {
WARN_ON(&ptype->list == head);
kfree_skb(skb);
return NET_RX_SUCCESS;
}
out:
return netif_receive_skb_internal(skb);
}
/* napi->gro_list contains packets ordered by age.
* youngest packets at the head of it.
* Complete skbs in reverse order to reduce latencies.
*/
void napi_gro_flush(struct napi_struct *napi, bool flush_old)
{
struct sk_buff *skb, *prev = NULL;
/* scan list and build reverse chain */
for (skb = napi->gro_list; skb != NULL; skb = skb->next) {
skb->prev = prev;
prev = skb;
}
for (skb = prev; skb; skb = prev) {
skb->next = NULL;
if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
return;
prev = skb->prev;
napi_gro_complete(skb);
napi->gro_count--;
}
napi->gro_list = NULL;
}
EXPORT_SYMBOL(napi_gro_flush);
static void gro_list_prepare(struct napi_struct *napi, struct sk_buff *skb)
{
struct sk_buff *p;
unsigned int maclen = skb->dev->hard_header_len;
u32 hash = skb_get_hash_raw(skb);
for (p = napi->gro_list; p; p = p->next) {
unsigned long diffs;
NAPI_GRO_CB(p)->flush = 0;
if (hash != skb_get_hash_raw(p)) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
diffs |= p->vlan_tci ^ skb->vlan_tci;
diffs |= skb_metadata_dst_cmp(p, skb);
if (maclen == ETH_HLEN)
diffs |= compare_ether_header(skb_mac_header(p),
skb_mac_header(skb));
else if (!diffs)
diffs = memcmp(skb_mac_header(p),
skb_mac_header(skb),
maclen);
NAPI_GRO_CB(p)->same_flow = !diffs;
}
}
static void skb_gro_reset_offset(struct sk_buff *skb)
{
const struct skb_shared_info *pinfo = skb_shinfo(skb);
const skb_frag_t *frag0 = &pinfo->frags[0];
NAPI_GRO_CB(skb)->data_offset = 0;
NAPI_GRO_CB(skb)->frag0 = NULL;
NAPI_GRO_CB(skb)->frag0_len = 0;
if (skb_mac_header(skb) == skb_tail_pointer(skb) &&
pinfo->nr_frags &&
!PageHighMem(skb_frag_page(frag0))) {
NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
skb_frag_size(frag0),
skb->end - skb->tail);
}
}
static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
{
struct skb_shared_info *pinfo = skb_shinfo(skb);
BUG_ON(skb->end - skb->tail < grow);
memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
skb->data_len -= grow;
skb->tail += grow;
pinfo->frags[0].page_offset += grow;
skb_frag_size_sub(&pinfo->frags[0], grow);
if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
skb_frag_unref(skb, 0);
memmove(pinfo->frags, pinfo->frags + 1,
--pinfo->nr_frags * sizeof(pinfo->frags[0]));
}
}
static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct packet_offload *ptype;
__be16 type = skb->protocol;
struct list_head *head = &offload_base;
int same_flow;
enum gro_result ret;
int grow;
if (netif_elide_gro(skb->dev))
goto normal;
gro_list_prepare(napi, skb);
rcu_read_lock();
list_for_each_entry_rcu(ptype, head, list) {
if (ptype->type != type || !ptype->callbacks.gro_receive)
continue;
skb_set_network_header(skb, skb_gro_offset(skb));
skb_reset_mac_len(skb);
NAPI_GRO_CB(skb)->same_flow = 0;
NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
NAPI_GRO_CB(skb)->free = 0;
NAPI_GRO_CB(skb)->encap_mark = 0;
NAPI_GRO_CB(skb)->recursion_counter = 0;
NAPI_GRO_CB(skb)->is_fou = 0;
NAPI_GRO_CB(skb)->is_atomic = 1;
NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
/* Setup for GRO checksum validation */
switch (skb->ip_summed) {
case CHECKSUM_COMPLETE:
NAPI_GRO_CB(skb)->csum = skb->csum;
NAPI_GRO_CB(skb)->csum_valid = 1;
NAPI_GRO_CB(skb)->csum_cnt = 0;
break;
case CHECKSUM_UNNECESSARY:
NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
NAPI_GRO_CB(skb)->csum_valid = 0;
break;
default:
NAPI_GRO_CB(skb)->csum_cnt = 0;
NAPI_GRO_CB(skb)->csum_valid = 0;
}
pp = ptype->callbacks.gro_receive(&napi->gro_list, skb);
break;
}
rcu_read_unlock();
if (&ptype->list == head)
goto normal;
if (IS_ERR(pp) && PTR_ERR(pp) == -EINPROGRESS) {
ret = GRO_CONSUMED;
goto ok;
}
same_flow = NAPI_GRO_CB(skb)->same_flow;
ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
if (pp) {
struct sk_buff *nskb = *pp;
*pp = nskb->next;
nskb->next = NULL;
napi_gro_complete(nskb);
napi->gro_count--;
}
if (same_flow)
goto ok;
if (NAPI_GRO_CB(skb)->flush)
goto normal;
if (unlikely(napi->gro_count >= MAX_GRO_SKBS)) {
struct sk_buff *nskb = napi->gro_list;
/* locate the end of the list to select the 'oldest' flow */
while (nskb->next) {
pp = &nskb->next;
nskb = *pp;
}
*pp = NULL;
nskb->next = NULL;
napi_gro_complete(nskb);
} else {
napi->gro_count++;
}
NAPI_GRO_CB(skb)->count = 1;
NAPI_GRO_CB(skb)->age = jiffies;
NAPI_GRO_CB(skb)->last = skb;
skb_shinfo(skb)->gso_size = skb_gro_len(skb);
skb->next = napi->gro_list;
napi->gro_list = skb;
ret = GRO_HELD;
pull:
grow = skb_gro_offset(skb) - skb_headlen(skb);
if (grow > 0)
gro_pull_from_frag0(skb, grow);
ok:
return ret;
normal:
ret = GRO_NORMAL;
goto pull;
}
struct packet_offload *gro_find_receive_by_type(__be16 type)
{
struct list_head *offload_head = &offload_base;
struct packet_offload *ptype;
list_for_each_entry_rcu(ptype, offload_head, list) {
if (ptype->type != type || !ptype->callbacks.gro_receive)
continue;
return ptype;
}
return NULL;
}
EXPORT_SYMBOL(gro_find_receive_by_type);
struct packet_offload *gro_find_complete_by_type(__be16 type)
{
struct list_head *offload_head = &offload_base;
struct packet_offload *ptype;
list_for_each_entry_rcu(ptype, offload_head, list) {
if (ptype->type != type || !ptype->callbacks.gro_complete)
continue;
return ptype;
}
return NULL;
}
EXPORT_SYMBOL(gro_find_complete_by_type);
static void napi_skb_free_stolen_head(struct sk_buff *skb)
{
skb_dst_drop(skb);
secpath_reset(skb);
kmem_cache_free(skbuff_head_cache, skb);
}
static gro_result_t napi_skb_finish(gro_result_t ret, struct sk_buff *skb)
{
switch (ret) {
case GRO_NORMAL:
if (netif_receive_skb_internal(skb))
ret = GRO_DROP;
break;
case GRO_DROP:
kfree_skb(skb);
break;
case GRO_MERGED_FREE:
if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
napi_skb_free_stolen_head(skb);
else
__kfree_skb(skb);
break;
case GRO_HELD:
case GRO_MERGED:
case GRO_CONSUMED:
break;
}
return ret;
}
gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
skb_mark_napi_id(skb, napi);
trace_napi_gro_receive_entry(skb);
skb_gro_reset_offset(skb);
return napi_skb_finish(dev_gro_receive(napi, skb), skb);
}
EXPORT_SYMBOL(napi_gro_receive);
static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
{
if (unlikely(skb->pfmemalloc)) {
consume_skb(skb);
return;
}
__skb_pull(skb, skb_headlen(skb));
/* restore the reserve we had after netdev_alloc_skb_ip_align() */
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
skb->vlan_tci = 0;
skb->dev = napi->dev;
skb->skb_iif = 0;
skb->encapsulation = 0;
skb_shinfo(skb)->gso_type = 0;
skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
secpath_reset(skb);
napi->skb = skb;
}
struct sk_buff *napi_get_frags(struct napi_struct *napi)
{
struct sk_buff *skb = napi->skb;
if (!skb) {
skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
if (skb) {
napi->skb = skb;
skb_mark_napi_id(skb, napi);
}
}
return skb;
}
EXPORT_SYMBOL(napi_get_frags);
static gro_result_t napi_frags_finish(struct napi_struct *napi,
struct sk_buff *skb,
gro_result_t ret)
{
switch (ret) {
case GRO_NORMAL:
case GRO_HELD:
__skb_push(skb, ETH_HLEN);
skb->protocol = eth_type_trans(skb, skb->dev);
if (ret == GRO_NORMAL && netif_receive_skb_internal(skb))
ret = GRO_DROP;
break;
case GRO_DROP:
napi_reuse_skb(napi, skb);
break;
case GRO_MERGED_FREE:
if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
napi_skb_free_stolen_head(skb);
else
napi_reuse_skb(napi, skb);
break;
case GRO_MERGED:
case GRO_CONSUMED:
break;
}
return ret;
}
/* Upper GRO stack assumes network header starts at gro_offset=0
* Drivers could call both napi_gro_frags() and napi_gro_receive()
* We copy ethernet header into skb->data to have a common layout.
*/
static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
{
struct sk_buff *skb = napi->skb;
const struct ethhdr *eth;
unsigned int hlen = sizeof(*eth);
napi->skb = NULL;
skb_reset_mac_header(skb);
skb_gro_reset_offset(skb);
eth = skb_gro_header_fast(skb, 0);
if (unlikely(skb_gro_header_hard(skb, hlen))) {
eth = skb_gro_header_slow(skb, hlen, 0);
if (unlikely(!eth)) {
net_warn_ratelimited("%s: dropping impossible skb from %s\n",
__func__, napi->dev->name);
napi_reuse_skb(napi, skb);
return NULL;
}
} else {
gro_pull_from_frag0(skb, hlen);
NAPI_GRO_CB(skb)->frag0 += hlen;
NAPI_GRO_CB(skb)->frag0_len -= hlen;
}
__skb_pull(skb, hlen);
/*
* This works because the only protocols we care about don't require
* special handling.
* We'll fix it up properly in napi_frags_finish()
*/
skb->protocol = eth->h_proto;
return skb;
}
gro_result_t napi_gro_frags(struct napi_struct *napi)
{
struct sk_buff *skb = napi_frags_skb(napi);
if (!skb)
return GRO_DROP;
trace_napi_gro_frags_entry(skb);
return napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
}
EXPORT_SYMBOL(napi_gro_frags);
/* Compute the checksum from gro_offset and return the folded value
* after adding in any pseudo checksum.
*/
__sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
{
__wsum wsum;
__sum16 sum;
wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
/* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
if (likely(!sum)) {
if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
!skb->csum_complete_sw)
netdev_rx_csum_fault(skb->dev);
}
NAPI_GRO_CB(skb)->csum = wsum;
NAPI_GRO_CB(skb)->csum_valid = 1;
return sum;
}
EXPORT_SYMBOL(__skb_gro_checksum_complete);
static void net_rps_send_ipi(struct softnet_data *remsd)
{
#ifdef CONFIG_RPS
while (remsd) {
struct softnet_data *next = remsd->rps_ipi_next;
if (cpu_online(remsd->cpu))
smp_call_function_single_async(remsd->cpu, &remsd->csd);
remsd = next;
}
#endif
}
/*
* net_rps_action_and_irq_enable sends any pending IPI's for rps.
* Note: called with local irq disabled, but exits with local irq enabled.
*/
static void net_rps_action_and_irq_enable(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
struct softnet_data *remsd = sd->rps_ipi_list;
if (remsd) {
sd->rps_ipi_list = NULL;
local_irq_enable();
/* Send pending IPI's to kick RPS processing on remote cpus. */
net_rps_send_ipi(remsd);
} else
#endif
local_irq_enable();
}
static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
return sd->rps_ipi_list != NULL;
#else
return false;
#endif
}
static int process_backlog(struct napi_struct *napi, int quota)
{
struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
bool again = true;
int work = 0;
/* Check if we have pending ipi, its better to send them now,
* not waiting net_rx_action() end.
*/
if (sd_has_rps_ipi_waiting(sd)) {
local_irq_disable();
net_rps_action_and_irq_enable(sd);
}
napi->weight = dev_rx_weight;
while (again) {
struct sk_buff *skb;
while ((skb = __skb_dequeue(&sd->process_queue))) {
rcu_read_lock();
__netif_receive_skb(skb);
rcu_read_unlock();
input_queue_head_incr(sd);
if (++work >= quota)
return work;
}
local_irq_disable();
rps_lock(sd);
if (skb_queue_empty(&sd->input_pkt_queue)) {
/*
* Inline a custom version of __napi_complete().
* only current cpu owns and manipulates this napi,
* and NAPI_STATE_SCHED is the only possible flag set
* on backlog.
* We can use a plain write instead of clear_bit(),
* and we dont need an smp_mb() memory barrier.
*/
napi->state = 0;
again = false;
} else {
skb_queue_splice_tail_init(&sd->input_pkt_queue,
&sd->process_queue);
}
rps_unlock(sd);
local_irq_enable();
}
return work;
}
/**
* __napi_schedule - schedule for receive
* @n: entry to schedule
*
* The entry's receive function will be scheduled to run.
* Consider using __napi_schedule_irqoff() if hard irqs are masked.
*/
void __napi_schedule(struct napi_struct *n)
{
unsigned long flags;
local_irq_save(flags);
____napi_schedule(this_cpu_ptr(&softnet_data), n);
local_irq_restore(flags);
}
EXPORT_SYMBOL(__napi_schedule);
/**
* napi_schedule_prep - check if napi can be scheduled
* @n: napi context
*
* Test if NAPI routine is already running, and if not mark
* it as running. This is used as a condition variable
* insure only one NAPI poll instance runs. We also make
* sure there is no pending NAPI disable.
*/
bool napi_schedule_prep(struct napi_struct *n)
{
unsigned long val, new;
do {
val = READ_ONCE(n->state);
if (unlikely(val & NAPIF_STATE_DISABLE))
return false;
new = val | NAPIF_STATE_SCHED;
/* Sets STATE_MISSED bit if STATE_SCHED was already set
* This was suggested by Alexander Duyck, as compiler
* emits better code than :
* if (val & NAPIF_STATE_SCHED)
* new |= NAPIF_STATE_MISSED;
*/
new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
NAPIF_STATE_MISSED;
} while (cmpxchg(&n->state, val, new) != val);
return !(val & NAPIF_STATE_SCHED);
}
EXPORT_SYMBOL(napi_schedule_prep);
/**
* __napi_schedule_irqoff - schedule for receive
* @n: entry to schedule
*
* Variant of __napi_schedule() assuming hard irqs are masked
*/
void __napi_schedule_irqoff(struct napi_struct *n)
{
____napi_schedule(this_cpu_ptr(&softnet_data), n);
}
EXPORT_SYMBOL(__napi_schedule_irqoff);
bool napi_complete_done(struct napi_struct *n, int work_done)
{
unsigned long flags, val, new;
/*
* 1) Don't let napi dequeue from the cpu poll list
* just in case its running on a different cpu.
* 2) If we are busy polling, do nothing here, we have
* the guarantee we will be called later.
*/
if (unlikely(n->state & (NAPIF_STATE_NPSVC |
NAPIF_STATE_IN_BUSY_POLL)))
return false;
if (n->gro_list) {
unsigned long timeout = 0;
if (work_done)
timeout = n->dev->gro_flush_timeout;
if (timeout)
hrtimer_start(&n->timer, ns_to_ktime(timeout),
HRTIMER_MODE_REL_PINNED);
else
napi_gro_flush(n, false);
}
if (unlikely(!list_empty(&n->poll_list))) {
/* If n->poll_list is not empty, we need to mask irqs */
local_irq_save(flags);
list_del_init(&n->poll_list);
local_irq_restore(flags);
}
do {
val = READ_ONCE(n->state);
WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
/* If STATE_MISSED was set, leave STATE_SCHED set,
* because we will call napi->poll() one more time.
* This C code was suggested by Alexander Duyck to help gcc.
*/
new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
NAPIF_STATE_SCHED;
} while (cmpxchg(&n->state, val, new) != val);
if (unlikely(val & NAPIF_STATE_MISSED)) {
__napi_schedule(n);
return false;
}
return true;
}
EXPORT_SYMBOL(napi_complete_done);
/* must be called under rcu_read_lock(), as we dont take a reference */
static struct napi_struct *napi_by_id(unsigned int napi_id)
{
unsigned int hash = napi_id % HASH_SIZE(napi_hash);
struct napi_struct *napi;
hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
if (napi->napi_id == napi_id)
return napi;
return NULL;
}
#if defined(CONFIG_NET_RX_BUSY_POLL)
#define BUSY_POLL_BUDGET 8
static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
{
int rc;
/* Busy polling means there is a high chance device driver hard irq
* could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
* set in napi_schedule_prep().
* Since we are about to call napi->poll() once more, we can safely
* clear NAPI_STATE_MISSED.
*
* Note: x86 could use a single "lock and ..." instruction
* to perform these two clear_bit()
*/
clear_bit(NAPI_STATE_MISSED, &napi->state);
clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
local_bh_disable();
/* All we really want here is to re-enable device interrupts.
* Ideally, a new ndo_busy_poll_stop() could avoid another round.
*/
rc = napi->poll(napi, BUSY_POLL_BUDGET);
trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
netpoll_poll_unlock(have_poll_lock);
if (rc == BUSY_POLL_BUDGET)
__napi_schedule(napi);
local_bh_enable();
}
void napi_busy_loop(unsigned int napi_id,
bool (*loop_end)(void *, unsigned long),
void *loop_end_arg)
{
unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
int (*napi_poll)(struct napi_struct *napi, int budget);
void *have_poll_lock = NULL;
struct napi_struct *napi;
restart:
napi_poll = NULL;
rcu_read_lock();
napi = napi_by_id(napi_id);
if (!napi)
goto out;
preempt_disable();
for (;;) {
int work = 0;
local_bh_disable();
if (!napi_poll) {
unsigned long val = READ_ONCE(napi->state);
/* If multiple threads are competing for this napi,
* we avoid dirtying napi->state as much as we can.
*/
if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
NAPIF_STATE_IN_BUSY_POLL))
goto count;
if (cmpxchg(&napi->state, val,
val | NAPIF_STATE_IN_BUSY_POLL |
NAPIF_STATE_SCHED) != val)
goto count;
have_poll_lock = netpoll_poll_lock(napi);
napi_poll = napi->poll;
}
work = napi_poll(napi, BUSY_POLL_BUDGET);
trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
count:
if (work > 0)
__NET_ADD_STATS(dev_net(napi->dev),
LINUX_MIB_BUSYPOLLRXPACKETS, work);
local_bh_enable();
if (!loop_end || loop_end(loop_end_arg, start_time))
break;
if (unlikely(need_resched())) {
if (napi_poll)
busy_poll_stop(napi, have_poll_lock);
preempt_enable();
rcu_read_unlock();
cond_resched();
if (loop_end(loop_end_arg, start_time))
return;
goto restart;
}
cpu_relax();
}
if (napi_poll)
busy_poll_stop(napi, have_poll_lock);
preempt_enable();
out:
rcu_read_unlock();
}
EXPORT_SYMBOL(napi_busy_loop);
#endif /* CONFIG_NET_RX_BUSY_POLL */
static void napi_hash_add(struct napi_struct *napi)
{
if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state) ||
test_and_set_bit(NAPI_STATE_HASHED, &napi->state))
return;
spin_lock(&napi_hash_lock);
/* 0..NR_CPUS range is reserved for sender_cpu use */
do {
if (unlikely(++napi_gen_id < MIN_NAPI_ID))
napi_gen_id = MIN_NAPI_ID;
} while (napi_by_id(napi_gen_id));
napi->napi_id = napi_gen_id;
hlist_add_head_rcu(&napi->napi_hash_node,
&napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
spin_unlock(&napi_hash_lock);
}
/* Warning : caller is responsible to make sure rcu grace period
* is respected before freeing memory containing @napi
*/
bool napi_hash_del(struct napi_struct *napi)
{
bool rcu_sync_needed = false;
spin_lock(&napi_hash_lock);
if (test_and_clear_bit(NAPI_STATE_HASHED, &napi->state)) {
rcu_sync_needed = true;
hlist_del_rcu(&napi->napi_hash_node);
}
spin_unlock(&napi_hash_lock);
return rcu_sync_needed;
}
EXPORT_SYMBOL_GPL(napi_hash_del);
static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
{
struct napi_struct *napi;
napi = container_of(timer, struct napi_struct, timer);
/* Note : we use a relaxed variant of napi_schedule_prep() not setting
* NAPI_STATE_MISSED, since we do not react to a device IRQ.
*/
if (napi->gro_list && !napi_disable_pending(napi) &&
!test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
__napi_schedule_irqoff(napi);
return HRTIMER_NORESTART;
}
void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
int (*poll)(struct napi_struct *, int), int weight)
{
INIT_LIST_HEAD(&napi->poll_list);
hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
napi->timer.function = napi_watchdog;
napi->gro_count = 0;
napi->gro_list = NULL;
napi->skb = NULL;
napi->poll = poll;
if (weight > NAPI_POLL_WEIGHT)
pr_err_once("netif_napi_add() called with weight %d on device %s\n",
weight, dev->name);
napi->weight = weight;
list_add(&napi->dev_list, &dev->napi_list);
napi->dev = dev;
#ifdef CONFIG_NETPOLL
napi->poll_owner = -1;
#endif
set_bit(NAPI_STATE_SCHED, &napi->state);
napi_hash_add(napi);
}
EXPORT_SYMBOL(netif_napi_add);
void napi_disable(struct napi_struct *n)
{
might_sleep();
set_bit(NAPI_STATE_DISABLE, &n->state);
while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
msleep(1);
while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
msleep(1);
hrtimer_cancel(&n->timer);
clear_bit(NAPI_STATE_DISABLE, &n->state);
}
EXPORT_SYMBOL(napi_disable);
/* Must be called in process context */
void netif_napi_del(struct napi_struct *napi)
{
might_sleep();
if (napi_hash_del(napi))
synchronize_net();
list_del_init(&napi->dev_list);
napi_free_frags(napi);
kfree_skb_list(napi->gro_list);
napi->gro_list = NULL;
napi->gro_count = 0;
}
EXPORT_SYMBOL(netif_napi_del);
static int napi_poll(struct napi_struct *n, struct list_head *repoll)
{
void *have;
int work, weight;
list_del_init(&n->poll_list);
have = netpoll_poll_lock(n);
weight = n->weight;
/* This NAPI_STATE_SCHED test is for avoiding a race
* with netpoll's poll_napi(). Only the entity which
* obtains the lock and sees NAPI_STATE_SCHED set will
* actually make the ->poll() call. Therefore we avoid
* accidentally calling ->poll() when NAPI is not scheduled.
*/
work = 0;
if (test_bit(NAPI_STATE_SCHED, &n->state)) {
work = n->poll(n, weight);
trace_napi_poll(n, work, weight);
}
WARN_ON_ONCE(work > weight);
if (likely(work < weight))
goto out_unlock;
/* Drivers must not modify the NAPI state if they
* consume the entire weight. In such cases this code
* still "owns" the NAPI instance and therefore can
* move the instance around on the list at-will.
*/
if (unlikely(napi_disable_pending(n))) {
napi_complete(n);
goto out_unlock;
}
if (n->gro_list) {
/* flush too old packets
* If HZ < 1000, flush all packets.
*/
napi_gro_flush(n, HZ >= 1000);
}
/* Some drivers may have called napi_schedule
* prior to exhausting their budget.
*/
if (unlikely(!list_empty(&n->poll_list))) {
pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
n->dev ? n->dev->name : "backlog");
goto out_unlock;
}
list_add_tail(&n->poll_list, repoll);
out_unlock:
netpoll_poll_unlock(have);
return work;
}
static __latent_entropy void net_rx_action(struct softirq_action *h)
{
struct softnet_data *sd = this_cpu_ptr(&softnet_data);
unsigned long time_limit = jiffies +
usecs_to_jiffies(netdev_budget_usecs);
int budget = netdev_budget;
LIST_HEAD(list);
LIST_HEAD(repoll);
local_irq_disable();
list_splice_init(&sd->poll_list, &list);
local_irq_enable();
for (;;) {
struct napi_struct *n;
if (list_empty(&list)) {
if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
goto out;
break;
}
n = list_first_entry(&list, struct napi_struct, poll_list);
budget -= napi_poll(n, &repoll);
/* If softirq window is exhausted then punt.
* Allow this to run for 2 jiffies since which will allow
* an average latency of 1.5/HZ.
*/
if (unlikely(budget <= 0 ||
time_after_eq(jiffies, time_limit))) {
sd->time_squeeze++;
break;
}
}
local_irq_disable();
list_splice_tail_init(&sd->poll_list, &list);
list_splice_tail(&repoll, &list);
list_splice(&list, &sd->poll_list);
if (!list_empty(&sd->poll_list))
__raise_softirq_irqoff(NET_RX_SOFTIRQ);
net_rps_action_and_irq_enable(sd);
out:
__kfree_skb_flush();
}
struct netdev_adjacent {
struct net_device *dev;
/* upper master flag, there can only be one master device per list */
bool master;
/* counter for the number of times this device was added to us */
u16 ref_nr;
/* private field for the users */
void *private;
struct list_head list;
struct rcu_head rcu;
};
static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
struct list_head *adj_list)
{
struct netdev_adjacent *adj;
list_for_each_entry(adj, adj_list, list) {
if (adj->dev == adj_dev)
return adj;
}
return NULL;
}
static int __netdev_has_upper_dev(struct net_device *upper_dev, void *data)
{
struct net_device *dev = data;
return upper_dev == dev;
}
/**
* netdev_has_upper_dev - Check if device is linked to an upper device
* @dev: device
* @upper_dev: upper device to check
*
* Find out if a device is linked to specified upper device and return true
* in case it is. Note that this checks only immediate upper device,
* not through a complete stack of devices. The caller must hold the RTNL lock.
*/
bool netdev_has_upper_dev(struct net_device *dev,
struct net_device *upper_dev)
{
ASSERT_RTNL();
return netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
upper_dev);
}
EXPORT_SYMBOL(netdev_has_upper_dev);
/**
* netdev_has_upper_dev_all - Check if device is linked to an upper device
* @dev: device
* @upper_dev: upper device to check
*
* Find out if a device is linked to specified upper device and return true
* in case it is. Note that this checks the entire upper device chain.
* The caller must hold rcu lock.
*/
bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
struct net_device *upper_dev)
{
return !!netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
upper_dev);
}
EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
/**
* netdev_has_any_upper_dev - Check if device is linked to some device
* @dev: device
*
* Find out if a device is linked to an upper device and return true in case
* it is. The caller must hold the RTNL lock.
*/
bool netdev_has_any_upper_dev(struct net_device *dev)
{
ASSERT_RTNL();
return !list_empty(&dev->adj_list.upper);
}
EXPORT_SYMBOL(netdev_has_any_upper_dev);
/**
* netdev_master_upper_dev_get - Get master upper device
* @dev: device
*
* Find a master upper device and return pointer to it or NULL in case
* it's not there. The caller must hold the RTNL lock.
*/
struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
{
struct netdev_adjacent *upper;
ASSERT_RTNL();
if (list_empty(&dev->adj_list.upper))
return NULL;
upper = list_first_entry(&dev->adj_list.upper,
struct netdev_adjacent, list);
if (likely(upper->master))
return upper->dev;
return NULL;
}
EXPORT_SYMBOL(netdev_master_upper_dev_get);
/**
* netdev_has_any_lower_dev - Check if device is linked to some device
* @dev: device
*
* Find out if a device is linked to a lower device and return true in case
* it is. The caller must hold the RTNL lock.
*/
static bool netdev_has_any_lower_dev(struct net_device *dev)
{
ASSERT_RTNL();
return !list_empty(&dev->adj_list.lower);
}
void *netdev_adjacent_get_private(struct list_head *adj_list)
{
struct netdev_adjacent *adj;
adj = list_entry(adj_list, struct netdev_adjacent, list);
return adj->private;
}
EXPORT_SYMBOL(netdev_adjacent_get_private);
/**
* netdev_upper_get_next_dev_rcu - Get the next dev from upper list
* @dev: device
* @iter: list_head ** of the current position
*
* Gets the next device from the dev's upper list, starting from iter
* position. The caller must hold RCU read lock.
*/
struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
struct list_head **iter)
{
struct netdev_adjacent *upper;
WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
if (&upper->list == &dev->adj_list.upper)
return NULL;
*iter = &upper->list;
return upper->dev;
}
EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
struct list_head **iter)
{
struct netdev_adjacent *upper;
WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
if (&upper->list == &dev->adj_list.upper)
return NULL;
*iter = &upper->list;
return upper->dev;
}
int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
int (*fn)(struct net_device *dev,
void *data),
void *data)
{
struct net_device *udev;
struct list_head *iter;
int ret;
for (iter = &dev->adj_list.upper,
udev = netdev_next_upper_dev_rcu(dev, &iter);
udev;
udev = netdev_next_upper_dev_rcu(dev, &iter)) {
/* first is the upper device itself */
ret = fn(udev, data);
if (ret)
return ret;
/* then look at all of its upper devices */
ret = netdev_walk_all_upper_dev_rcu(udev, fn, data);
if (ret)
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
/**
* netdev_lower_get_next_private - Get the next ->private from the
* lower neighbour list
* @dev: device
* @iter: list_head ** of the current position
*
* Gets the next netdev_adjacent->private from the dev's lower neighbour
* list, starting from iter position. The caller must hold either hold the
* RTNL lock or its own locking that guarantees that the neighbour lower
* list will remain unchanged.
*/
void *netdev_lower_get_next_private(struct net_device *dev,
struct list_head **iter)
{
struct netdev_adjacent *lower;
lower = list_entry(*iter, struct netdev_adjacent, list);
if (&lower->list == &dev->adj_list.lower)
return NULL;
*iter = lower->list.next;
return lower->private;
}
EXPORT_SYMBOL(netdev_lower_get_next_private);
/**
* netdev_lower_get_next_private_rcu - Get the next ->private from the
* lower neighbour list, RCU
* variant
* @dev: device
* @iter: list_head ** of the current position
*
* Gets the next netdev_adjacent->private from the dev's lower neighbour
* list, starting from iter position. The caller must hold RCU read lock.
*/
void *netdev_lower_get_next_private_rcu(struct net_device *dev,
struct list_head **iter)
{
struct netdev_adjacent *lower;
WARN_ON_ONCE(!rcu_read_lock_held());
lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
if (&lower->list == &dev->adj_list.lower)
return NULL;
*iter = &lower->list;
return lower->private;
}
EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
/**
* netdev_lower_get_next - Get the next device from the lower neighbour
* list
* @dev: device
* @iter: list_head ** of the current position
*
* Gets the next netdev_adjacent from the dev's lower neighbour
* list, starting from iter position. The caller must hold RTNL lock or
* its own locking that guarantees that the neighbour lower
* list will remain unchanged.
*/
void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
{
struct netdev_adjacent *lower;
lower = list_entry(*iter, struct netdev_adjacent, list);
if (&lower->list == &dev->adj_list.lower)
return NULL;
*iter = lower->list.next;
return lower->dev;
}
EXPORT_SYMBOL(netdev_lower_get_next);
static struct net_device *netdev_next_lower_dev(struct net_device *dev,
struct list_head **iter)
{
struct netdev_adjacent *lower;
lower = list_entry((*iter)->next, struct netdev_adjacent, list);
if (&lower->list == &dev->adj_list.lower)
return NULL;
*iter = &lower->list;
return lower->dev;
}
int netdev_walk_all_lower_dev(struct net_device *dev,
int (*fn)(struct net_device *dev,
void *data),
void *data)
{
struct net_device *ldev;
struct list_head *iter;
int ret;
for (iter = &dev->adj_list.lower,
ldev = netdev_next_lower_dev(dev, &iter);
ldev;
ldev = netdev_next_lower_dev(dev, &iter)) {
/* first is the lower device itself */
ret = fn(ldev, data);
if (ret)
return ret;
/* then look at all of its lower devices */
ret = netdev_walk_all_lower_dev(ldev, fn, data);
if (ret)
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
static struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
struct list_head **iter)
{
struct netdev_adjacent *lower;
lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
if (&lower->list == &dev->adj_list.lower)
return NULL;
*iter = &lower->list;
return lower->dev;
}
int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
int (*fn)(struct net_device *dev,
void *data),
void *data)
{
struct net_device *ldev;
struct list_head *iter;
int ret;
for (iter = &dev->adj_list.lower,
ldev = netdev_next_lower_dev_rcu(dev, &iter);
ldev;
ldev = netdev_next_lower_dev_rcu(dev, &iter)) {
/* first is the lower device itself */
ret = fn(ldev, data);
if (ret)
return ret;
/* then look at all of its lower devices */
ret = netdev_walk_all_lower_dev_rcu(ldev, fn, data);
if (ret)
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
/**
* netdev_lower_get_first_private_rcu - Get the first ->private from the
* lower neighbour list, RCU
* variant
* @dev: device
*
* Gets the first netdev_adjacent->private from the dev's lower neighbour
* list. The caller must hold RCU read lock.
*/
void *netdev_lower_get_first_private_rcu(struct net_device *dev)
{
struct netdev_adjacent *lower;
lower = list_first_or_null_rcu(&dev->adj_list.lower,
struct netdev_adjacent, list);
if (lower)
return lower->private;
return NULL;
}
EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
/**
* netdev_master_upper_dev_get_rcu - Get master upper device
* @dev: device
*
* Find a master upper device and return pointer to it or NULL in case
* it's not there. The caller must hold the RCU read lock.
*/
struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
{
struct netdev_adjacent *upper;
upper = list_first_or_null_rcu(&dev->adj_list.upper,
struct netdev_adjacent, list);
if (upper && likely(upper->master))
return upper->dev;
return NULL;
}
EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
static int netdev_adjacent_sysfs_add(struct net_device *dev,
struct net_device *adj_dev,
struct list_head *dev_list)
{
char linkname[IFNAMSIZ+7];
sprintf(linkname, dev_list == &dev->adj_list.upper ?
"upper_%s" : "lower_%s", adj_dev->name);
return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
linkname);
}
static void netdev_adjacent_sysfs_del(struct net_device *dev,
char *name,
struct list_head *dev_list)
{
char linkname[IFNAMSIZ+7];
sprintf(linkname, dev_list == &dev->adj_list.upper ?
"upper_%s" : "lower_%s", name);
sysfs_remove_link(&(dev->dev.kobj), linkname);
}
static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
struct net_device *adj_dev,
struct list_head *dev_list)
{
return (dev_list == &dev->adj_list.upper ||
dev_list == &dev->adj_list.lower) &&
net_eq(dev_net(dev), dev_net(adj_dev));
}
static int __netdev_adjacent_dev_insert(struct net_device *dev,
struct net_device *adj_dev,
struct list_head *dev_list,
void *private, bool master)
{
struct netdev_adjacent *adj;
int ret;
adj = __netdev_find_adj(adj_dev, dev_list);
if (adj) {
adj->ref_nr += 1;
pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
dev->name, adj_dev->name, adj->ref_nr);
return 0;
}
adj = kmalloc(sizeof(*adj), GFP_KERNEL);
if (!adj)
return -ENOMEM;
adj->dev = adj_dev;
adj->master = master;
adj->ref_nr = 1;
adj->private = private;
dev_hold(adj_dev);
pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
if (ret)
goto free_adj;
}
/* Ensure that master link is always the first item in list. */
if (master) {
ret = sysfs_create_link(&(dev->dev.kobj),
&(adj_dev->dev.kobj), "master");
if (ret)
goto remove_symlinks;
list_add_rcu(&adj->list, dev_list);
} else {
list_add_tail_rcu(&adj->list, dev_list);
}
return 0;
remove_symlinks:
if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
free_adj:
kfree(adj);
dev_put(adj_dev);
return ret;
}
static void __netdev_adjacent_dev_remove(struct net_device *dev,
struct net_device *adj_dev,
u16 ref_nr,
struct list_head *dev_list)
{
struct netdev_adjacent *adj;
pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
dev->name, adj_dev->name, ref_nr);
adj = __netdev_find_adj(adj_dev, dev_list);
if (!adj) {
pr_err("Adjacency does not exist for device %s from %s\n",
dev->name, adj_dev->name);
WARN_ON(1);
return;
}
if (adj->ref_nr > ref_nr) {
pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
dev->name, adj_dev->name, ref_nr,
adj->ref_nr - ref_nr);
adj->ref_nr -= ref_nr;
return;
}
if (adj->master)
sysfs_remove_link(&(dev->dev.kobj), "master");
if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
list_del_rcu(&adj->list);
pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
adj_dev->name, dev->name, adj_dev->name);
dev_put(adj_dev);
kfree_rcu(adj, rcu);
}
static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
struct net_device *upper_dev,
struct list_head *up_list,
struct list_head *down_list,
void *private, bool master)
{
int ret;
ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
private, master);
if (ret)
return ret;
ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
private, false);
if (ret) {
__netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
return ret;
}
return 0;
}
static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
struct net_device *upper_dev,
u16 ref_nr,
struct list_head *up_list,
struct list_head *down_list)
{
__netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
__netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
}
static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
struct net_device *upper_dev,
void *private, bool master)
{
return __netdev_adjacent_dev_link_lists(dev, upper_dev,
&dev->adj_list.upper,
&upper_dev->adj_list.lower,
private, master);
}
static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
struct net_device *upper_dev)
{
__netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
&dev->adj_list.upper,
&upper_dev->adj_list.lower);
}
static int __netdev_upper_dev_link(struct net_device *dev,
struct net_device *upper_dev, bool master,
void *upper_priv, void *upper_info)
{
struct netdev_notifier_changeupper_info changeupper_info;
int ret = 0;
ASSERT_RTNL();
if (dev == upper_dev)
return -EBUSY;
/* To prevent loops, check if dev is not upper device to upper_dev. */
if (netdev_has_upper_dev(upper_dev, dev))
return -EBUSY;
if (netdev_has_upper_dev(dev, upper_dev))
return -EEXIST;
if (master && netdev_master_upper_dev_get(dev))
return -EBUSY;
changeupper_info.upper_dev = upper_dev;
changeupper_info.master = master;
changeupper_info.linking = true;
changeupper_info.upper_info = upper_info;
ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, dev,
&changeupper_info.info);
ret = notifier_to_errno(ret);
if (ret)
return ret;
ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
master);
if (ret)
return ret;
ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, dev,
&changeupper_info.info);
ret = notifier_to_errno(ret);
if (ret)
goto rollback;
return 0;
rollback:
__netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
return ret;
}
/**
* netdev_upper_dev_link - Add a link to the upper device
* @dev: device
* @upper_dev: new upper device
*
* Adds a link to device which is upper to this one. The caller must hold
* the RTNL lock. On a failure a negative errno code is returned.
* On success the reference counts are adjusted and the function
* returns zero.
*/
int netdev_upper_dev_link(struct net_device *dev,
struct net_device *upper_dev)
{
return __netdev_upper_dev_link(dev, upper_dev, false, NULL, NULL);
}
EXPORT_SYMBOL(netdev_upper_dev_link);
/**
* netdev_master_upper_dev_link - Add a master link to the upper device
* @dev: device
* @upper_dev: new upper device
* @upper_priv: upper device private
* @upper_info: upper info to be passed down via notifier
*
* Adds a link to device which is upper to this one. In this case, only
* one master upper device can be linked, although other non-master devices
* might be linked as well. The caller must hold the RTNL lock.
* On a failure a negative errno code is returned. On success the reference
* counts are adjusted and the function returns zero.
*/
int netdev_master_upper_dev_link(struct net_device *dev,
struct net_device *upper_dev,
void *upper_priv, void *upper_info)
{
return __netdev_upper_dev_link(dev, upper_dev, true,
upper_priv, upper_info);
}
EXPORT_SYMBOL(netdev_master_upper_dev_link);
/**
* netdev_upper_dev_unlink - Removes a link to upper device
* @dev: device
* @upper_dev: new upper device
*
* Removes a link to device which is upper to this one. The caller must hold
* the RTNL lock.
*/
void netdev_upper_dev_unlink(struct net_device *dev,
struct net_device *upper_dev)
{
struct netdev_notifier_changeupper_info changeupper_info;
ASSERT_RTNL();
changeupper_info.upper_dev = upper_dev;
changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
changeupper_info.linking = false;
call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, dev,
&changeupper_info.info);
__netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, dev,
&changeupper_info.info);
}
EXPORT_SYMBOL(netdev_upper_dev_unlink);
/**
* netdev_bonding_info_change - Dispatch event about slave change
* @dev: device
* @bonding_info: info to dispatch
*
* Send NETDEV_BONDING_INFO to netdev notifiers with info.
* The caller must hold the RTNL lock.
*/
void netdev_bonding_info_change(struct net_device *dev,
struct netdev_bonding_info *bonding_info)
{
struct netdev_notifier_bonding_info info;
memcpy(&info.bonding_info, bonding_info,
sizeof(struct netdev_bonding_info));
call_netdevice_notifiers_info(NETDEV_BONDING_INFO, dev,
&info.info);
}
EXPORT_SYMBOL(netdev_bonding_info_change);
static void netdev_adjacent_add_links(struct net_device *dev)
{
struct netdev_adjacent *iter;
struct net *net = dev_net(dev);
list_for_each_entry(iter, &dev->adj_list.upper, list) {
if (!net_eq(net, dev_net(iter->dev)))
continue;
netdev_adjacent_sysfs_add(iter->dev, dev,
&iter->dev->adj_list.lower);
netdev_adjacent_sysfs_add(dev, iter->dev,
&dev->adj_list.upper);
}
list_for_each_entry(iter, &dev->adj_list.lower, list) {
if (!net_eq(net, dev_net(iter->dev)))
continue;
netdev_adjacent_sysfs_add(iter->dev, dev,
&iter->dev->adj_list.upper);
netdev_adjacent_sysfs_add(dev, iter->dev,
&dev->adj_list.lower);
}
}
static void netdev_adjacent_del_links(struct net_device *dev)
{
struct netdev_adjacent *iter;
struct net *net = dev_net(dev);
list_for_each_entry(iter, &dev->adj_list.upper, list) {
if (!net_eq(net, dev_net(iter->dev)))
continue;
netdev_adjacent_sysfs_del(iter->dev, dev->name,
&iter->dev->adj_list.lower);
netdev_adjacent_sysfs_del(dev, iter->dev->name,
&dev->adj_list.upper);
}
list_for_each_entry(iter, &dev->adj_list.lower, list) {
if (!net_eq(net, dev_net(iter->dev)))
continue;
netdev_adjacent_sysfs_del(iter->dev, dev->name,
&iter->dev->adj_list.upper);
netdev_adjacent_sysfs_del(dev, iter->dev->name,
&dev->adj_list.lower);
}
}
void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
{
struct netdev_adjacent *iter;
struct net *net = dev_net(dev);
list_for_each_entry(iter, &dev->adj_list.upper, list) {
if (!net_eq(net, dev_net(iter->dev)))
continue;
netdev_adjacent_sysfs_del(iter->dev, oldname,
&iter->dev->adj_list.lower);
netdev_adjacent_sysfs_add(iter->dev, dev,
&iter->dev->adj_list.lower);
}
list_for_each_entry(iter, &dev->adj_list.lower, list) {
if (!net_eq(net, dev_net(iter->dev)))
continue;
netdev_adjacent_sysfs_del(iter->dev, oldname,
&iter->dev->adj_list.upper);
netdev_adjacent_sysfs_add(iter->dev, dev,
&iter->dev->adj_list.upper);
}
}
void *netdev_lower_dev_get_private(struct net_device *dev,
struct net_device *lower_dev)
{
struct netdev_adjacent *lower;
if (!lower_dev)
return NULL;
lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
if (!lower)
return NULL;
return lower->private;
}
EXPORT_SYMBOL(netdev_lower_dev_get_private);
int dev_get_nest_level(struct net_device *dev)
{
struct net_device *lower = NULL;
struct list_head *iter;
int max_nest = -1;
int nest;
ASSERT_RTNL();
netdev_for_each_lower_dev(dev, lower, iter) {
nest = dev_get_nest_level(lower);
if (max_nest < nest)
max_nest = nest;
}
return max_nest + 1;
}
EXPORT_SYMBOL(dev_get_nest_level);
/**
* netdev_lower_change - Dispatch event about lower device state change
* @lower_dev: device
* @lower_state_info: state to dispatch
*
* Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
* The caller must hold the RTNL lock.
*/
void netdev_lower_state_changed(struct net_device *lower_dev,
void *lower_state_info)
{
struct netdev_notifier_changelowerstate_info changelowerstate_info;
ASSERT_RTNL();
changelowerstate_info.lower_state_info = lower_state_info;
call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE, lower_dev,
&changelowerstate_info.info);
}
EXPORT_SYMBOL(netdev_lower_state_changed);
static void dev_change_rx_flags(struct net_device *dev, int flags)
{
const struct net_device_ops *ops = dev->netdev_ops;
if (ops->ndo_change_rx_flags)
ops->ndo_change_rx_flags(dev, flags);
}
static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
{
unsigned int old_flags = dev->flags;
kuid_t uid;
kgid_t gid;
ASSERT_RTNL();
dev->flags |= IFF_PROMISC;
dev->promiscuity += inc;
if (dev->promiscuity == 0) {
/*
* Avoid overflow.
* If inc causes overflow, untouch promisc and return error.
*/
if (inc < 0)
dev->flags &= ~IFF_PROMISC;
else {
dev->promiscuity -= inc;
pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
dev->name);
return -EOVERFLOW;
}
}
if (dev->flags != old_flags) {
pr_info("device %s %s promiscuous mode\n",
dev->name,
dev->flags & IFF_PROMISC ? "entered" : "left");
if (audit_enabled) {
current_uid_gid(&uid, &gid);
audit_log(current->audit_context, GFP_ATOMIC,
AUDIT_ANOM_PROMISCUOUS,
"dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
dev->name, (dev->flags & IFF_PROMISC),
(old_flags & IFF_PROMISC),
from_kuid(&init_user_ns, audit_get_loginuid(current)),
from_kuid(&init_user_ns, uid),
from_kgid(&init_user_ns, gid),
audit_get_sessionid(current));
}
dev_change_rx_flags(dev, IFF_PROMISC);
}
if (notify)
__dev_notify_flags(dev, old_flags, IFF_PROMISC);
return 0;
}
/**
* dev_set_promiscuity - update promiscuity count on a device
* @dev: device
* @inc: modifier
*
* Add or remove promiscuity from a device. While the count in the device
* remains above zero the interface remains promiscuous. Once it hits zero
* the device reverts back to normal filtering operation. A negative inc
* value is used to drop promiscuity on the device.
* Return 0 if successful or a negative errno code on error.
*/
int dev_set_promiscuity(struct net_device *dev, int inc)
{
unsigned int old_flags = dev->flags;
int err;
err = __dev_set_promiscuity(dev, inc, true);
if (err < 0)
return err;
if (dev->flags != old_flags)
dev_set_rx_mode(dev);
return err;
}
EXPORT_SYMBOL(dev_set_promiscuity);
static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
{
unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
ASSERT_RTNL();
dev->flags |= IFF_ALLMULTI;
dev->allmulti += inc;
if (dev->allmulti == 0) {
/*
* Avoid overflow.
* If inc causes overflow, untouch allmulti and return error.
*/
if (inc < 0)
dev->flags &= ~IFF_ALLMULTI;
else {
dev->allmulti -= inc;
pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
dev->name);
return -EOVERFLOW;
}
}
if (dev->flags ^ old_flags) {
dev_change_rx_flags(dev, IFF_ALLMULTI);
dev_set_rx_mode(dev);
if (notify)
__dev_notify_flags(dev, old_flags,
dev->gflags ^ old_gflags);
}
return 0;
}
/**
* dev_set_allmulti - update allmulti count on a device
* @dev: device
* @inc: modifier
*
* Add or remove reception of all multicast frames to a device. While the
* count in the device remains above zero the interface remains listening
* to all interfaces. Once it hits zero the device reverts back to normal
* filtering operation. A negative @inc value is used to drop the counter
* when releasing a resource needing all multicasts.
* Return 0 if successful or a negative errno code on error.
*/
int dev_set_allmulti(struct net_device *dev, int inc)
{
return __dev_set_allmulti(dev, inc, true);
}
EXPORT_SYMBOL(dev_set_allmulti);
/*
* Upload unicast and multicast address lists to device and
* configure RX filtering. When the device doesn't support unicast
* filtering it is put in promiscuous mode while unicast addresses
* are present.
*/
void __dev_set_rx_mode(struct net_device *dev)
{
const struct net_device_ops *ops = dev->netdev_ops;
/* dev_open will call this function so the list will stay sane. */
if (!(dev->flags&IFF_UP))
return;
if (!netif_device_present(dev))
return;
if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
/* Unicast addresses changes may only happen under the rtnl,
* therefore calling __dev_set_promiscuity here is safe.
*/
if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
__dev_set_promiscuity(dev, 1, false);
dev->uc_promisc = true;
} else if (netdev_uc_empty(dev) && dev->uc_promisc) {
__dev_set_promiscuity(dev, -1, false);
dev->uc_promisc = false;
}
}
if (ops->ndo_set_rx_mode)
ops->ndo_set_rx_mode(dev);
}
void dev_set_rx_mode(struct net_device *dev)
{
netif_addr_lock_bh(dev);
__dev_set_rx_mode(dev);
netif_addr_unlock_bh(dev);
}
/**
* dev_get_flags - get flags reported to userspace
* @dev: device
*
* Get the combination of flag bits exported through APIs to userspace.
*/
unsigned int dev_get_flags(const struct net_device *dev)
{
unsigned int flags;
flags = (dev->flags & ~(IFF_PROMISC |
IFF_ALLMULTI |
IFF_RUNNING |
IFF_LOWER_UP |
IFF_DORMANT)) |
(dev->gflags & (IFF_PROMISC |
IFF_ALLMULTI));
if (netif_running(dev)) {
if (netif_oper_up(dev))
flags |= IFF_RUNNING;
if (netif_carrier_ok(dev))
flags |= IFF_LOWER_UP;
if (netif_dormant(dev))
flags |= IFF_DORMANT;
}
return flags;
}
EXPORT_SYMBOL(dev_get_flags);
int __dev_change_flags(struct net_device *dev, unsigned int flags)
{
unsigned int old_flags = dev->flags;
int ret;
ASSERT_RTNL();
/*
* Set the flags on our device.
*/
dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
IFF_AUTOMEDIA)) |
(dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
IFF_ALLMULTI));
/*
* Load in the correct multicast list now the flags have changed.
*/
if ((old_flags ^ flags) & IFF_MULTICAST)
dev_change_rx_flags(dev, IFF_MULTICAST);
dev_set_rx_mode(dev);
/*
* Have we downed the interface. We handle IFF_UP ourselves
* according to user attempts to set it, rather than blindly
* setting it.
*/
ret = 0;
if ((old_flags ^ flags) & IFF_UP) {
if (old_flags & IFF_UP)
__dev_close(dev);
else
ret = __dev_open(dev);
}
if ((flags ^ dev->gflags) & IFF_PROMISC) {
int inc = (flags & IFF_PROMISC) ? 1 : -1;
unsigned int old_flags = dev->flags;
dev->gflags ^= IFF_PROMISC;
if (__dev_set_promiscuity(dev, inc, false) >= 0)
if (dev->flags != old_flags)
dev_set_rx_mode(dev);
}
/* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
* is important. Some (broken) drivers set IFF_PROMISC, when
* IFF_ALLMULTI is requested not asking us and not reporting.
*/
if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
dev->gflags ^= IFF_ALLMULTI;
__dev_set_allmulti(dev, inc, false);
}
return ret;
}
void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
unsigned int gchanges)
{
unsigned int changes = dev->flags ^ old_flags;
if (gchanges)
rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
if (changes & IFF_UP) {
if (dev->flags & IFF_UP)
call_netdevice_notifiers(NETDEV_UP, dev);
else
call_netdevice_notifiers(NETDEV_DOWN, dev);
}
if (dev->flags & IFF_UP &&
(changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
struct netdev_notifier_change_info change_info;
change_info.flags_changed = changes;
call_netdevice_notifiers_info(NETDEV_CHANGE, dev,
&change_info.info);
}
}
/**
* dev_change_flags - change device settings
* @dev: device
* @flags: device state flags
*
* Change settings on device based state flags. The flags are
* in the userspace exported format.
*/
int dev_change_flags(struct net_device *dev, unsigned int flags)
{
int ret;
unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
ret = __dev_change_flags(dev, flags);
if (ret < 0)
return ret;
changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
__dev_notify_flags(dev, old_flags, changes);
return ret;
}
EXPORT_SYMBOL(dev_change_flags);
int __dev_set_mtu(struct net_device *dev, int new_mtu)
{
const struct net_device_ops *ops = dev->netdev_ops;
if (ops->ndo_change_mtu)
return ops->ndo_change_mtu(dev, new_mtu);
dev->mtu = new_mtu;
return 0;
}
EXPORT_SYMBOL(__dev_set_mtu);
/**
* dev_set_mtu - Change maximum transfer unit
* @dev: device
* @new_mtu: new transfer unit
*
* Change the maximum transfer size of the network device.
*/
int dev_set_mtu(struct net_device *dev, int new_mtu)
{
int err, orig_mtu;
if (new_mtu == dev->mtu)
return 0;
/* MTU must be positive, and in range */
if (new_mtu < 0 || new_mtu < dev->min_mtu) {
net_err_ratelimited("%s: Invalid MTU %d requested, hw min %d\n",
dev->name, new_mtu, dev->min_mtu);
return -EINVAL;
}
if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
net_err_ratelimited("%s: Invalid MTU %d requested, hw max %d\n",
dev->name, new_mtu, dev->max_mtu);
return -EINVAL;
}
if (!netif_device_present(dev))
return -ENODEV;
err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
err = notifier_to_errno(err);
if (err)
return err;
orig_mtu = dev->mtu;
err = __dev_set_mtu(dev, new_mtu);
if (!err) {
err = call_netdevice_notifiers(NETDEV_CHANGEMTU, dev);
err = notifier_to_errno(err);
if (err) {
/* setting mtu back and notifying everyone again,
* so that they have a chance to revert changes.
*/
__dev_set_mtu(dev, orig_mtu);
call_netdevice_notifiers(NETDEV_CHANGEMTU, dev);
}
}
return err;
}
EXPORT_SYMBOL(dev_set_mtu);
/**
* dev_set_group - Change group this device belongs to
* @dev: device
* @new_group: group this device should belong to
*/
void dev_set_group(struct net_device *dev, int new_group)
{
dev->group = new_group;
}
EXPORT_SYMBOL(dev_set_group);
/**
* dev_set_mac_address - Change Media Access Control Address
* @dev: device
* @sa: new address
*
* Change the hardware (MAC) address of the device
*/
int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa)
{
const struct net_device_ops *ops = dev->netdev_ops;
int err;
if (!ops->ndo_set_mac_address)
return -EOPNOTSUPP;
if (sa->sa_family != dev->type)
return -EINVAL;
if (!netif_device_present(dev))
return -ENODEV;
err = ops->ndo_set_mac_address(dev, sa);
if (err)
return err;
dev->addr_assign_type = NET_ADDR_SET;
call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
add_device_randomness(dev->dev_addr, dev->addr_len);
return 0;
}
EXPORT_SYMBOL(dev_set_mac_address);
/**
* dev_change_carrier - Change device carrier
* @dev: device
* @new_carrier: new value
*
* Change device carrier
*/
int dev_change_carrier(struct net_device *dev, bool new_carrier)
{
const struct net_device_ops *ops = dev->netdev_ops;
if (!ops->ndo_change_carrier)
return -EOPNOTSUPP;
if (!netif_device_present(dev))
return -ENODEV;
return ops->ndo_change_carrier(dev, new_carrier);
}
EXPORT_SYMBOL(dev_change_carrier);
/**
* dev_get_phys_port_id - Get device physical port ID
* @dev: device
* @ppid: port ID
*
* Get device physical port ID
*/
int dev_get_phys_port_id(struct net_device *dev,
struct netdev_phys_item_id *ppid)
{
const struct net_device_ops *ops = dev->netdev_ops;
if (!ops->ndo_get_phys_port_id)
return -EOPNOTSUPP;
return ops->ndo_get_phys_port_id(dev, ppid);
}
EXPORT_SYMBOL(dev_get_phys_port_id);
/**
* dev_get_phys_port_name - Get device physical port name
* @dev: device
* @name: port name
* @len: limit of bytes to copy to name
*
* Get device physical port name
*/
int dev_get_phys_port_name(struct net_device *dev,
char *name, size_t len)
{
const struct net_device_ops *ops = dev->netdev_ops;
if (!ops->ndo_get_phys_port_name)
return -EOPNOTSUPP;
return ops->ndo_get_phys_port_name(dev, name, len);
}
EXPORT_SYMBOL(dev_get_phys_port_name);
/**
* dev_change_proto_down - update protocol port state information
* @dev: device
* @proto_down: new value
*
* This info can be used by switch drivers to set the phys state of the
* port.
*/
int dev_change_proto_down(struct net_device *dev, bool proto_down)
{
const struct net_device_ops *ops = dev->netdev_ops;
if (!ops->ndo_change_proto_down)
return -EOPNOTSUPP;
if (!netif_device_present(dev))
return -ENODEV;
return ops->ndo_change_proto_down(dev, proto_down);
}
EXPORT_SYMBOL(dev_change_proto_down);
u8 __dev_xdp_attached(struct net_device *dev, xdp_op_t xdp_op, u32 *prog_id)
{
struct netdev_xdp xdp;
memset(&xdp, 0, sizeof(xdp));
xdp.command = XDP_QUERY_PROG;
/* Query must always succeed. */
WARN_ON(xdp_op(dev, &xdp) < 0);
if (prog_id)
*prog_id = xdp.prog_id;
return xdp.prog_attached;
}
static int dev_xdp_install(struct net_device *dev, xdp_op_t xdp_op,
struct netlink_ext_ack *extack, u32 flags,
struct bpf_prog *prog)
{
struct netdev_xdp xdp;
memset(&xdp, 0, sizeof(xdp));
if (flags & XDP_FLAGS_HW_MODE)
xdp.command = XDP_SETUP_PROG_HW;
else
xdp.command = XDP_SETUP_PROG;
xdp.extack = extack;
xdp.flags = flags;
xdp.prog = prog;
return xdp_op(dev, &xdp);
}
/**
* dev_change_xdp_fd - set or clear a bpf program for a device rx path
* @dev: device
* @extack: netlink extended ack
* @fd: new program fd or negative value to clear
* @flags: xdp-related flags
*
* Set or clear a bpf program for a device
*/
int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
int fd, u32 flags)
{
const struct net_device_ops *ops = dev->netdev_ops;
struct bpf_prog *prog = NULL;
xdp_op_t xdp_op, xdp_chk;
int err;
ASSERT_RTNL();
xdp_op = xdp_chk = ops->ndo_xdp;
if (!xdp_op && (flags & (XDP_FLAGS_DRV_MODE | XDP_FLAGS_HW_MODE)))
return -EOPNOTSUPP;
if (!xdp_op || (flags & XDP_FLAGS_SKB_MODE))
xdp_op = generic_xdp_install;
if (xdp_op == xdp_chk)
xdp_chk = generic_xdp_install;
if (fd >= 0) {
if (xdp_chk && __dev_xdp_attached(dev, xdp_chk, NULL))
return -EEXIST;
if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) &&
__dev_xdp_attached(dev, xdp_op, NULL))
return -EBUSY;
prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_XDP);
if (IS_ERR(prog))
return PTR_ERR(prog);
}
err = dev_xdp_install(dev, xdp_op, extack, flags, prog);
if (err < 0 && prog)
bpf_prog_put(prog);
return err;
}
/**
* dev_new_index - allocate an ifindex
* @net: the applicable net namespace
*
* Returns a suitable unique value for a new device interface
* number. The caller must hold the rtnl semaphore or the
* dev_base_lock to be sure it remains unique.
*/
static int dev_new_index(struct net *net)
{
int ifindex = net->ifindex;
for (;;) {
if (++ifindex <= 0)
ifindex = 1;
if (!__dev_get_by_index(net, ifindex))
return net->ifindex = ifindex;
}
}
/* Delayed registration/unregisteration */
static LIST_HEAD(net_todo_list);
DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
static void net_set_todo(struct net_device *dev)
{
list_add_tail(&dev->todo_list, &net_todo_list);
dev_net(dev)->dev_unreg_count++;
}
static void rollback_registered_many(struct list_head *head)
{
struct net_device *dev, *tmp;
LIST_HEAD(close_head);
BUG_ON(dev_boot_phase);
ASSERT_RTNL();
list_for_each_entry_safe(dev, tmp, head, unreg_list) {
/* Some devices call without registering
* for initialization unwind. Remove those
* devices and proceed with the remaining.
*/
if (dev->reg_state == NETREG_UNINITIALIZED) {
pr_debug("unregister_netdevice: device %s/%p never was registered\n",
dev->name, dev);
WARN_ON(1);
list_del(&dev->unreg_list);
continue;
}
dev->dismantle = true;
BUG_ON(dev->reg_state != NETREG_REGISTERED);
}
/* If device is running, close it first. */
list_for_each_entry(dev, head, unreg_list)
list_add_tail(&dev->close_list, &close_head);
dev_close_many(&close_head, true);
list_for_each_entry(dev, head, unreg_list) {
/* And unlink it from device chain. */
unlist_netdevice(dev);
dev->reg_state = NETREG_UNREGISTERING;
}
flush_all_backlogs();
synchronize_net();
list_for_each_entry(dev, head, unreg_list) {
struct sk_buff *skb = NULL;
/* Shutdown queueing discipline. */
dev_shutdown(dev);
/* Notify protocols, that we are about to destroy
* this device. They should clean all the things.
*/
call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
if (!dev->rtnl_link_ops ||
dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
GFP_KERNEL);
/*
* Flush the unicast and multicast chains
*/
dev_uc_flush(dev);
dev_mc_flush(dev);
if (dev->netdev_ops->ndo_uninit)
dev->netdev_ops->ndo_uninit(dev);
if (skb)
rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
/* Notifier chain MUST detach us all upper devices. */
WARN_ON(netdev_has_any_upper_dev(dev));
WARN_ON(netdev_has_any_lower_dev(dev));
/* Remove entries from kobject tree */
netdev_unregister_kobject(dev);
#ifdef CONFIG_XPS
/* Remove XPS queueing entries */
netif_reset_xps_queues_gt(dev, 0);
#endif
}
synchronize_net();
list_for_each_entry(dev, head, unreg_list)
dev_put(dev);
}
static void rollback_registered(struct net_device *dev)
{
LIST_HEAD(single);
list_add(&dev->unreg_list, &single);
rollback_registered_many(&single);
list_del(&single);
}
static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
struct net_device *upper, netdev_features_t features)
{
netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
netdev_features_t feature;
int feature_bit;
for_each_netdev_feature(&upper_disables, feature_bit) {
feature = __NETIF_F_BIT(feature_bit);
if (!(upper->wanted_features & feature)
&& (features & feature)) {
netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
&feature, upper->name);
features &= ~feature;
}
}
return features;
}
static void netdev_sync_lower_features(struct net_device *upper,
struct net_device *lower, netdev_features_t features)
{
netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
netdev_features_t feature;
int feature_bit;
for_each_netdev_feature(&upper_disables, feature_bit) {
feature = __NETIF_F_BIT(feature_bit);
if (!(features & feature) && (lower->features & feature)) {
netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
&feature, lower->name);
lower->wanted_features &= ~feature;
netdev_update_features(lower);
if (unlikely(lower->features & feature))
netdev_WARN(upper, "failed to disable %pNF on %s!\n",
&feature, lower->name);
}
}
}
static netdev_features_t netdev_fix_features(struct net_device *dev,
netdev_features_t features)
{
/* Fix illegal checksum combinations */
if ((features & NETIF_F_HW_CSUM) &&
(features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
netdev_warn(dev, "mixed HW and IP checksum settings.\n");
features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
}
/* TSO requires that SG is present as well. */
if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
features &= ~NETIF_F_ALL_TSO;
}
if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
!(features & NETIF_F_IP_CSUM)) {
netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
features &= ~NETIF_F_TSO;
features &= ~NETIF_F_TSO_ECN;
}
if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
!(features & NETIF_F_IPV6_CSUM)) {
netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
features &= ~NETIF_F_TSO6;
}
/* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
features &= ~NETIF_F_TSO_MANGLEID;
/* TSO ECN requires that TSO is present as well. */
if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
features &= ~NETIF_F_TSO_ECN;
/* Software GSO depends on SG. */
if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
features &= ~NETIF_F_GSO;
}
/* GSO partial features require GSO partial be set */
if ((features & dev->gso_partial_features) &&
!(features & NETIF_F_GSO_PARTIAL)) {
netdev_dbg(dev,
"Dropping partially supported GSO features since no GSO partial.\n");
features &= ~dev->gso_partial_features;
}
return features;
}
int __netdev_update_features(struct net_device *dev)
{
struct net_device *upper, *lower;
netdev_features_t features;
struct list_head *iter;
int err = -1;
ASSERT_RTNL();
features = netdev_get_wanted_features(dev);
if (dev->netdev_ops->ndo_fix_features)
features = dev->netdev_ops->ndo_fix_features(dev, features);
/* driver might be less strict about feature dependencies */
features = netdev_fix_features(dev, features);
/* some features can't be enabled if they're off an an upper device */
netdev_for_each_upper_dev_rcu(dev, upper, iter)
features = netdev_sync_upper_features(dev, upper, features);
if (dev->features == features)
goto sync_lower;
netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
&dev->features, &features);
if (dev->netdev_ops->ndo_set_features)
err = dev->netdev_ops->ndo_set_features(dev, features);
else
err = 0;
if (unlikely(err < 0)) {
netdev_err(dev,
"set_features() failed (%d); wanted %pNF, left %pNF\n",
err, &features, &dev->features);
/* return non-0 since some features might have changed and
* it's better to fire a spurious notification than miss it
*/
return -1;
}
sync_lower:
/* some features must be disabled on lower devices when disabled
* on an upper device (think: bonding master or bridge)
*/
netdev_for_each_lower_dev(dev, lower, iter)
netdev_sync_lower_features(dev, lower, features);
if (!err) {
netdev_features_t diff = features ^ dev->features;
if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
/* udp_tunnel_{get,drop}_rx_info both need
* NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
* device, or they won't do anything.
* Thus we need to update dev->features
* *before* calling udp_tunnel_get_rx_info,
* but *after* calling udp_tunnel_drop_rx_info.
*/
if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
dev->features = features;
udp_tunnel_get_rx_info(dev);
} else {
udp_tunnel_drop_rx_info(dev);
}
}
dev->features = features;
}
return err < 0 ? 0 : 1;
}
/**
* netdev_update_features - recalculate device features
* @dev: the device to check
*
* Recalculate dev->features set and send notifications if it
* has changed. Should be called after driver or hardware dependent
* conditions might have changed that influence the features.
*/
void netdev_update_features(struct net_device *dev)
{
if (__netdev_update_features(dev))
netdev_features_change(dev);
}
EXPORT_SYMBOL(netdev_update_features);
/**
* netdev_change_features - recalculate device features
* @dev: the device to check
*
* Recalculate dev->features set and send notifications even
* if they have not changed. Should be called instead of
* netdev_update_features() if also dev->vlan_features might
* have changed to allow the changes to be propagated to stacked
* VLAN devices.
*/
void netdev_change_features(struct net_device *dev)
{
__netdev_update_features(dev);
netdev_features_change(dev);
}
EXPORT_SYMBOL(netdev_change_features);
/**
* netif_stacked_transfer_operstate - transfer operstate
* @rootdev: the root or lower level device to transfer state from
* @dev: the device to transfer operstate to
*
* Transfer operational state from root to device. This is normally
* called when a stacking relationship exists between the root
* device and the device(a leaf device).
*/
void netif_stacked_transfer_operstate(const struct net_device *rootdev,
struct net_device *dev)
{
if (rootdev->operstate == IF_OPER_DORMANT)
netif_dormant_on(dev);
else
netif_dormant_off(dev);
if (netif_carrier_ok(rootdev))
netif_carrier_on(dev);
else
netif_carrier_off(dev);
}
EXPORT_SYMBOL(netif_stacked_transfer_operstate);
#ifdef CONFIG_SYSFS
static int netif_alloc_rx_queues(struct net_device *dev)
{
unsigned int i, count = dev->num_rx_queues;
struct netdev_rx_queue *rx;
size_t sz = count * sizeof(*rx);
BUG_ON(count < 1);
rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
if (!rx)
return -ENOMEM;
dev->_rx = rx;
for (i = 0; i < count; i++)
rx[i].dev = dev;
return 0;
}
#endif
static void netdev_init_one_queue(struct net_device *dev,
struct netdev_queue *queue, void *_unused)
{
/* Initialize queue lock */
spin_lock_init(&queue->_xmit_lock);
netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
queue->xmit_lock_owner = -1;
netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
queue->dev = dev;
#ifdef CONFIG_BQL
dql_init(&queue->dql, HZ);
#endif
}
static void netif_free_tx_queues(struct net_device *dev)
{
kvfree(dev->_tx);
}
static int netif_alloc_netdev_queues(struct net_device *dev)
{
unsigned int count = dev->num_tx_queues;
struct netdev_queue *tx;
size_t sz = count * sizeof(*tx);
if (count < 1 || count > 0xffff)
return -EINVAL;
tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
if (!tx)
return -ENOMEM;
dev->_tx = tx;
netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
spin_lock_init(&dev->tx_global_lock);
return 0;
}
void netif_tx_stop_all_queues(struct net_device *dev)
{
unsigned int i;
for (i = 0; i < dev->num_tx_queues; i++) {
struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
netif_tx_stop_queue(txq);
}
}
EXPORT_SYMBOL(netif_tx_stop_all_queues);
/**
* register_netdevice - register a network device
* @dev: device to register
*
* Take a completed network device structure and add it to the kernel
* interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
* chain. 0 is returned on success. A negative errno code is returned
* on a failure to set up the device, or if the name is a duplicate.
*
* Callers must hold the rtnl semaphore. You may want
* register_netdev() instead of this.
*
* BUGS:
* The locking appears insufficient to guarantee two parallel registers
* will not get the same name.
*/
int register_netdevice(struct net_device *dev)
{
int ret;
struct net *net = dev_net(dev);
BUG_ON(dev_boot_phase);
ASSERT_RTNL();
might_sleep();
/* When net_device's are persistent, this will be fatal. */
BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
BUG_ON(!net);
spin_lock_init(&dev->addr_list_lock);
netdev_set_addr_lockdep_class(dev);
ret = dev_get_valid_name(net, dev, dev->name);
if (ret < 0)
goto out;
/* Init, if this function is available */
if (dev->netdev_ops->ndo_init) {
ret = dev->netdev_ops->ndo_init(dev);
if (ret) {
if (ret > 0)
ret = -EIO;
goto out;
}
}
if (((dev->hw_features | dev->features) &
NETIF_F_HW_VLAN_CTAG_FILTER) &&
(!dev->netdev_ops->ndo_vlan_rx_add_vid ||
!dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
ret = -EINVAL;
goto err_uninit;
}
ret = -EBUSY;
if (!dev->ifindex)
dev->ifindex = dev_new_index(net);
else if (__dev_get_by_index(net, dev->ifindex))
goto err_uninit;
/* Transfer changeable features to wanted_features and enable
* software offloads (GSO and GRO).
*/
dev->hw_features |= NETIF_F_SOFT_FEATURES;
dev->features |= NETIF_F_SOFT_FEATURES;
if (dev->netdev_ops->ndo_udp_tunnel_add) {
dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
}
dev->wanted_features = dev->features & dev->hw_features;
if (!(dev->flags & IFF_LOOPBACK))
dev->hw_features |= NETIF_F_NOCACHE_COPY;
/* If IPv4 TCP segmentation offload is supported we should also
* allow the device to enable segmenting the frame with the option
* of ignoring a static IP ID value. This doesn't enable the
* feature itself but allows the user to enable it later.
*/
if (dev->hw_features & NETIF_F_TSO)
dev->hw_features |= NETIF_F_TSO_MANGLEID;
if (dev->vlan_features & NETIF_F_TSO)
dev->vlan_features |= NETIF_F_TSO_MANGLEID;
if (dev->mpls_features & NETIF_F_TSO)
dev->mpls_features |= NETIF_F_TSO_MANGLEID;
if (dev->hw_enc_features & NETIF_F_TSO)
dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
/* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
*/
dev->vlan_features |= NETIF_F_HIGHDMA;
/* Make NETIF_F_SG inheritable to tunnel devices.
*/
dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
/* Make NETIF_F_SG inheritable to MPLS.
*/
dev->mpls_features |= NETIF_F_SG;
ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
ret = notifier_to_errno(ret);
if (ret)
goto err_uninit;
ret = netdev_register_kobject(dev);
if (ret)
goto err_uninit;
dev->reg_state = NETREG_REGISTERED;
__netdev_update_features(dev);
/*
* Default initial state at registry is that the
* device is present.
*/
set_bit(__LINK_STATE_PRESENT, &dev->state);
linkwatch_init_dev(dev);
dev_init_scheduler(dev);
dev_hold(dev);
list_netdevice(dev);
add_device_randomness(dev->dev_addr, dev->addr_len);
/* If the device has permanent device address, driver should
* set dev_addr and also addr_assign_type should be set to
* NET_ADDR_PERM (default value).
*/
if (dev->addr_assign_type == NET_ADDR_PERM)
memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
/* Notify protocols, that a new device appeared. */
ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
ret = notifier_to_errno(ret);
if (ret) {
rollback_registered(dev);
dev->reg_state = NETREG_UNREGISTERED;
}
/*
* Prevent userspace races by waiting until the network
* device is fully setup before sending notifications.
*/
if (!dev->rtnl_link_ops ||
dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
out:
return ret;
err_uninit:
if (dev->netdev_ops->ndo_uninit)
dev->netdev_ops->ndo_uninit(dev);
if (dev->priv_destructor)
dev->priv_destructor(dev);
goto out;
}
EXPORT_SYMBOL(register_netdevice);
/**
* init_dummy_netdev - init a dummy network device for NAPI
* @dev: device to init
*
* This takes a network device structure and initialize the minimum
* amount of fields so it can be used to schedule NAPI polls without
* registering a full blown interface. This is to be used by drivers
* that need to tie several hardware interfaces to a single NAPI
* poll scheduler due to HW limitations.
*/
int init_dummy_netdev(struct net_device *dev)
{
/* Clear everything. Note we don't initialize spinlocks
* are they aren't supposed to be taken by any of the
* NAPI code and this dummy netdev is supposed to be
* only ever used for NAPI polls
*/
memset(dev, 0, sizeof(struct net_device));
/* make sure we BUG if trying to hit standard
* register/unregister code path
*/
dev->reg_state = NETREG_DUMMY;
/* NAPI wants this */
INIT_LIST_HEAD(&dev->napi_list);
/* a dummy interface is started by default */
set_bit(__LINK_STATE_PRESENT, &dev->state);
set_bit(__LINK_STATE_START, &dev->state);
/* Note : We dont allocate pcpu_refcnt for dummy devices,
* because users of this 'device' dont need to change
* its refcount.
*/
return 0;
}
EXPORT_SYMBOL_GPL(init_dummy_netdev);
/**
* register_netdev - register a network device
* @dev: device to register
*
* Take a completed network device structure and add it to the kernel
* interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
* chain. 0 is returned on success. A negative errno code is returned
* on a failure to set up the device, or if the name is a duplicate.
*
* This is a wrapper around register_netdevice that takes the rtnl semaphore
* and expands the device name if you passed a format string to
* alloc_netdev.
*/
int register_netdev(struct net_device *dev)
{
int err;
rtnl_lock();
err = register_netdevice(dev);
rtnl_unlock();
return err;
}
EXPORT_SYMBOL(register_netdev);
int netdev_refcnt_read(const struct net_device *dev)
{
int i, refcnt = 0;
for_each_possible_cpu(i)
refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
return refcnt;
}
EXPORT_SYMBOL(netdev_refcnt_read);
/**
* netdev_wait_allrefs - wait until all references are gone.
* @dev: target net_device
*
* This is called when unregistering network devices.
*
* Any protocol or device that holds a reference should register
* for netdevice notification, and cleanup and put back the
* reference if they receive an UNREGISTER event.
* We can get stuck here if buggy protocols don't correctly
* call dev_put.
*/
static void netdev_wait_allrefs(struct net_device *dev)
{
unsigned long rebroadcast_time, warning_time;
int refcnt;
linkwatch_forget_dev(dev);
rebroadcast_time = warning_time = jiffies;
refcnt = netdev_refcnt_read(dev);
while (refcnt != 0) {
if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
rtnl_lock();
/* Rebroadcast unregister notification */
call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
__rtnl_unlock();
rcu_barrier();
rtnl_lock();
call_netdevice_notifiers(NETDEV_UNREGISTER_FINAL, dev);
if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
&dev->state)) {
/* We must not have linkwatch events
* pending on unregister. If this
* happens, we simply run the queue
* unscheduled, resulting in a noop
* for this device.
*/
linkwatch_run_queue();
}
__rtnl_unlock();
rebroadcast_time = jiffies;
}
msleep(250);
refcnt = netdev_refcnt_read(dev);
if (time_after(jiffies, warning_time + 10 * HZ)) {
pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
dev->name, refcnt);
warning_time = jiffies;
}
}
}
/* The sequence is:
*
* rtnl_lock();
* ...
* register_netdevice(x1);
* register_netdevice(x2);
* ...
* unregister_netdevice(y1);
* unregister_netdevice(y2);
* ...
* rtnl_unlock();
* free_netdev(y1);
* free_netdev(y2);
*
* We are invoked by rtnl_unlock().
* This allows us to deal with problems:
* 1) We can delete sysfs objects which invoke hotplug
* without deadlocking with linkwatch via keventd.
* 2) Since we run with the RTNL semaphore not held, we can sleep
* safely in order to wait for the netdev refcnt to drop to zero.
*
* We must not return until all unregister events added during
* the interval the lock was held have been completed.
*/
void netdev_run_todo(void)
{
struct list_head list;
/* Snapshot list, allow later requests */
list_replace_init(&net_todo_list, &list);
__rtnl_unlock();
/* Wait for rcu callbacks to finish before next phase */
if (!list_empty(&list))
rcu_barrier();
while (!list_empty(&list)) {
struct net_device *dev
= list_first_entry(&list, struct net_device, todo_list);
list_del(&dev->todo_list);
rtnl_lock();
call_netdevice_notifiers(NETDEV_UNREGISTER_FINAL, dev);
__rtnl_unlock();
if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
pr_err("network todo '%s' but state %d\n",
dev->name, dev->reg_state);
dump_stack();
continue;
}
dev->reg_state = NETREG_UNREGISTERED;
netdev_wait_allrefs(dev);
/* paranoia */
BUG_ON(netdev_refcnt_read(dev));
BUG_ON(!list_empty(&dev->ptype_all));
BUG_ON(!list_empty(&dev->ptype_specific));
WARN_ON(rcu_access_pointer(dev->ip_ptr));
WARN_ON(rcu_access_pointer(dev->ip6_ptr));
WARN_ON(dev->dn_ptr);
if (dev->priv_destructor)
dev->priv_destructor(dev);
if (dev->needs_free_netdev)
free_netdev(dev);
/* Report a network device has been unregistered */
rtnl_lock();
dev_net(dev)->dev_unreg_count--;
__rtnl_unlock();
wake_up(&netdev_unregistering_wq);
/* Free network device */
kobject_put(&dev->dev.kobj);
}
}
/* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
* all the same fields in the same order as net_device_stats, with only
* the type differing, but rtnl_link_stats64 may have additional fields
* at the end for newer counters.
*/
void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
const struct net_device_stats *netdev_stats)
{
#if BITS_PER_LONG == 64
BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
/* zero out counters that only exist in rtnl_link_stats64 */
memset((char *)stats64 + sizeof(*netdev_stats), 0,
sizeof(*stats64) - sizeof(*netdev_stats));
#else
size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
const unsigned long *src = (const unsigned long *)netdev_stats;
u64 *dst = (u64 *)stats64;
BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
for (i = 0; i < n; i++)
dst[i] = src[i];
/* zero out counters that only exist in rtnl_link_stats64 */
memset((char *)stats64 + n * sizeof(u64), 0,
sizeof(*stats64) - n * sizeof(u64));
#endif
}
EXPORT_SYMBOL(netdev_stats_to_stats64);
/**
* dev_get_stats - get network device statistics
* @dev: device to get statistics from
* @storage: place to store stats
*
* Get network statistics from device. Return @storage.
* The device driver may provide its own method by setting
* dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
* otherwise the internal statistics structure is used.
*/
struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
struct rtnl_link_stats64 *storage)
{
const struct net_device_ops *ops = dev->netdev_ops;
if (ops->ndo_get_stats64) {
memset(storage, 0, sizeof(*storage));
ops->ndo_get_stats64(dev, storage);
} else if (ops->ndo_get_stats) {
netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
} else {
netdev_stats_to_stats64(storage, &dev->stats);
}
storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
return storage;
}
EXPORT_SYMBOL(dev_get_stats);
struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
{
struct netdev_queue *queue = dev_ingress_queue(dev);
#ifdef CONFIG_NET_CLS_ACT
if (queue)
return queue;
queue = kzalloc(sizeof(*queue), GFP_KERNEL);
if (!queue)
return NULL;
netdev_init_one_queue(dev, queue, NULL);
RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
queue->qdisc_sleeping = &noop_qdisc;
rcu_assign_pointer(dev->ingress_queue, queue);
#endif
return queue;
}
static const struct ethtool_ops default_ethtool_ops;
void netdev_set_default_ethtool_ops(struct net_device *dev,
const struct ethtool_ops *ops)
{
if (dev->ethtool_ops == &default_ethtool_ops)
dev->ethtool_ops = ops;
}
EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
void netdev_freemem(struct net_device *dev)
{
char *addr = (char *)dev - dev->padded;
kvfree(addr);
}
/**
* alloc_netdev_mqs - allocate network device
* @sizeof_priv: size of private data to allocate space for
* @name: device name format string
* @name_assign_type: origin of device name
* @setup: callback to initialize device
* @txqs: the number of TX subqueues to allocate
* @rxqs: the number of RX subqueues to allocate
*
* Allocates a struct net_device with private data area for driver use
* and performs basic initialization. Also allocates subqueue structs
* for each queue on the device.
*/
struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
unsigned char name_assign_type,
void (*setup)(struct net_device *),
unsigned int txqs, unsigned int rxqs)
{
struct net_device *dev;
size_t alloc_size;
struct net_device *p;
BUG_ON(strlen(name) >= sizeof(dev->name));
if (txqs < 1) {
pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
return NULL;
}
#ifdef CONFIG_SYSFS
if (rxqs < 1) {
pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
return NULL;
}
#endif
alloc_size = sizeof(struct net_device);
if (sizeof_priv) {
/* ensure 32-byte alignment of private area */
alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
alloc_size += sizeof_priv;
}
/* ensure 32-byte alignment of whole construct */
alloc_size += NETDEV_ALIGN - 1;
p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
if (!p)
return NULL;
dev = PTR_ALIGN(p, NETDEV_ALIGN);
dev->padded = (char *)dev - (char *)p;
dev->pcpu_refcnt = alloc_percpu(int);
if (!dev->pcpu_refcnt)
goto free_dev;
if (dev_addr_init(dev))
goto free_pcpu;
dev_mc_init(dev);
dev_uc_init(dev);
dev_net_set(dev, &init_net);
dev->gso_max_size = GSO_MAX_SIZE;
dev->gso_max_segs = GSO_MAX_SEGS;
INIT_LIST_HEAD(&dev->napi_list);
INIT_LIST_HEAD(&dev->unreg_list);
INIT_LIST_HEAD(&dev->close_list);
INIT_LIST_HEAD(&dev->link_watch_list);
INIT_LIST_HEAD(&dev->adj_list.upper);
INIT_LIST_HEAD(&dev->adj_list.lower);
INIT_LIST_HEAD(&dev->ptype_all);
INIT_LIST_HEAD(&dev->ptype_specific);
#ifdef CONFIG_NET_SCHED
hash_init(dev->qdisc_hash);
#endif
dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
setup(dev);
if (!dev->tx_queue_len) {
dev->priv_flags |= IFF_NO_QUEUE;
dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
}
dev->num_tx_queues = txqs;
dev->real_num_tx_queues = txqs;
if (netif_alloc_netdev_queues(dev))
goto free_all;
#ifdef CONFIG_SYSFS
dev->num_rx_queues = rxqs;
dev->real_num_rx_queues = rxqs;
if (netif_alloc_rx_queues(dev))
goto free_all;
#endif
strcpy(dev->name, name);
dev->name_assign_type = name_assign_type;
dev->group = INIT_NETDEV_GROUP;
if (!dev->ethtool_ops)
dev->ethtool_ops = &default_ethtool_ops;
nf_hook_ingress_init(dev);
return dev;
free_all:
free_netdev(dev);
return NULL;
free_pcpu:
free_percpu(dev->pcpu_refcnt);
free_dev:
netdev_freemem(dev);
return NULL;
}
EXPORT_SYMBOL(alloc_netdev_mqs);
/**
* free_netdev - free network device
* @dev: device
*
* This function does the last stage of destroying an allocated device
* interface. The reference to the device object is released. If this
* is the last reference then it will be freed.Must be called in process
* context.
*/
void free_netdev(struct net_device *dev)
{
struct napi_struct *p, *n;
struct bpf_prog *prog;
might_sleep();
netif_free_tx_queues(dev);
#ifdef CONFIG_SYSFS
kvfree(dev->_rx);
#endif
kfree(rcu_dereference_protected(dev->ingress_queue, 1));
/* Flush device addresses */
dev_addr_flush(dev);
list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
netif_napi_del(p);
free_percpu(dev->pcpu_refcnt);
dev->pcpu_refcnt = NULL;
prog = rcu_dereference_protected(dev->xdp_prog, 1);
if (prog) {
bpf_prog_put(prog);
static_key_slow_dec(&generic_xdp_needed);
}
/* Compatibility with error handling in drivers */
if (dev->reg_state == NETREG_UNINITIALIZED) {
netdev_freemem(dev);
return;
}
BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
dev->reg_state = NETREG_RELEASED;
/* will free via device release */
put_device(&dev->dev);
}
EXPORT_SYMBOL(free_netdev);
/**
* synchronize_net - Synchronize with packet receive processing
*
* Wait for packets currently being received to be done.
* Does not block later packets from starting.
*/
void synchronize_net(void)
{
might_sleep();
if (rtnl_is_locked())
synchronize_rcu_expedited();
else
synchronize_rcu();
}
EXPORT_SYMBOL(synchronize_net);
/**
* unregister_netdevice_queue - remove device from the kernel
* @dev: device
* @head: list
*
* This function shuts down a device interface and removes it
* from the kernel tables.
* If head not NULL, device is queued to be unregistered later.
*
* Callers must hold the rtnl semaphore. You may want
* unregister_netdev() instead of this.
*/
void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
{
ASSERT_RTNL();
if (head) {
list_move_tail(&dev->unreg_list, head);
} else {
rollback_registered(dev);
/* Finish processing unregister after unlock */
net_set_todo(dev);
}
}
EXPORT_SYMBOL(unregister_netdevice_queue);
/**
* unregister_netdevice_many - unregister many devices
* @head: list of devices
*
* Note: As most callers use a stack allocated list_head,
* we force a list_del() to make sure stack wont be corrupted later.
*/
void unregister_netdevice_many(struct list_head *head)
{
struct net_device *dev;
if (!list_empty(head)) {
rollback_registered_many(head);
list_for_each_entry(dev, head, unreg_list)
net_set_todo(dev);
list_del(head);
}
}
EXPORT_SYMBOL(unregister_netdevice_many);
/**
* unregister_netdev - remove device from the kernel
* @dev: device
*
* This function shuts down a device interface and removes it
* from the kernel tables.
*
* This is just a wrapper for unregister_netdevice that takes
* the rtnl semaphore. In general you want to use this and not
* unregister_netdevice.
*/
void unregister_netdev(struct net_device *dev)
{
rtnl_lock();
unregister_netdevice(dev);
rtnl_unlock();
}
EXPORT_SYMBOL(unregister_netdev);
/**
* dev_change_net_namespace - move device to different nethost namespace
* @dev: device
* @net: network namespace
* @pat: If not NULL name pattern to try if the current device name
* is already taken in the destination network namespace.
*
* This function shuts down a device interface and moves it
* to a new network namespace. On success 0 is returned, on
* a failure a netagive errno code is returned.
*
* Callers must hold the rtnl semaphore.
*/
int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
{
int err;
ASSERT_RTNL();
/* Don't allow namespace local devices to be moved. */
err = -EINVAL;
if (dev->features & NETIF_F_NETNS_LOCAL)
goto out;
/* Ensure the device has been registrered */
if (dev->reg_state != NETREG_REGISTERED)
goto out;
/* Get out if there is nothing todo */
err = 0;
if (net_eq(dev_net(dev), net))
goto out;
/* Pick the destination device name, and ensure
* we can use it in the destination network namespace.
*/
err = -EEXIST;
if (__dev_get_by_name(net, dev->name)) {
/* We get here if we can't use the current device name */
if (!pat)
goto out;
if (dev_get_valid_name(net, dev, pat) < 0)
goto out;
}
/*
* And now a mini version of register_netdevice unregister_netdevice.
*/
/* If device is running close it first. */
dev_close(dev);
/* And unlink it from device chain */
err = -ENODEV;
unlist_netdevice(dev);
synchronize_net();
/* Shutdown queueing discipline. */
dev_shutdown(dev);
/* Notify protocols, that we are about to destroy
* this device. They should clean all the things.
*
* Note that dev->reg_state stays at NETREG_REGISTERED.
* This is wanted because this way 8021q and macvlan know
* the device is just moving and can keep their slaves up.
*/
call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
rcu_barrier();
call_netdevice_notifiers(NETDEV_UNREGISTER_FINAL, dev);
rtmsg_ifinfo(RTM_DELLINK, dev, ~0U, GFP_KERNEL);
/*
* Flush the unicast and multicast chains
*/
dev_uc_flush(dev);
dev_mc_flush(dev);
/* Send a netdev-removed uevent to the old namespace */
kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
netdev_adjacent_del_links(dev);
/* Actually switch the network namespace */
dev_net_set(dev, net);
/* If there is an ifindex conflict assign a new one */
if (__dev_get_by_index(net, dev->ifindex))
dev->ifindex = dev_new_index(net);
/* Send a netdev-add uevent to the new namespace */
kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
netdev_adjacent_add_links(dev);
/* Fixup kobjects */
err = device_rename(&dev->dev, dev->name);
WARN_ON(err);
/* Add the device back in the hashes */
list_netdevice(dev);
/* Notify protocols, that a new device appeared. */
call_netdevice_notifiers(NETDEV_REGISTER, dev);
/*
* Prevent userspace races by waiting until the network
* device is fully setup before sending notifications.
*/
rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
synchronize_net();
err = 0;
out:
return err;
}
EXPORT_SYMBOL_GPL(dev_change_net_namespace);
static int dev_cpu_dead(unsigned int oldcpu)
{
struct sk_buff **list_skb;
struct sk_buff *skb;
unsigned int cpu;
struct softnet_data *sd, *oldsd, *remsd = NULL;
local_irq_disable();
cpu = smp_processor_id();
sd = &per_cpu(softnet_data, cpu);
oldsd = &per_cpu(softnet_data, oldcpu);
/* Find end of our completion_queue. */
list_skb = &sd->completion_queue;
while (*list_skb)
list_skb = &(*list_skb)->next;
/* Append completion queue from offline CPU. */
*list_skb = oldsd->completion_queue;
oldsd->completion_queue = NULL;
/* Append output queue from offline CPU. */
if (oldsd->output_queue) {
*sd->output_queue_tailp = oldsd->output_queue;
sd->output_queue_tailp = oldsd->output_queue_tailp;
oldsd->output_queue = NULL;
oldsd->output_queue_tailp = &oldsd->output_queue;
}
/* Append NAPI poll list from offline CPU, with one exception :
* process_backlog() must be called by cpu owning percpu backlog.
* We properly handle process_queue & input_pkt_queue later.
*/
while (!list_empty(&oldsd->poll_list)) {
struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
struct napi_struct,
poll_list);
list_del_init(&napi->poll_list);
if (napi->poll == process_backlog)
napi->state = 0;
else
____napi_schedule(sd, napi);
}
raise_softirq_irqoff(NET_TX_SOFTIRQ);
local_irq_enable();
#ifdef CONFIG_RPS
remsd = oldsd->rps_ipi_list;
oldsd->rps_ipi_list = NULL;
#endif
/* send out pending IPI's on offline CPU */
net_rps_send_ipi(remsd);
/* Process offline CPU's input_pkt_queue */
while ((skb = __skb_dequeue(&oldsd->process_queue))) {
netif_rx_ni(skb);
input_queue_head_incr(oldsd);
}
while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
netif_rx_ni(skb);
input_queue_head_incr(oldsd);
}
return 0;
}
/**
* netdev_increment_features - increment feature set by one
* @all: current feature set
* @one: new feature set
* @mask: mask feature set
*
* Computes a new feature set after adding a device with feature set
* @one to the master device with current feature set @all. Will not
* enable anything that is off in @mask. Returns the new feature set.
*/
netdev_features_t netdev_increment_features(netdev_features_t all,
netdev_features_t one, netdev_features_t mask)
{
if (mask & NETIF_F_HW_CSUM)
mask |= NETIF_F_CSUM_MASK;
mask |= NETIF_F_VLAN_CHALLENGED;
all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
all &= one | ~NETIF_F_ALL_FOR_ALL;
/* If one device supports hw checksumming, set for all. */
if (all & NETIF_F_HW_CSUM)
all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
return all;
}
EXPORT_SYMBOL(netdev_increment_features);
static struct hlist_head * __net_init netdev_create_hash(void)
{
int i;
struct hlist_head *hash;
hash = kmalloc(sizeof(*hash) * NETDEV_HASHENTRIES, GFP_KERNEL);
if (hash != NULL)
for (i = 0; i < NETDEV_HASHENTRIES; i++)
INIT_HLIST_HEAD(&hash[i]);
return hash;
}
/* Initialize per network namespace state */
static int __net_init netdev_init(struct net *net)
{
if (net != &init_net)
INIT_LIST_HEAD(&net->dev_base_head);
net->dev_name_head = netdev_create_hash();
if (net->dev_name_head == NULL)
goto err_name;
net->dev_index_head = netdev_create_hash();
if (net->dev_index_head == NULL)
goto err_idx;
return 0;
err_idx:
kfree(net->dev_name_head);
err_name:
return -ENOMEM;
}
/**
* netdev_drivername - network driver for the device
* @dev: network device
*
* Determine network driver for device.
*/
const char *netdev_drivername(const struct net_device *dev)
{
const struct device_driver *driver;
const struct device *parent;
const char *empty = "";
parent = dev->dev.parent;
if (!parent)
return empty;
driver = parent->driver;
if (driver && driver->name)
return driver->name;
return empty;
}
static void __netdev_printk(const char *level, const struct net_device *dev,
struct va_format *vaf)
{
if (dev && dev->dev.parent) {
dev_printk_emit(level[1] - '0',
dev->dev.parent,
"%s %s %s%s: %pV",
dev_driver_string(dev->dev.parent),
dev_name(dev->dev.parent),
netdev_name(dev), netdev_reg_state(dev),
vaf);
} else if (dev) {
printk("%s%s%s: %pV",
level, netdev_name(dev), netdev_reg_state(dev), vaf);
} else {
printk("%s(NULL net_device): %pV", level, vaf);
}
}
void netdev_printk(const char *level, const struct net_device *dev,
const char *format, ...)
{
struct va_format vaf;
va_list args;
va_start(args, format);
vaf.fmt = format;
vaf.va = &args;
__netdev_printk(level, dev, &vaf);
va_end(args);
}
EXPORT_SYMBOL(netdev_printk);
#define define_netdev_printk_level(func, level) \
void func(const struct net_device *dev, const char *fmt, ...) \
{ \
struct va_format vaf; \
va_list args; \
\
va_start(args, fmt); \
\
vaf.fmt = fmt; \
vaf.va = &args; \
\
__netdev_printk(level, dev, &vaf); \
\
va_end(args); \
} \
EXPORT_SYMBOL(func);
define_netdev_printk_level(netdev_emerg, KERN_EMERG);
define_netdev_printk_level(netdev_alert, KERN_ALERT);
define_netdev_printk_level(netdev_crit, KERN_CRIT);
define_netdev_printk_level(netdev_err, KERN_ERR);
define_netdev_printk_level(netdev_warn, KERN_WARNING);
define_netdev_printk_level(netdev_notice, KERN_NOTICE);
define_netdev_printk_level(netdev_info, KERN_INFO);
static void __net_exit netdev_exit(struct net *net)
{
kfree(net->dev_name_head);
kfree(net->dev_index_head);
}
static struct pernet_operations __net_initdata netdev_net_ops = {
.init = netdev_init,
.exit = netdev_exit,
};
static void __net_exit default_device_exit(struct net *net)
{
struct net_device *dev, *aux;
/*
* Push all migratable network devices back to the
* initial network namespace
*/
rtnl_lock();
for_each_netdev_safe(net, dev, aux) {
int err;
char fb_name[IFNAMSIZ];
/* Ignore unmoveable devices (i.e. loopback) */
if (dev->features & NETIF_F_NETNS_LOCAL)
continue;
/* Leave virtual devices for the generic cleanup */
if (dev->rtnl_link_ops)
continue;
/* Push remaining network devices to init_net */
snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
err = dev_change_net_namespace(dev, &init_net, fb_name);
if (err) {
pr_emerg("%s: failed to move %s to init_net: %d\n",
__func__, dev->name, err);
BUG();
}
}
rtnl_unlock();
}
static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
{
/* Return with the rtnl_lock held when there are no network
* devices unregistering in any network namespace in net_list.
*/
struct net *net;
bool unregistering;
DEFINE_WAIT_FUNC(wait, woken_wake_function);
add_wait_queue(&netdev_unregistering_wq, &wait);
for (;;) {
unregistering = false;
rtnl_lock();
list_for_each_entry(net, net_list, exit_list) {
if (net->dev_unreg_count > 0) {
unregistering = true;
break;
}
}
if (!unregistering)
break;
__rtnl_unlock();
wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
}
remove_wait_queue(&netdev_unregistering_wq, &wait);
}
static void __net_exit default_device_exit_batch(struct list_head *net_list)
{
/* At exit all network devices most be removed from a network
* namespace. Do this in the reverse order of registration.
* Do this across as many network namespaces as possible to
* improve batching efficiency.
*/
struct net_device *dev;
struct net *net;
LIST_HEAD(dev_kill_list);
/* To prevent network device cleanup code from dereferencing
* loopback devices or network devices that have been freed
* wait here for all pending unregistrations to complete,
* before unregistring the loopback device and allowing the
* network namespace be freed.
*
* The netdev todo list containing all network devices
* unregistrations that happen in default_device_exit_batch
* will run in the rtnl_unlock() at the end of
* default_device_exit_batch.
*/
rtnl_lock_unregistering(net_list);
list_for_each_entry(net, net_list, exit_list) {
for_each_netdev_reverse(net, dev) {
if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
else
unregister_netdevice_queue(dev, &dev_kill_list);
}
}
unregister_netdevice_many(&dev_kill_list);
rtnl_unlock();
}
static struct pernet_operations __net_initdata default_device_ops = {
.exit = default_device_exit,
.exit_batch = default_device_exit_batch,
};
/*
* Initialize the DEV module. At boot time this walks the device list and
* unhooks any devices that fail to initialise (normally hardware not
* present) and leaves us with a valid list of present and active devices.
*
*/
/*
* This is called single threaded during boot, so no need
* to take the rtnl semaphore.
*/
static int __init net_dev_init(void)
{
int i, rc = -ENOMEM;
BUG_ON(!dev_boot_phase);
if (dev_proc_init())
goto out;
if (netdev_kobject_init())
goto out;
INIT_LIST_HEAD(&ptype_all);
for (i = 0; i < PTYPE_HASH_SIZE; i++)
INIT_LIST_HEAD(&ptype_base[i]);
INIT_LIST_HEAD(&offload_base);
if (register_pernet_subsys(&netdev_net_ops))
goto out;
/*
* Initialise the packet receive queues.
*/
for_each_possible_cpu(i) {
struct work_struct *flush = per_cpu_ptr(&flush_works, i);
struct softnet_data *sd = &per_cpu(softnet_data, i);
INIT_WORK(flush, flush_backlog);
skb_queue_head_init(&sd->input_pkt_queue);
skb_queue_head_init(&sd->process_queue);
INIT_LIST_HEAD(&sd->poll_list);
sd->output_queue_tailp = &sd->output_queue;
#ifdef CONFIG_RPS
sd->csd.func = rps_trigger_softirq;
sd->csd.info = sd;
sd->cpu = i;
#endif
sd->backlog.poll = process_backlog;
sd->backlog.weight = weight_p;
}
dev_boot_phase = 0;
/* The loopback device is special if any other network devices
* is present in a network namespace the loopback device must
* be present. Since we now dynamically allocate and free the
* loopback device ensure this invariant is maintained by
* keeping the loopback device as the first device on the
* list of network devices. Ensuring the loopback devices
* is the first device that appears and the last network device
* that disappears.
*/
if (register_pernet_device(&loopback_net_ops))
goto out;
if (register_pernet_device(&default_device_ops))
goto out;
open_softirq(NET_TX_SOFTIRQ, net_tx_action);
open_softirq(NET_RX_SOFTIRQ, net_rx_action);
rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
NULL, dev_cpu_dead);
WARN_ON(rc < 0);
rc = 0;
out:
return rc;
}
subsys_initcall(net_dev_init);
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_623_2 |
crossvul-cpp_data_good_3000_0 | /*
* i8042 keyboard and mouse controller driver for Linux
*
* Copyright (c) 1999-2004 Vojtech Pavlik
*/
/*
* 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/serio.h>
#include <linux/err.h>
#include <linux/rcupdate.h>
#include <linux/platform_device.h>
#include <linux/i8042.h>
#include <linux/slab.h>
#include <linux/suspend.h>
#include <asm/io.h>
MODULE_AUTHOR("Vojtech Pavlik <vojtech@suse.cz>");
MODULE_DESCRIPTION("i8042 keyboard and mouse controller driver");
MODULE_LICENSE("GPL");
static bool i8042_nokbd;
module_param_named(nokbd, i8042_nokbd, bool, 0);
MODULE_PARM_DESC(nokbd, "Do not probe or use KBD port.");
static bool i8042_noaux;
module_param_named(noaux, i8042_noaux, bool, 0);
MODULE_PARM_DESC(noaux, "Do not probe or use AUX (mouse) port.");
static bool i8042_nomux;
module_param_named(nomux, i8042_nomux, bool, 0);
MODULE_PARM_DESC(nomux, "Do not check whether an active multiplexing controller is present.");
static bool i8042_unlock;
module_param_named(unlock, i8042_unlock, bool, 0);
MODULE_PARM_DESC(unlock, "Ignore keyboard lock.");
enum i8042_controller_reset_mode {
I8042_RESET_NEVER,
I8042_RESET_ALWAYS,
I8042_RESET_ON_S2RAM,
#define I8042_RESET_DEFAULT I8042_RESET_ON_S2RAM
};
static enum i8042_controller_reset_mode i8042_reset = I8042_RESET_DEFAULT;
static int i8042_set_reset(const char *val, const struct kernel_param *kp)
{
enum i8042_controller_reset_mode *arg = kp->arg;
int error;
bool reset;
if (val) {
error = kstrtobool(val, &reset);
if (error)
return error;
} else {
reset = true;
}
*arg = reset ? I8042_RESET_ALWAYS : I8042_RESET_NEVER;
return 0;
}
static const struct kernel_param_ops param_ops_reset_param = {
.flags = KERNEL_PARAM_OPS_FL_NOARG,
.set = i8042_set_reset,
};
#define param_check_reset_param(name, p) \
__param_check(name, p, enum i8042_controller_reset_mode)
module_param_named(reset, i8042_reset, reset_param, 0);
MODULE_PARM_DESC(reset, "Reset controller on resume, cleanup or both");
static bool i8042_direct;
module_param_named(direct, i8042_direct, bool, 0);
MODULE_PARM_DESC(direct, "Put keyboard port into non-translated mode.");
static bool i8042_dumbkbd;
module_param_named(dumbkbd, i8042_dumbkbd, bool, 0);
MODULE_PARM_DESC(dumbkbd, "Pretend that controller can only read data from keyboard");
static bool i8042_noloop;
module_param_named(noloop, i8042_noloop, bool, 0);
MODULE_PARM_DESC(noloop, "Disable the AUX Loopback command while probing for the AUX port");
static bool i8042_notimeout;
module_param_named(notimeout, i8042_notimeout, bool, 0);
MODULE_PARM_DESC(notimeout, "Ignore timeouts signalled by i8042");
static bool i8042_kbdreset;
module_param_named(kbdreset, i8042_kbdreset, bool, 0);
MODULE_PARM_DESC(kbdreset, "Reset device connected to KBD port");
#ifdef CONFIG_X86
static bool i8042_dritek;
module_param_named(dritek, i8042_dritek, bool, 0);
MODULE_PARM_DESC(dritek, "Force enable the Dritek keyboard extension");
#endif
#ifdef CONFIG_PNP
static bool i8042_nopnp;
module_param_named(nopnp, i8042_nopnp, bool, 0);
MODULE_PARM_DESC(nopnp, "Do not use PNP to detect controller settings");
#endif
#define DEBUG
#ifdef DEBUG
static bool i8042_debug;
module_param_named(debug, i8042_debug, bool, 0600);
MODULE_PARM_DESC(debug, "Turn i8042 debugging mode on and off");
static bool i8042_unmask_kbd_data;
module_param_named(unmask_kbd_data, i8042_unmask_kbd_data, bool, 0600);
MODULE_PARM_DESC(unmask_kbd_data, "Unconditional enable (may reveal sensitive data) of normally sanitize-filtered kbd data traffic debug log [pre-condition: i8042.debug=1 enabled]");
#endif
static bool i8042_bypass_aux_irq_test;
static char i8042_kbd_firmware_id[128];
static char i8042_aux_firmware_id[128];
#include "i8042.h"
/*
* i8042_lock protects serialization between i8042_command and
* the interrupt handler.
*/
static DEFINE_SPINLOCK(i8042_lock);
/*
* Writers to AUX and KBD ports as well as users issuing i8042_command
* directly should acquire i8042_mutex (by means of calling
* i8042_lock_chip() and i8042_unlock_ship() helpers) to ensure that
* they do not disturb each other (unfortunately in many i8042
* implementations write to one of the ports will immediately abort
* command that is being processed by another port).
*/
static DEFINE_MUTEX(i8042_mutex);
struct i8042_port {
struct serio *serio;
int irq;
bool exists;
bool driver_bound;
signed char mux;
};
#define I8042_KBD_PORT_NO 0
#define I8042_AUX_PORT_NO 1
#define I8042_MUX_PORT_NO 2
#define I8042_NUM_PORTS (I8042_NUM_MUX_PORTS + 2)
static struct i8042_port i8042_ports[I8042_NUM_PORTS];
static unsigned char i8042_initial_ctr;
static unsigned char i8042_ctr;
static bool i8042_mux_present;
static bool i8042_kbd_irq_registered;
static bool i8042_aux_irq_registered;
static unsigned char i8042_suppress_kbd_ack;
static struct platform_device *i8042_platform_device;
static struct notifier_block i8042_kbd_bind_notifier_block;
static irqreturn_t i8042_interrupt(int irq, void *dev_id);
static bool (*i8042_platform_filter)(unsigned char data, unsigned char str,
struct serio *serio);
void i8042_lock_chip(void)
{
mutex_lock(&i8042_mutex);
}
EXPORT_SYMBOL(i8042_lock_chip);
void i8042_unlock_chip(void)
{
mutex_unlock(&i8042_mutex);
}
EXPORT_SYMBOL(i8042_unlock_chip);
int i8042_install_filter(bool (*filter)(unsigned char data, unsigned char str,
struct serio *serio))
{
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&i8042_lock, flags);
if (i8042_platform_filter) {
ret = -EBUSY;
goto out;
}
i8042_platform_filter = filter;
out:
spin_unlock_irqrestore(&i8042_lock, flags);
return ret;
}
EXPORT_SYMBOL(i8042_install_filter);
int i8042_remove_filter(bool (*filter)(unsigned char data, unsigned char str,
struct serio *port))
{
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&i8042_lock, flags);
if (i8042_platform_filter != filter) {
ret = -EINVAL;
goto out;
}
i8042_platform_filter = NULL;
out:
spin_unlock_irqrestore(&i8042_lock, flags);
return ret;
}
EXPORT_SYMBOL(i8042_remove_filter);
/*
* The i8042_wait_read() and i8042_wait_write functions wait for the i8042 to
* be ready for reading values from it / writing values to it.
* Called always with i8042_lock held.
*/
static int i8042_wait_read(void)
{
int i = 0;
while ((~i8042_read_status() & I8042_STR_OBF) && (i < I8042_CTL_TIMEOUT)) {
udelay(50);
i++;
}
return -(i == I8042_CTL_TIMEOUT);
}
static int i8042_wait_write(void)
{
int i = 0;
while ((i8042_read_status() & I8042_STR_IBF) && (i < I8042_CTL_TIMEOUT)) {
udelay(50);
i++;
}
return -(i == I8042_CTL_TIMEOUT);
}
/*
* i8042_flush() flushes all data that may be in the keyboard and mouse buffers
* of the i8042 down the toilet.
*/
static int i8042_flush(void)
{
unsigned long flags;
unsigned char data, str;
int count = 0;
int retval = 0;
spin_lock_irqsave(&i8042_lock, flags);
while ((str = i8042_read_status()) & I8042_STR_OBF) {
if (count++ < I8042_BUFFER_SIZE) {
udelay(50);
data = i8042_read_data();
dbg("%02x <- i8042 (flush, %s)\n",
data, str & I8042_STR_AUXDATA ? "aux" : "kbd");
} else {
retval = -EIO;
break;
}
}
spin_unlock_irqrestore(&i8042_lock, flags);
return retval;
}
/*
* i8042_command() executes a command on the i8042. It also sends the input
* parameter(s) of the commands to it, and receives the output value(s). The
* parameters are to be stored in the param array, and the output is placed
* into the same array. The number of the parameters and output values is
* encoded in bits 8-11 of the command number.
*/
static int __i8042_command(unsigned char *param, int command)
{
int i, error;
if (i8042_noloop && command == I8042_CMD_AUX_LOOP)
return -1;
error = i8042_wait_write();
if (error)
return error;
dbg("%02x -> i8042 (command)\n", command & 0xff);
i8042_write_command(command & 0xff);
for (i = 0; i < ((command >> 12) & 0xf); i++) {
error = i8042_wait_write();
if (error) {
dbg(" -- i8042 (wait write timeout)\n");
return error;
}
dbg("%02x -> i8042 (parameter)\n", param[i]);
i8042_write_data(param[i]);
}
for (i = 0; i < ((command >> 8) & 0xf); i++) {
error = i8042_wait_read();
if (error) {
dbg(" -- i8042 (wait read timeout)\n");
return error;
}
if (command == I8042_CMD_AUX_LOOP &&
!(i8042_read_status() & I8042_STR_AUXDATA)) {
dbg(" -- i8042 (auxerr)\n");
return -1;
}
param[i] = i8042_read_data();
dbg("%02x <- i8042 (return)\n", param[i]);
}
return 0;
}
int i8042_command(unsigned char *param, int command)
{
unsigned long flags;
int retval;
spin_lock_irqsave(&i8042_lock, flags);
retval = __i8042_command(param, command);
spin_unlock_irqrestore(&i8042_lock, flags);
return retval;
}
EXPORT_SYMBOL(i8042_command);
/*
* i8042_kbd_write() sends a byte out through the keyboard interface.
*/
static int i8042_kbd_write(struct serio *port, unsigned char c)
{
unsigned long flags;
int retval = 0;
spin_lock_irqsave(&i8042_lock, flags);
if (!(retval = i8042_wait_write())) {
dbg("%02x -> i8042 (kbd-data)\n", c);
i8042_write_data(c);
}
spin_unlock_irqrestore(&i8042_lock, flags);
return retval;
}
/*
* i8042_aux_write() sends a byte out through the aux interface.
*/
static int i8042_aux_write(struct serio *serio, unsigned char c)
{
struct i8042_port *port = serio->port_data;
return i8042_command(&c, port->mux == -1 ?
I8042_CMD_AUX_SEND :
I8042_CMD_MUX_SEND + port->mux);
}
/*
* i8042_port_close attempts to clear AUX or KBD port state by disabling
* and then re-enabling it.
*/
static void i8042_port_close(struct serio *serio)
{
int irq_bit;
int disable_bit;
const char *port_name;
if (serio == i8042_ports[I8042_AUX_PORT_NO].serio) {
irq_bit = I8042_CTR_AUXINT;
disable_bit = I8042_CTR_AUXDIS;
port_name = "AUX";
} else {
irq_bit = I8042_CTR_KBDINT;
disable_bit = I8042_CTR_KBDDIS;
port_name = "KBD";
}
i8042_ctr &= ~irq_bit;
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR))
pr_warn("Can't write CTR while closing %s port\n", port_name);
udelay(50);
i8042_ctr &= ~disable_bit;
i8042_ctr |= irq_bit;
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR))
pr_err("Can't reactivate %s port\n", port_name);
/*
* See if there is any data appeared while we were messing with
* port state.
*/
i8042_interrupt(0, NULL);
}
/*
* i8042_start() is called by serio core when port is about to finish
* registering. It will mark port as existing so i8042_interrupt can
* start sending data through it.
*/
static int i8042_start(struct serio *serio)
{
struct i8042_port *port = serio->port_data;
spin_lock_irq(&i8042_lock);
port->exists = true;
spin_unlock_irq(&i8042_lock);
return 0;
}
/*
* i8042_stop() marks serio port as non-existing so i8042_interrupt
* will not try to send data to the port that is about to go away.
* The function is called by serio core as part of unregister procedure.
*/
static void i8042_stop(struct serio *serio)
{
struct i8042_port *port = serio->port_data;
spin_lock_irq(&i8042_lock);
port->exists = false;
port->serio = NULL;
spin_unlock_irq(&i8042_lock);
/*
* We need to make sure that interrupt handler finishes using
* our serio port before we return from this function.
* We synchronize with both AUX and KBD IRQs because there is
* a (very unlikely) chance that AUX IRQ is raised for KBD port
* and vice versa.
*/
synchronize_irq(I8042_AUX_IRQ);
synchronize_irq(I8042_KBD_IRQ);
}
/*
* i8042_filter() filters out unwanted bytes from the input data stream.
* It is called from i8042_interrupt and thus is running with interrupts
* off and i8042_lock held.
*/
static bool i8042_filter(unsigned char data, unsigned char str,
struct serio *serio)
{
if (unlikely(i8042_suppress_kbd_ack)) {
if ((~str & I8042_STR_AUXDATA) &&
(data == 0xfa || data == 0xfe)) {
i8042_suppress_kbd_ack--;
dbg("Extra keyboard ACK - filtered out\n");
return true;
}
}
if (i8042_platform_filter && i8042_platform_filter(data, str, serio)) {
dbg("Filtered out by platform filter\n");
return true;
}
return false;
}
/*
* i8042_interrupt() is the most important function in this driver -
* it handles the interrupts from the i8042, and sends incoming bytes
* to the upper layers.
*/
static irqreturn_t i8042_interrupt(int irq, void *dev_id)
{
struct i8042_port *port;
struct serio *serio;
unsigned long flags;
unsigned char str, data;
unsigned int dfl;
unsigned int port_no;
bool filtered;
int ret = 1;
spin_lock_irqsave(&i8042_lock, flags);
str = i8042_read_status();
if (unlikely(~str & I8042_STR_OBF)) {
spin_unlock_irqrestore(&i8042_lock, flags);
if (irq)
dbg("Interrupt %d, without any data\n", irq);
ret = 0;
goto out;
}
data = i8042_read_data();
if (i8042_mux_present && (str & I8042_STR_AUXDATA)) {
static unsigned long last_transmit;
static unsigned char last_str;
dfl = 0;
if (str & I8042_STR_MUXERR) {
dbg("MUX error, status is %02x, data is %02x\n",
str, data);
/*
* When MUXERR condition is signalled the data register can only contain
* 0xfd, 0xfe or 0xff if implementation follows the spec. Unfortunately
* it is not always the case. Some KBCs also report 0xfc when there is
* nothing connected to the port while others sometimes get confused which
* port the data came from and signal error leaving the data intact. They
* _do not_ revert to legacy mode (actually I've never seen KBC reverting
* to legacy mode yet, when we see one we'll add proper handling).
* Anyway, we process 0xfc, 0xfd, 0xfe and 0xff as timeouts, and for the
* rest assume that the data came from the same serio last byte
* was transmitted (if transmission happened not too long ago).
*/
switch (data) {
default:
if (time_before(jiffies, last_transmit + HZ/10)) {
str = last_str;
break;
}
/* fall through - report timeout */
case 0xfc:
case 0xfd:
case 0xfe: dfl = SERIO_TIMEOUT; data = 0xfe; break;
case 0xff: dfl = SERIO_PARITY; data = 0xfe; break;
}
}
port_no = I8042_MUX_PORT_NO + ((str >> 6) & 3);
last_str = str;
last_transmit = jiffies;
} else {
dfl = ((str & I8042_STR_PARITY) ? SERIO_PARITY : 0) |
((str & I8042_STR_TIMEOUT && !i8042_notimeout) ? SERIO_TIMEOUT : 0);
port_no = (str & I8042_STR_AUXDATA) ?
I8042_AUX_PORT_NO : I8042_KBD_PORT_NO;
}
port = &i8042_ports[port_no];
serio = port->exists ? port->serio : NULL;
filter_dbg(port->driver_bound, data, "<- i8042 (interrupt, %d, %d%s%s)\n",
port_no, irq,
dfl & SERIO_PARITY ? ", bad parity" : "",
dfl & SERIO_TIMEOUT ? ", timeout" : "");
filtered = i8042_filter(data, str, serio);
spin_unlock_irqrestore(&i8042_lock, flags);
if (likely(serio && !filtered))
serio_interrupt(serio, data, dfl);
out:
return IRQ_RETVAL(ret);
}
/*
* i8042_enable_kbd_port enables keyboard port on chip
*/
static int i8042_enable_kbd_port(void)
{
i8042_ctr &= ~I8042_CTR_KBDDIS;
i8042_ctr |= I8042_CTR_KBDINT;
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
i8042_ctr &= ~I8042_CTR_KBDINT;
i8042_ctr |= I8042_CTR_KBDDIS;
pr_err("Failed to enable KBD port\n");
return -EIO;
}
return 0;
}
/*
* i8042_enable_aux_port enables AUX (mouse) port on chip
*/
static int i8042_enable_aux_port(void)
{
i8042_ctr &= ~I8042_CTR_AUXDIS;
i8042_ctr |= I8042_CTR_AUXINT;
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
i8042_ctr &= ~I8042_CTR_AUXINT;
i8042_ctr |= I8042_CTR_AUXDIS;
pr_err("Failed to enable AUX port\n");
return -EIO;
}
return 0;
}
/*
* i8042_enable_mux_ports enables 4 individual AUX ports after
* the controller has been switched into Multiplexed mode
*/
static int i8042_enable_mux_ports(void)
{
unsigned char param;
int i;
for (i = 0; i < I8042_NUM_MUX_PORTS; i++) {
i8042_command(¶m, I8042_CMD_MUX_PFX + i);
i8042_command(¶m, I8042_CMD_AUX_ENABLE);
}
return i8042_enable_aux_port();
}
/*
* i8042_set_mux_mode checks whether the controller has an
* active multiplexor and puts the chip into Multiplexed (true)
* or Legacy (false) mode.
*/
static int i8042_set_mux_mode(bool multiplex, unsigned char *mux_version)
{
unsigned char param, val;
/*
* Get rid of bytes in the queue.
*/
i8042_flush();
/*
* Internal loopback test - send three bytes, they should come back from the
* mouse interface, the last should be version.
*/
param = val = 0xf0;
if (i8042_command(¶m, I8042_CMD_AUX_LOOP) || param != val)
return -1;
param = val = multiplex ? 0x56 : 0xf6;
if (i8042_command(¶m, I8042_CMD_AUX_LOOP) || param != val)
return -1;
param = val = multiplex ? 0xa4 : 0xa5;
if (i8042_command(¶m, I8042_CMD_AUX_LOOP) || param == val)
return -1;
/*
* Workaround for interference with USB Legacy emulation
* that causes a v10.12 MUX to be found.
*/
if (param == 0xac)
return -1;
if (mux_version)
*mux_version = param;
return 0;
}
/*
* i8042_check_mux() checks whether the controller supports the PS/2 Active
* Multiplexing specification by Synaptics, Phoenix, Insyde and
* LCS/Telegraphics.
*/
static int __init i8042_check_mux(void)
{
unsigned char mux_version;
if (i8042_set_mux_mode(true, &mux_version))
return -1;
pr_info("Detected active multiplexing controller, rev %d.%d\n",
(mux_version >> 4) & 0xf, mux_version & 0xf);
/*
* Disable all muxed ports by disabling AUX.
*/
i8042_ctr |= I8042_CTR_AUXDIS;
i8042_ctr &= ~I8042_CTR_AUXINT;
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
pr_err("Failed to disable AUX port, can't use MUX\n");
return -EIO;
}
i8042_mux_present = true;
return 0;
}
/*
* The following is used to test AUX IRQ delivery.
*/
static struct completion i8042_aux_irq_delivered __initdata;
static bool i8042_irq_being_tested __initdata;
static irqreturn_t __init i8042_aux_test_irq(int irq, void *dev_id)
{
unsigned long flags;
unsigned char str, data;
int ret = 0;
spin_lock_irqsave(&i8042_lock, flags);
str = i8042_read_status();
if (str & I8042_STR_OBF) {
data = i8042_read_data();
dbg("%02x <- i8042 (aux_test_irq, %s)\n",
data, str & I8042_STR_AUXDATA ? "aux" : "kbd");
if (i8042_irq_being_tested &&
data == 0xa5 && (str & I8042_STR_AUXDATA))
complete(&i8042_aux_irq_delivered);
ret = 1;
}
spin_unlock_irqrestore(&i8042_lock, flags);
return IRQ_RETVAL(ret);
}
/*
* i8042_toggle_aux - enables or disables AUX port on i8042 via command and
* verifies success by readinng CTR. Used when testing for presence of AUX
* port.
*/
static int __init i8042_toggle_aux(bool on)
{
unsigned char param;
int i;
if (i8042_command(¶m,
on ? I8042_CMD_AUX_ENABLE : I8042_CMD_AUX_DISABLE))
return -1;
/* some chips need some time to set the I8042_CTR_AUXDIS bit */
for (i = 0; i < 100; i++) {
udelay(50);
if (i8042_command(¶m, I8042_CMD_CTL_RCTR))
return -1;
if (!(param & I8042_CTR_AUXDIS) == on)
return 0;
}
return -1;
}
/*
* i8042_check_aux() applies as much paranoia as it can at detecting
* the presence of an AUX interface.
*/
static int __init i8042_check_aux(void)
{
int retval = -1;
bool irq_registered = false;
bool aux_loop_broken = false;
unsigned long flags;
unsigned char param;
/*
* Get rid of bytes in the queue.
*/
i8042_flush();
/*
* Internal loopback test - filters out AT-type i8042's. Unfortunately
* SiS screwed up and their 5597 doesn't support the LOOP command even
* though it has an AUX port.
*/
param = 0x5a;
retval = i8042_command(¶m, I8042_CMD_AUX_LOOP);
if (retval || param != 0x5a) {
/*
* External connection test - filters out AT-soldered PS/2 i8042's
* 0x00 - no error, 0x01-0x03 - clock/data stuck, 0xff - general error
* 0xfa - no error on some notebooks which ignore the spec
* Because it's common for chipsets to return error on perfectly functioning
* AUX ports, we test for this only when the LOOP command failed.
*/
if (i8042_command(¶m, I8042_CMD_AUX_TEST) ||
(param && param != 0xfa && param != 0xff))
return -1;
/*
* If AUX_LOOP completed without error but returned unexpected data
* mark it as broken
*/
if (!retval)
aux_loop_broken = true;
}
/*
* Bit assignment test - filters out PS/2 i8042's in AT mode
*/
if (i8042_toggle_aux(false)) {
pr_warn("Failed to disable AUX port, but continuing anyway... Is this a SiS?\n");
pr_warn("If AUX port is really absent please use the 'i8042.noaux' option\n");
}
if (i8042_toggle_aux(true))
return -1;
/*
* Reset keyboard (needed on some laptops to successfully detect
* touchpad, e.g., some Gigabyte laptop models with Elantech
* touchpads).
*/
if (i8042_kbdreset) {
pr_warn("Attempting to reset device connected to KBD port\n");
i8042_kbd_write(NULL, (unsigned char) 0xff);
}
/*
* Test AUX IRQ delivery to make sure BIOS did not grab the IRQ and
* used it for a PCI card or somethig else.
*/
if (i8042_noloop || i8042_bypass_aux_irq_test || aux_loop_broken) {
/*
* Without LOOP command we can't test AUX IRQ delivery. Assume the port
* is working and hope we are right.
*/
retval = 0;
goto out;
}
if (request_irq(I8042_AUX_IRQ, i8042_aux_test_irq, IRQF_SHARED,
"i8042", i8042_platform_device))
goto out;
irq_registered = true;
if (i8042_enable_aux_port())
goto out;
spin_lock_irqsave(&i8042_lock, flags);
init_completion(&i8042_aux_irq_delivered);
i8042_irq_being_tested = true;
param = 0xa5;
retval = __i8042_command(¶m, I8042_CMD_AUX_LOOP & 0xf0ff);
spin_unlock_irqrestore(&i8042_lock, flags);
if (retval)
goto out;
if (wait_for_completion_timeout(&i8042_aux_irq_delivered,
msecs_to_jiffies(250)) == 0) {
/*
* AUX IRQ was never delivered so we need to flush the controller to
* get rid of the byte we put there; otherwise keyboard may not work.
*/
dbg(" -- i8042 (aux irq test timeout)\n");
i8042_flush();
retval = -1;
}
out:
/*
* Disable the interface.
*/
i8042_ctr |= I8042_CTR_AUXDIS;
i8042_ctr &= ~I8042_CTR_AUXINT;
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR))
retval = -1;
if (irq_registered)
free_irq(I8042_AUX_IRQ, i8042_platform_device);
return retval;
}
static int i8042_controller_check(void)
{
if (i8042_flush()) {
pr_info("No controller found\n");
return -ENODEV;
}
return 0;
}
static int i8042_controller_selftest(void)
{
unsigned char param;
int i = 0;
/*
* We try this 5 times; on some really fragile systems this does not
* take the first time...
*/
do {
if (i8042_command(¶m, I8042_CMD_CTL_TEST)) {
pr_err("i8042 controller selftest timeout\n");
return -ENODEV;
}
if (param == I8042_RET_CTL_TEST)
return 0;
dbg("i8042 controller selftest: %#x != %#x\n",
param, I8042_RET_CTL_TEST);
msleep(50);
} while (i++ < 5);
#ifdef CONFIG_X86
/*
* On x86, we don't fail entire i8042 initialization if controller
* reset fails in hopes that keyboard port will still be functional
* and user will still get a working keyboard. This is especially
* important on netbooks. On other arches we trust hardware more.
*/
pr_info("giving up on controller selftest, continuing anyway...\n");
return 0;
#else
pr_err("i8042 controller selftest failed\n");
return -EIO;
#endif
}
/*
* i8042_controller init initializes the i8042 controller, and,
* most importantly, sets it into non-xlated mode if that's
* desired.
*/
static int i8042_controller_init(void)
{
unsigned long flags;
int n = 0;
unsigned char ctr[2];
/*
* Save the CTR for restore on unload / reboot.
*/
do {
if (n >= 10) {
pr_err("Unable to get stable CTR read\n");
return -EIO;
}
if (n != 0)
udelay(50);
if (i8042_command(&ctr[n++ % 2], I8042_CMD_CTL_RCTR)) {
pr_err("Can't read CTR while initializing i8042\n");
return -EIO;
}
} while (n < 2 || ctr[0] != ctr[1]);
i8042_initial_ctr = i8042_ctr = ctr[0];
/*
* Disable the keyboard interface and interrupt.
*/
i8042_ctr |= I8042_CTR_KBDDIS;
i8042_ctr &= ~I8042_CTR_KBDINT;
/*
* Handle keylock.
*/
spin_lock_irqsave(&i8042_lock, flags);
if (~i8042_read_status() & I8042_STR_KEYLOCK) {
if (i8042_unlock)
i8042_ctr |= I8042_CTR_IGNKEYLOCK;
else
pr_warn("Warning: Keylock active\n");
}
spin_unlock_irqrestore(&i8042_lock, flags);
/*
* If the chip is configured into nontranslated mode by the BIOS, don't
* bother enabling translating and be happy.
*/
if (~i8042_ctr & I8042_CTR_XLATE)
i8042_direct = true;
/*
* Set nontranslated mode for the kbd interface if requested by an option.
* After this the kbd interface becomes a simple serial in/out, like the aux
* interface is. We don't do this by default, since it can confuse notebook
* BIOSes.
*/
if (i8042_direct)
i8042_ctr &= ~I8042_CTR_XLATE;
/*
* Write CTR back.
*/
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
pr_err("Can't write CTR while initializing i8042\n");
return -EIO;
}
/*
* Flush whatever accumulated while we were disabling keyboard port.
*/
i8042_flush();
return 0;
}
/*
* Reset the controller and reset CRT to the original value set by BIOS.
*/
static void i8042_controller_reset(bool s2r_wants_reset)
{
i8042_flush();
/*
* Disable both KBD and AUX interfaces so they don't get in the way
*/
i8042_ctr |= I8042_CTR_KBDDIS | I8042_CTR_AUXDIS;
i8042_ctr &= ~(I8042_CTR_KBDINT | I8042_CTR_AUXINT);
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR))
pr_warn("Can't write CTR while resetting\n");
/*
* Disable MUX mode if present.
*/
if (i8042_mux_present)
i8042_set_mux_mode(false, NULL);
/*
* Reset the controller if requested.
*/
if (i8042_reset == I8042_RESET_ALWAYS ||
(i8042_reset == I8042_RESET_ON_S2RAM && s2r_wants_reset)) {
i8042_controller_selftest();
}
/*
* Restore the original control register setting.
*/
if (i8042_command(&i8042_initial_ctr, I8042_CMD_CTL_WCTR))
pr_warn("Can't restore CTR\n");
}
/*
* i8042_panic_blink() will turn the keyboard LEDs on or off and is called
* when kernel panics. Flashing LEDs is useful for users running X who may
* not see the console and will help distinguishing panics from "real"
* lockups.
*
* Note that DELAY has a limit of 10ms so we will not get stuck here
* waiting for KBC to free up even if KBD interrupt is off
*/
#define DELAY do { mdelay(1); if (++delay > 10) return delay; } while(0)
static long i8042_panic_blink(int state)
{
long delay = 0;
char led;
led = (state) ? 0x01 | 0x04 : 0;
while (i8042_read_status() & I8042_STR_IBF)
DELAY;
dbg("%02x -> i8042 (panic blink)\n", 0xed);
i8042_suppress_kbd_ack = 2;
i8042_write_data(0xed); /* set leds */
DELAY;
while (i8042_read_status() & I8042_STR_IBF)
DELAY;
DELAY;
dbg("%02x -> i8042 (panic blink)\n", led);
i8042_write_data(led);
DELAY;
return delay;
}
#undef DELAY
#ifdef CONFIG_X86
static void i8042_dritek_enable(void)
{
unsigned char param = 0x90;
int error;
error = i8042_command(¶m, 0x1059);
if (error)
pr_warn("Failed to enable DRITEK extension: %d\n", error);
}
#endif
#ifdef CONFIG_PM
/*
* Here we try to reset everything back to a state we had
* before suspending.
*/
static int i8042_controller_resume(bool s2r_wants_reset)
{
int error;
error = i8042_controller_check();
if (error)
return error;
if (i8042_reset == I8042_RESET_ALWAYS ||
(i8042_reset == I8042_RESET_ON_S2RAM && s2r_wants_reset)) {
error = i8042_controller_selftest();
if (error)
return error;
}
/*
* Restore original CTR value and disable all ports
*/
i8042_ctr = i8042_initial_ctr;
if (i8042_direct)
i8042_ctr &= ~I8042_CTR_XLATE;
i8042_ctr |= I8042_CTR_AUXDIS | I8042_CTR_KBDDIS;
i8042_ctr &= ~(I8042_CTR_AUXINT | I8042_CTR_KBDINT);
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
pr_warn("Can't write CTR to resume, retrying...\n");
msleep(50);
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
pr_err("CTR write retry failed\n");
return -EIO;
}
}
#ifdef CONFIG_X86
if (i8042_dritek)
i8042_dritek_enable();
#endif
if (i8042_mux_present) {
if (i8042_set_mux_mode(true, NULL) || i8042_enable_mux_ports())
pr_warn("failed to resume active multiplexor, mouse won't work\n");
} else if (i8042_ports[I8042_AUX_PORT_NO].serio)
i8042_enable_aux_port();
if (i8042_ports[I8042_KBD_PORT_NO].serio)
i8042_enable_kbd_port();
i8042_interrupt(0, NULL);
return 0;
}
/*
* Here we try to restore the original BIOS settings to avoid
* upsetting it.
*/
static int i8042_pm_suspend(struct device *dev)
{
int i;
if (pm_suspend_via_firmware())
i8042_controller_reset(true);
/* Set up serio interrupts for system wakeup. */
for (i = 0; i < I8042_NUM_PORTS; i++) {
struct serio *serio = i8042_ports[i].serio;
if (serio && device_may_wakeup(&serio->dev))
enable_irq_wake(i8042_ports[i].irq);
}
return 0;
}
static int i8042_pm_resume_noirq(struct device *dev)
{
if (!pm_resume_via_firmware())
i8042_interrupt(0, NULL);
return 0;
}
static int i8042_pm_resume(struct device *dev)
{
bool want_reset;
int i;
for (i = 0; i < I8042_NUM_PORTS; i++) {
struct serio *serio = i8042_ports[i].serio;
if (serio && device_may_wakeup(&serio->dev))
disable_irq_wake(i8042_ports[i].irq);
}
/*
* If platform firmware was not going to be involved in suspend, we did
* not restore the controller state to whatever it had been at boot
* time, so we do not need to do anything.
*/
if (!pm_suspend_via_firmware())
return 0;
/*
* We only need to reset the controller if we are resuming after handing
* off control to the platform firmware, otherwise we can simply restore
* the mode.
*/
want_reset = pm_resume_via_firmware();
return i8042_controller_resume(want_reset);
}
static int i8042_pm_thaw(struct device *dev)
{
i8042_interrupt(0, NULL);
return 0;
}
static int i8042_pm_reset(struct device *dev)
{
i8042_controller_reset(false);
return 0;
}
static int i8042_pm_restore(struct device *dev)
{
return i8042_controller_resume(false);
}
static const struct dev_pm_ops i8042_pm_ops = {
.suspend = i8042_pm_suspend,
.resume_noirq = i8042_pm_resume_noirq,
.resume = i8042_pm_resume,
.thaw = i8042_pm_thaw,
.poweroff = i8042_pm_reset,
.restore = i8042_pm_restore,
};
#endif /* CONFIG_PM */
/*
* We need to reset the 8042 back to original mode on system shutdown,
* because otherwise BIOSes will be confused.
*/
static void i8042_shutdown(struct platform_device *dev)
{
i8042_controller_reset(false);
}
static int __init i8042_create_kbd_port(void)
{
struct serio *serio;
struct i8042_port *port = &i8042_ports[I8042_KBD_PORT_NO];
serio = kzalloc(sizeof(struct serio), GFP_KERNEL);
if (!serio)
return -ENOMEM;
serio->id.type = i8042_direct ? SERIO_8042 : SERIO_8042_XL;
serio->write = i8042_dumbkbd ? NULL : i8042_kbd_write;
serio->start = i8042_start;
serio->stop = i8042_stop;
serio->close = i8042_port_close;
serio->ps2_cmd_mutex = &i8042_mutex;
serio->port_data = port;
serio->dev.parent = &i8042_platform_device->dev;
strlcpy(serio->name, "i8042 KBD port", sizeof(serio->name));
strlcpy(serio->phys, I8042_KBD_PHYS_DESC, sizeof(serio->phys));
strlcpy(serio->firmware_id, i8042_kbd_firmware_id,
sizeof(serio->firmware_id));
port->serio = serio;
port->irq = I8042_KBD_IRQ;
return 0;
}
static int __init i8042_create_aux_port(int idx)
{
struct serio *serio;
int port_no = idx < 0 ? I8042_AUX_PORT_NO : I8042_MUX_PORT_NO + idx;
struct i8042_port *port = &i8042_ports[port_no];
serio = kzalloc(sizeof(struct serio), GFP_KERNEL);
if (!serio)
return -ENOMEM;
serio->id.type = SERIO_8042;
serio->write = i8042_aux_write;
serio->start = i8042_start;
serio->stop = i8042_stop;
serio->ps2_cmd_mutex = &i8042_mutex;
serio->port_data = port;
serio->dev.parent = &i8042_platform_device->dev;
if (idx < 0) {
strlcpy(serio->name, "i8042 AUX port", sizeof(serio->name));
strlcpy(serio->phys, I8042_AUX_PHYS_DESC, sizeof(serio->phys));
strlcpy(serio->firmware_id, i8042_aux_firmware_id,
sizeof(serio->firmware_id));
serio->close = i8042_port_close;
} else {
snprintf(serio->name, sizeof(serio->name), "i8042 AUX%d port", idx);
snprintf(serio->phys, sizeof(serio->phys), I8042_MUX_PHYS_DESC, idx + 1);
strlcpy(serio->firmware_id, i8042_aux_firmware_id,
sizeof(serio->firmware_id));
}
port->serio = serio;
port->mux = idx;
port->irq = I8042_AUX_IRQ;
return 0;
}
static void __init i8042_free_kbd_port(void)
{
kfree(i8042_ports[I8042_KBD_PORT_NO].serio);
i8042_ports[I8042_KBD_PORT_NO].serio = NULL;
}
static void __init i8042_free_aux_ports(void)
{
int i;
for (i = I8042_AUX_PORT_NO; i < I8042_NUM_PORTS; i++) {
kfree(i8042_ports[i].serio);
i8042_ports[i].serio = NULL;
}
}
static void __init i8042_register_ports(void)
{
int i;
for (i = 0; i < I8042_NUM_PORTS; i++) {
struct serio *serio = i8042_ports[i].serio;
if (serio) {
printk(KERN_INFO "serio: %s at %#lx,%#lx irq %d\n",
serio->name,
(unsigned long) I8042_DATA_REG,
(unsigned long) I8042_COMMAND_REG,
i8042_ports[i].irq);
serio_register_port(serio);
device_set_wakeup_capable(&serio->dev, true);
}
}
}
static void i8042_unregister_ports(void)
{
int i;
for (i = 0; i < I8042_NUM_PORTS; i++) {
if (i8042_ports[i].serio) {
serio_unregister_port(i8042_ports[i].serio);
i8042_ports[i].serio = NULL;
}
}
}
static void i8042_free_irqs(void)
{
if (i8042_aux_irq_registered)
free_irq(I8042_AUX_IRQ, i8042_platform_device);
if (i8042_kbd_irq_registered)
free_irq(I8042_KBD_IRQ, i8042_platform_device);
i8042_aux_irq_registered = i8042_kbd_irq_registered = false;
}
static int __init i8042_setup_aux(void)
{
int (*aux_enable)(void);
int error;
int i;
if (i8042_check_aux())
return -ENODEV;
if (i8042_nomux || i8042_check_mux()) {
error = i8042_create_aux_port(-1);
if (error)
goto err_free_ports;
aux_enable = i8042_enable_aux_port;
} else {
for (i = 0; i < I8042_NUM_MUX_PORTS; i++) {
error = i8042_create_aux_port(i);
if (error)
goto err_free_ports;
}
aux_enable = i8042_enable_mux_ports;
}
error = request_irq(I8042_AUX_IRQ, i8042_interrupt, IRQF_SHARED,
"i8042", i8042_platform_device);
if (error)
goto err_free_ports;
if (aux_enable())
goto err_free_irq;
i8042_aux_irq_registered = true;
return 0;
err_free_irq:
free_irq(I8042_AUX_IRQ, i8042_platform_device);
err_free_ports:
i8042_free_aux_ports();
return error;
}
static int __init i8042_setup_kbd(void)
{
int error;
error = i8042_create_kbd_port();
if (error)
return error;
error = request_irq(I8042_KBD_IRQ, i8042_interrupt, IRQF_SHARED,
"i8042", i8042_platform_device);
if (error)
goto err_free_port;
error = i8042_enable_kbd_port();
if (error)
goto err_free_irq;
i8042_kbd_irq_registered = true;
return 0;
err_free_irq:
free_irq(I8042_KBD_IRQ, i8042_platform_device);
err_free_port:
i8042_free_kbd_port();
return error;
}
static int i8042_kbd_bind_notifier(struct notifier_block *nb,
unsigned long action, void *data)
{
struct device *dev = data;
struct serio *serio = to_serio_port(dev);
struct i8042_port *port = serio->port_data;
if (serio != i8042_ports[I8042_KBD_PORT_NO].serio)
return 0;
switch (action) {
case BUS_NOTIFY_BOUND_DRIVER:
port->driver_bound = true;
break;
case BUS_NOTIFY_UNBIND_DRIVER:
port->driver_bound = false;
break;
}
return 0;
}
static int __init i8042_probe(struct platform_device *dev)
{
int error;
i8042_platform_device = dev;
if (i8042_reset == I8042_RESET_ALWAYS) {
error = i8042_controller_selftest();
if (error)
return error;
}
error = i8042_controller_init();
if (error)
return error;
#ifdef CONFIG_X86
if (i8042_dritek)
i8042_dritek_enable();
#endif
if (!i8042_noaux) {
error = i8042_setup_aux();
if (error && error != -ENODEV && error != -EBUSY)
goto out_fail;
}
if (!i8042_nokbd) {
error = i8042_setup_kbd();
if (error)
goto out_fail;
}
/*
* Ok, everything is ready, let's register all serio ports
*/
i8042_register_ports();
return 0;
out_fail:
i8042_free_aux_ports(); /* in case KBD failed but AUX not */
i8042_free_irqs();
i8042_controller_reset(false);
i8042_platform_device = NULL;
return error;
}
static int i8042_remove(struct platform_device *dev)
{
i8042_unregister_ports();
i8042_free_irqs();
i8042_controller_reset(false);
i8042_platform_device = NULL;
return 0;
}
static struct platform_driver i8042_driver = {
.driver = {
.name = "i8042",
#ifdef CONFIG_PM
.pm = &i8042_pm_ops,
#endif
},
.remove = i8042_remove,
.shutdown = i8042_shutdown,
};
static struct notifier_block i8042_kbd_bind_notifier_block = {
.notifier_call = i8042_kbd_bind_notifier,
};
static int __init i8042_init(void)
{
struct platform_device *pdev;
int err;
dbg_init();
err = i8042_platform_init();
if (err)
return err;
err = i8042_controller_check();
if (err)
goto err_platform_exit;
pdev = platform_create_bundle(&i8042_driver, i8042_probe, NULL, 0, NULL, 0);
if (IS_ERR(pdev)) {
err = PTR_ERR(pdev);
goto err_platform_exit;
}
bus_register_notifier(&serio_bus, &i8042_kbd_bind_notifier_block);
panic_blink = i8042_panic_blink;
return 0;
err_platform_exit:
i8042_platform_exit();
return err;
}
static void __exit i8042_exit(void)
{
platform_device_unregister(i8042_platform_device);
platform_driver_unregister(&i8042_driver);
i8042_platform_exit();
bus_unregister_notifier(&serio_bus, &i8042_kbd_bind_notifier_block);
panic_blink = NULL;
}
module_init(i8042_init);
module_exit(i8042_exit);
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3000_0 |
crossvul-cpp_data_bad_5108_1 | /* packet-usb-audio.c
*
* usb audio dissector
* Tomasz Mon 2012
*
* 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.
*/
/* the parsing of audio-specific descriptors is based on
USB Device Class Definition for Audio Devices, Release 2.0 and
USB Audio Device Class Specification for Basic Audio Devices, Release 1.0 */
#include "config.h"
#include <epan/packet.h>
#include <epan/expert.h>
#include <epan/reassemble.h>
#include "packet-usb.h"
/* XXX - we use the same macro for mpeg sections,
can we put this in a common include file? */
#define USB_AUDIO_BCD44_TO_DEC(x) ((((x)&0xf0) >> 4) * 10 + ((x)&0x0f))
void proto_register_usb_audio(void);
void proto_reg_handoff_usb_audio(void);
/* protocols and header fields */
static int proto_usb_audio = -1;
static int hf_midi_cable_number = -1;
static int hf_midi_code_index = -1;
static int hf_midi_event = -1;
static int hf_ac_if_desc_subtype = -1;
static int hf_ac_if_hdr_ver = -1;
static int hf_ac_if_hdr_total_len = -1;
static int hf_ac_if_hdr_bInCollection = -1;
static int hf_ac_if_hdr_if_num = -1;
static int hf_ac_if_input_terminalid = -1;
static int hf_ac_if_input_terminaltype = -1;
static int hf_ac_if_input_assocterminal = -1;
static int hf_ac_if_input_nrchannels = -1;
static int hf_ac_if_input_channelconfig = -1;
static int hf_ac_if_input_channelnames = -1;
static int hf_ac_if_input_terminal = -1;
static int hf_ac_if_output_terminalid = -1;
static int hf_ac_if_output_terminaltype = -1;
static int hf_ac_if_output_assocterminal = -1;
static int hf_ac_if_output_sourceid = -1;
static int hf_ac_if_output_terminal = -1;
static int hf_ac_if_fu_unitid = -1;
static int hf_ac_if_fu_sourceid = -1;
static int hf_ac_if_fu_controlsize = -1;
static int hf_ac_if_fu_controls = -1;
static int hf_ac_if_fu_control = -1;
static int hf_ac_if_fu_controls_d0 = -1;
static int hf_ac_if_fu_controls_d1 = -1;
static int hf_ac_if_fu_controls_d2 = -1;
static int hf_ac_if_fu_controls_d3 = -1;
static int hf_ac_if_fu_controls_d4 = -1;
static int hf_ac_if_fu_controls_d5 = -1;
static int hf_ac_if_fu_controls_d6 = -1;
static int hf_ac_if_fu_controls_d7 = -1;
static int hf_ac_if_fu_controls_d8 = -1;
static int hf_ac_if_fu_controls_d9 = -1;
static int hf_ac_if_fu_controls_rsv = -1;
static int hf_ac_if_fu_ifeature = -1;
static int hf_as_if_desc_subtype = -1;
static int hf_as_if_gen_term_id = -1;
static int hf_as_if_gen_delay = -1;
static int hf_as_if_gen_format = -1;
static int hf_as_if_ft_formattype = -1;
static int hf_as_if_ft_maxbitrate = -1;
static int hf_as_if_ft_nrchannels = -1;
static int hf_as_if_ft_subframesize = -1;
static int hf_as_if_ft_bitresolution = -1;
static int hf_as_if_ft_samplesperframe = -1;
static int hf_as_if_ft_samfreqtype = -1;
static int hf_as_if_ft_lowersamfreq = -1;
static int hf_as_if_ft_uppersamfreq = -1;
static int hf_as_if_ft_samfreq = -1;
static int hf_as_ep_desc_subtype = -1;
static reassembly_table midi_data_reassembly_table;
static gint ett_usb_audio = -1;
static gint ett_usb_audio_desc = -1;
static gint ett_ac_if_fu_controls = -1;
static gint ett_ac_if_fu_controls0 = -1;
static gint ett_ac_if_fu_controls1 = -1;
static dissector_handle_t sysex_handle;
#define AUDIO_IF_SUBCLASS_UNDEFINED 0x00
#define AUDIO_IF_SUBCLASS_AUDIOCONTROL 0x01
#define AUDIO_IF_SUBCLASS_AUDIOSTREAMING 0x02
#define AUDIO_IF_SUBCLASS_MIDISTREAMING 0x03
#if 0
static const value_string usb_audio_subclass_vals[] = {
{AUDIO_IF_SUBCLASS_UNDEFINED, "SUBCLASS_UNDEFINED"},
{AUDIO_IF_SUBCLASS_AUDIOCONTROL, "AUDIOCONSTROL"},
{AUDIO_IF_SUBCLASS_AUDIOSTREAMING, "AUDIOSTREAMING"},
{AUDIO_IF_SUBCLASS_MIDISTREAMING, "MIDISTREAMING"},
{0, NULL}
};
#endif
static const value_string code_index_vals[] = {
{ 0x0, "Miscellaneous (Reserved)" },
{ 0x1, "Cable events (Reserved)" },
{ 0x2, "Two-byte System Common message" },
{ 0x3, "Three-byte System Common message" },
{ 0x4, "SysEx starts or continues" },
{ 0x5, "SysEx ends with following single byte/Single-byte System Common Message" },
{ 0x6, "SysEx ends with following two bytes" },
{ 0x7, "SysEx ends with following three bytes" },
{ 0x8, "Note-off" },
{ 0x9, "Note-on" },
{ 0xA, "Poly-KeyPress" },
{ 0xB, "Control Change" },
{ 0xC, "Program Change" },
{ 0xD, "Channel Pressure" },
{ 0xE, "PitchBend Change" },
{ 0xF, "Single Byte" },
{ 0, NULL }
};
/* USB audio specification, section A.8 */
#define CS_INTERFACE 0x24
#define CS_ENDPOINT 0x25
static const value_string aud_descriptor_type_vals[] = {
{CS_INTERFACE, "audio class interface"},
{CS_ENDPOINT, "audio class endpoint"},
{0,NULL}
};
static value_string_ext aud_descriptor_type_vals_ext =
VALUE_STRING_EXT_INIT(aud_descriptor_type_vals);
#define AC_SUBTYPE_HEADER 0x01
#define AC_SUBTYPE_INPUT_TERMINAL 0x02
#define AC_SUBTYPE_OUTPUT_TERMINAL 0x03
#define AC_SUBTYPE_MIXER_UNIT 0x04
#define AC_SUBTYPE_SELECTOR_UNIT 0x05
#define AC_SUBTYPE_FEATURE_UNIT 0x06
static const value_string ac_subtype_vals[] = {
{AC_SUBTYPE_HEADER, "Header Descriptor"},
{AC_SUBTYPE_INPUT_TERMINAL, "Input terminal descriptor"},
{AC_SUBTYPE_OUTPUT_TERMINAL, "Output terminal descriptor"},
{AC_SUBTYPE_MIXER_UNIT, "Mixer unit descriptor"},
{AC_SUBTYPE_SELECTOR_UNIT, "Selector unit descriptor"},
{AC_SUBTYPE_FEATURE_UNIT, "Feature unit descriptor"},
{0,NULL}
};
static value_string_ext ac_subtype_vals_ext =
VALUE_STRING_EXT_INIT(ac_subtype_vals);
#define AS_SUBTYPE_GENERAL 0x01
#define AS_SUBTYPE_FORMAT_TYPE 0x02
#define AS_SUBTYPE_ENCODER 0x03
static const value_string as_subtype_vals[] = {
{AS_SUBTYPE_GENERAL, "General AS Descriptor"},
{AS_SUBTYPE_FORMAT_TYPE, "Format type descriptor"},
{AS_SUBTYPE_ENCODER, "Encoder descriptor"},
{0,NULL}
};
static value_string_ext as_subtype_vals_ext =
VALUE_STRING_EXT_INIT(as_subtype_vals);
/* From http://www.usb.org/developers/docs/devclass_docs/termt10.pdf */
static const value_string terminal_types_vals[] = {
/* USB Terminal Types */
{0x0100, "USB Undefined"},
{0x0101, "USB Streaming"},
{0x01FF, "USB vendor specific"},
/* Input Terminal Tyoes */
{0x0200, "Input Undefined"},
{0x0201, "Microphone"},
{0x0202, "Desktop Microphone"},
{0x0203, "Personal microphone"},
{0x0204, "Omni-directional icrophone"},
{0x0205, "Microphone array"},
{0x0206, "Processing microphone array"},
{0x0300, "Output Undefined"},
{0x0301, "Speaker"},
{0x0302, "Headphones"},
{0x0303, "Head Mounted Display Audio"},
{0x0304, "Desktop speaker"},
{0x0305, "Room speaker"},
{0x0306, "Communication speaker"},
{0x0307, "Low frequency effects speaker"},
/* Bi-directional Terminal Types */
{0x0400, "Bi-directional Undefined"},
{0x0401, "Handset"},
{0x0402, "Headset"},
{0x0403, "Speakerphone, no echoreduction"},
{0x0404, "Echo-suppressing speakerphone"},
{0x0405, "Echo-canceling speakerphone"},
/* Telephony Terminal Types */
{0x0500, "Telephony Undefined"},
{0x0501, "Phone line"},
{0x0502, "Telephone"},
{0x0503, "Down Line Pone"},
/* External Terminal Types */
{0x0600, "External Undefined"},
{0x0601, "Analog connector"},
{0x0602, "Digital audio interface"},
{0x0603, "Line connector"},
{0x0604, "Legacy audio connector"},
{0x0605, "S/PDIF interface"},
{0x0606, "1394 DA stream"},
{0x0607, "1394 DV stream soudtrack"},
/* Embedded Funciton Terminal Types */
{0x0700, "Embedded Undefined"},
{0x0701, "Level Calibration Noise Source"},
{0x0702, "Equalization Noise"},
{0x0703, "CD player"},
{0x0704, "DAT"},
{0x0705, "DCC"},
{0x0706, "MiniDisk"},
{0x0707, "Analog Tape"},
{0x0708, "Phonograph"},
{0x0709, "VCR Audio"},
{0x070A, "Video Disc Audio"},
{0x070B, "DVD Audio"},
{0x070C, "TV Tuner Audio"},
{0x070D, "Satellite Receiver Audio"},
{0x070E, "cable Tuner Audio"},
{0x070F, "DSS Audio"},
{0x0710, "Radio Receiver"},
{0x0711, "Radio Transmitter"},
{0x0712, "Multi-track Recorder"},
{0x0713, "Synthesizer"},
{0,NULL}
};
static value_string_ext terminal_types_vals_ext =
VALUE_STRING_EXT_INIT(terminal_types_vals);
typedef struct _audio_conv_info_t {
/* the major version of the USB audio class specification,
taken from the AC header descriptor */
guint8 ver_major;
} audio_conv_info_t;
static int hf_sysex_msg_fragments = -1;
static int hf_sysex_msg_fragment = -1;
static int hf_sysex_msg_fragment_overlap = -1;
static int hf_sysex_msg_fragment_overlap_conflicts = -1;
static int hf_sysex_msg_fragment_multiple_tails = -1;
static int hf_sysex_msg_fragment_too_long_fragment = -1;
static int hf_sysex_msg_fragment_error = -1;
static int hf_sysex_msg_fragment_count = -1;
static int hf_sysex_msg_reassembled_in = -1;
static int hf_sysex_msg_reassembled_length = -1;
static int hf_sysex_msg_reassembled_data = -1;
static gint ett_sysex_msg_fragment = -1;
static gint ett_sysex_msg_fragments = -1;
static expert_field ei_usb_audio_undecoded = EI_INIT;
static const fragment_items sysex_msg_frag_items = {
/* Fragment subtrees */
&ett_sysex_msg_fragment,
&ett_sysex_msg_fragments,
/* Fragment fields */
&hf_sysex_msg_fragments,
&hf_sysex_msg_fragment,
&hf_sysex_msg_fragment_overlap,
&hf_sysex_msg_fragment_overlap_conflicts,
&hf_sysex_msg_fragment_multiple_tails,
&hf_sysex_msg_fragment_too_long_fragment,
&hf_sysex_msg_fragment_error,
&hf_sysex_msg_fragment_count,
/* Reassembled in field */
&hf_sysex_msg_reassembled_in,
/* Reassembled length field */
&hf_sysex_msg_reassembled_length,
&hf_sysex_msg_reassembled_data,
/* Tag */
"Message fragments"
};
static inline gboolean
is_sysex_code(guint8 code)
{
return (code == 0x04 || code == 0x05 || code == 0x06 || code == 0x07);
}
static gboolean
is_last_sysex_packet_in_tvb(tvbuff_t *tvb, gint offset)
{
gboolean last = TRUE;
gint length = tvb_reported_length(tvb);
offset += 4;
while (offset < length)
{
guint8 code = tvb_get_guint8(tvb, offset);
code &= 0x0F;
if (is_sysex_code(code))
{
last = FALSE;
break;
}
offset += 4;
}
return last;
}
static void
dissect_usb_midi_event(tvbuff_t *tvb, packet_info *pinfo,
proto_tree *usb_audio_tree, proto_tree *parent_tree,
gint offset)
{
guint8 code;
guint8 cable;
gboolean save_fragmented;
proto_tree *tree = NULL;
col_set_str(pinfo->cinfo, COL_INFO, "USB-MIDI Event Packets");
code = tvb_get_guint8(tvb, offset);
cable = (code & 0xF0) >> 4;
code &= 0x0F;
if (parent_tree)
{
proto_item *ti;
ti = proto_tree_add_protocol_format(usb_audio_tree, proto_usb_audio, tvb, offset, 4, "USB Midi Event Packet");
tree = proto_item_add_subtree(ti, ett_usb_audio);
proto_tree_add_item(tree, hf_midi_cable_number, tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_midi_code_index, tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_midi_event, tvb, offset+1, 3, ENC_BIG_ENDIAN);
}
save_fragmented = pinfo->fragmented;
/* Reassemble SysEx commands */
if (is_sysex_code(code))
{
tvbuff_t* new_tvb = NULL;
fragment_head *frag_sysex_msg = NULL;
pinfo->fragmented = TRUE;
if (code == 0x04)
{
frag_sysex_msg = fragment_add_seq_next(&midi_data_reassembly_table,
tvb, offset+1,
pinfo,
cable, /* ID for fragments belonging together */
NULL,
3,
TRUE);
}
else
{
frag_sysex_msg = fragment_add_seq_next(&midi_data_reassembly_table,
tvb, offset+1,
pinfo,
cable, /* ID for fragments belonging together */
NULL,
(gint)(code - 4),
FALSE);
}
if (is_last_sysex_packet_in_tvb(tvb, offset))
{
new_tvb = process_reassembled_data(tvb, offset+1, pinfo,
"Reassembled Message", frag_sysex_msg, &sysex_msg_frag_items,
NULL, usb_audio_tree);
if (code != 0x04) { /* Reassembled */
col_append_str(pinfo->cinfo, COL_INFO,
" (SysEx Reassembled)");
} else { /* Not last packet of reassembled Short Message */
col_append_str(pinfo->cinfo, COL_INFO,
" (SysEx fragment)");
}
if (new_tvb)
{
call_dissector(sysex_handle, new_tvb, pinfo, parent_tree);
}
}
}
pinfo->fragmented = save_fragmented;
}
/* dissect the body of an AC interface header descriptor
return the number of bytes dissected (which may be smaller than the
body's length) */
static gint
dissect_ac_if_hdr_body(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_,
proto_tree *tree, usb_conv_info_t *usb_conv_info)
{
gint offset_start;
guint16 bcdADC;
guint8 ver_major;
double ver;
guint8 if_in_collection, i;
audio_conv_info_t *audio_conv_info;
offset_start = offset;
bcdADC = tvb_get_letohs(tvb, offset);
ver_major = USB_AUDIO_BCD44_TO_DEC(bcdADC>>8);
ver = ver_major + USB_AUDIO_BCD44_TO_DEC(bcdADC&0xFF) / 100.0;
proto_tree_add_double_format_value(tree, hf_ac_if_hdr_ver,
tvb, offset, 2, ver, "%2.2f", ver);
audio_conv_info = (audio_conv_info_t *)usb_conv_info->class_data;
if(!audio_conv_info) {
audio_conv_info = wmem_new(wmem_file_scope(), audio_conv_info_t);
usb_conv_info->class_data = audio_conv_info;
/* XXX - set reasonable default values for all components
that are not filled in by this function */
}
audio_conv_info->ver_major = ver_major;
offset += 2;
/* version 1 refers to the Basic Audio Device specification,
version 2 is the Audio Device class specification, see above */
if (ver_major==1) {
proto_tree_add_item(tree, hf_ac_if_hdr_total_len,
tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
if_in_collection = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_ac_if_hdr_bInCollection,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
for (i=0; i<if_in_collection; i++) {
proto_tree_add_item(tree, hf_ac_if_hdr_if_num,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
}
}
return offset-offset_start;
}
static gint
dissect_ac_if_input_terminal(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_,
proto_tree *tree, usb_conv_info_t *usb_conv_info _U_)
{
gint offset_start;
offset_start = offset;
proto_tree_add_item(tree, hf_ac_if_input_terminalid, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_ac_if_input_terminaltype, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_ac_if_input_assocterminal, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_ac_if_input_nrchannels, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_ac_if_input_channelconfig, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_ac_if_input_channelnames, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_ac_if_input_terminal, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
return offset-offset_start;
}
static gint
dissect_ac_if_output_terminal(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_,
proto_tree *tree, usb_conv_info_t *usb_conv_info _U_)
{
gint offset_start;
offset_start = offset;
proto_tree_add_item(tree, hf_ac_if_output_terminalid, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_ac_if_output_terminaltype, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_ac_if_output_assocterminal, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_ac_if_output_sourceid, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_ac_if_output_terminal, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
return offset-offset_start;
}
static gint
dissect_ac_if_feature_unit(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_,
proto_tree *tree, usb_conv_info_t *usb_conv_info _U_)
{
gint offset_start;
guint8 controlsize;
proto_tree *bitmap_tree;
proto_item *ti;
static const int *fu_controls0[] = {
&hf_ac_if_fu_controls_d0,
&hf_ac_if_fu_controls_d1,
&hf_ac_if_fu_controls_d2,
&hf_ac_if_fu_controls_d3,
&hf_ac_if_fu_controls_d4,
&hf_ac_if_fu_controls_d5,
&hf_ac_if_fu_controls_d6,
&hf_ac_if_fu_controls_d7,
NULL };
static const int *fu_controls1[] = {
&hf_ac_if_fu_controls_d8,
&hf_ac_if_fu_controls_d9,
&hf_ac_if_fu_controls_rsv,
NULL };
offset_start = offset;
proto_tree_add_item(tree, hf_ac_if_fu_unitid, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_ac_if_fu_sourceid, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_ac_if_fu_controlsize, tvb, offset, 1, ENC_LITTLE_ENDIAN);
controlsize = tvb_get_guint8(tvb, offset) + 1;
offset += 1;
ti = proto_tree_add_item(tree, hf_ac_if_fu_controls, tvb, offset, controlsize, ENC_NA);
bitmap_tree = proto_item_add_subtree(ti, ett_ac_if_fu_controls);
proto_tree_add_bitmask(bitmap_tree, tvb, offset, hf_ac_if_fu_control, ett_ac_if_fu_controls0, fu_controls0, ENC_LITTLE_ENDIAN);
if(controlsize >= 1){
proto_tree_add_bitmask(bitmap_tree, tvb, offset + 1, hf_ac_if_fu_control, ett_ac_if_fu_controls1, fu_controls1, ENC_LITTLE_ENDIAN);
}
offset += controlsize;
proto_tree_add_item(tree, hf_ac_if_fu_ifeature, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
return offset-offset_start;
}
static gint
dissect_as_if_general_body(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_,
proto_tree *tree, usb_conv_info_t *usb_conv_info)
{
audio_conv_info_t *audio_conv_info;
gint offset_start;
/* the caller has already checked that usb_conv_info!=NULL */
audio_conv_info = (audio_conv_info_t *)usb_conv_info->class_data;
if (!audio_conv_info)
return 0;
offset_start = offset;
if (audio_conv_info->ver_major==1) {
proto_tree_add_item(tree, hf_as_if_gen_term_id,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_as_if_gen_delay,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_as_if_gen_format,
tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
}
return offset-offset_start;
}
static gint
dissect_as_if_format_type_body(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_,
proto_tree *tree, usb_conv_info_t *usb_conv_info)
{
audio_conv_info_t *audio_conv_info;
gint offset_start;
guint8 SamFreqType;
guint8 format_type;
/* the caller has already checked that usb_conv_info!=NULL */
audio_conv_info = (audio_conv_info_t *)usb_conv_info->class_data;
if (!audio_conv_info)
return 0;
offset_start = offset;
proto_tree_add_item(tree, hf_as_if_ft_formattype, tvb, offset, 1, ENC_LITTLE_ENDIAN);
format_type = tvb_get_guint8(tvb, offset);
offset++;
switch(format_type){
case 1:
proto_tree_add_item(tree, hf_as_if_ft_nrchannels, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_as_if_ft_subframesize, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_as_if_ft_bitresolution, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_as_if_ft_samfreqtype, tvb, offset, 1, ENC_LITTLE_ENDIAN);
SamFreqType = tvb_get_guint8(tvb, offset);
offset++;
if(SamFreqType == 0){
proto_tree_add_item(tree, hf_as_if_ft_lowersamfreq, tvb, offset, 3, ENC_LITTLE_ENDIAN);
offset += 3;
proto_tree_add_item(tree, hf_as_if_ft_uppersamfreq, tvb, offset, 3, ENC_LITTLE_ENDIAN);
offset += 3;
}else {
while(SamFreqType){
proto_tree_add_item(tree, hf_as_if_ft_samfreq, tvb, offset, 3, ENC_LITTLE_ENDIAN);
offset += 3;
SamFreqType--;
}
}
break;
case 2:
proto_tree_add_item(tree, hf_as_if_ft_maxbitrate, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_as_if_ft_samplesperframe, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_as_if_ft_samfreqtype, tvb, offset, 1, ENC_LITTLE_ENDIAN);
SamFreqType = tvb_get_guint8(tvb, offset);
offset++;
if(SamFreqType == 0){
proto_tree_add_item(tree, hf_as_if_ft_lowersamfreq, tvb, offset, 3, ENC_LITTLE_ENDIAN);
offset += 3;
proto_tree_add_item(tree, hf_as_if_ft_uppersamfreq, tvb, offset, 3, ENC_LITTLE_ENDIAN);
offset += 3;
}else {
while(SamFreqType){
proto_tree_add_item(tree, hf_as_if_ft_samfreq, tvb, offset, 3, ENC_LITTLE_ENDIAN);
offset += 3;
SamFreqType--;
}
}
break;
default:
break;
}
return offset-offset_start;
}
static gint
dissect_usb_audio_descriptor(tvbuff_t *tvb, packet_info *pinfo,
proto_tree *tree, void *data)
{
gint offset = 0;
usb_conv_info_t *usb_conv_info;
proto_tree *desc_tree = NULL;
proto_item *desc_tree_item;
guint8 desc_len;
guint8 desc_type;
guint8 desc_subtype;
const gchar *subtype_str;
usb_conv_info = (usb_conv_info_t *)data;
if (!usb_conv_info || usb_conv_info->interfaceClass!=IF_CLASS_AUDIO)
return 0;
desc_len = tvb_get_guint8(tvb, offset);
desc_type = tvb_get_guint8(tvb, offset+1);
if (desc_type==CS_INTERFACE &&
usb_conv_info->interfaceSubclass==AUDIO_IF_SUBCLASS_AUDIOCONTROL) {
desc_tree = proto_tree_add_subtree(tree, tvb, offset, desc_len,
ett_usb_audio_desc, &desc_tree_item,
"Class-specific Audio Control Interface Descriptor");
dissect_usb_descriptor_header(desc_tree, tvb, offset,
&aud_descriptor_type_vals_ext);
offset += 2;
desc_subtype = tvb_get_guint8(tvb, offset);
proto_tree_add_item(desc_tree, hf_ac_if_desc_subtype,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
subtype_str = try_val_to_str_ext(desc_subtype, &ac_subtype_vals_ext);
if (subtype_str)
proto_item_append_text(desc_tree_item, ": %s", subtype_str);
offset++;
switch(desc_subtype) {
case AC_SUBTYPE_HEADER:
/* these subfunctions return the number of bytes dissected,
this is not necessarily the length of the body
as some components are not yet dissected
we rely on the descriptor's length byte instead */
dissect_ac_if_hdr_body(tvb, offset, pinfo, desc_tree, usb_conv_info);
break;
case AC_SUBTYPE_INPUT_TERMINAL:
dissect_ac_if_input_terminal(tvb, offset, pinfo, desc_tree, usb_conv_info);
break;
case AC_SUBTYPE_OUTPUT_TERMINAL:
dissect_ac_if_output_terminal(tvb, offset, pinfo, desc_tree, usb_conv_info);
break;
case AC_SUBTYPE_FEATURE_UNIT:
dissect_ac_if_feature_unit(tvb, offset, pinfo, desc_tree, usb_conv_info);
break;
default:
proto_tree_add_expert(desc_tree, pinfo, &ei_usb_audio_undecoded, tvb, offset-3, desc_len);
break;
}
}
else if (desc_type==CS_INTERFACE &&
usb_conv_info->interfaceSubclass==AUDIO_IF_SUBCLASS_AUDIOSTREAMING) {
desc_tree = proto_tree_add_subtree(tree, tvb, offset, desc_len,
ett_usb_audio_desc, &desc_tree_item,
"Class-specific Audio Streaming Interface Descriptor");
dissect_usb_descriptor_header(desc_tree, tvb, offset,
&aud_descriptor_type_vals_ext);
offset += 2;
desc_subtype = tvb_get_guint8(tvb, offset);
proto_tree_add_item(desc_tree, hf_as_if_desc_subtype,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
subtype_str = try_val_to_str_ext(desc_subtype, &as_subtype_vals_ext);
if (subtype_str)
proto_item_append_text(desc_tree_item, ": %s", subtype_str);
offset++;
switch(desc_subtype) {
case AS_SUBTYPE_GENERAL:
dissect_as_if_general_body(tvb, offset, pinfo,
desc_tree, usb_conv_info);
break;
case AS_SUBTYPE_FORMAT_TYPE:
dissect_as_if_format_type_body(tvb, offset, pinfo,
desc_tree, usb_conv_info);
break;
default:
proto_tree_add_expert(desc_tree, pinfo, &ei_usb_audio_undecoded, tvb, offset-3, desc_len);
break;
}
}
/* there are no class-specific endpoint descriptors for audio control */
else if (desc_type == CS_ENDPOINT &&
usb_conv_info->interfaceSubclass==AUDIO_IF_SUBCLASS_AUDIOSTREAMING) {
desc_tree = proto_tree_add_subtree(tree, tvb, offset, desc_len,
ett_usb_audio_desc, &desc_tree_item,
"Class-specific Audio Streaming Endpoint Descriptor");
dissect_usb_descriptor_header(desc_tree, tvb, offset,
&aud_descriptor_type_vals_ext);
offset += 2;
proto_tree_add_item(desc_tree, hf_as_ep_desc_subtype,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
}
else
return 0;
return desc_len;
}
/* dissector for usb midi bulk data */
static int
dissect_usb_audio_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void *data)
{
usb_conv_info_t *usb_conv_info;
proto_tree *tree;
proto_item *ti;
gint offset, length;
gint i;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
usb_conv_info = (usb_conv_info_t *)data;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBAUDIO");
ti = proto_tree_add_protocol_format(parent_tree, proto_usb_audio, tvb, 0, -1, "USB Audio");
tree = proto_item_add_subtree(ti, ett_usb_audio);
length = tvb_reported_length(tvb);
offset = 0;
switch (usb_conv_info->interfaceSubclass)
{
case AUDIO_IF_SUBCLASS_MIDISTREAMING:
col_set_str(pinfo->cinfo, COL_INFO, "USB-MIDI Event Packets");
for (i = 0; i < length / 4; i++)
{
dissect_usb_midi_event(tvb, pinfo, tree, parent_tree, offset);
offset += 4;
}
break;
default:
proto_tree_add_expert(tree, pinfo, &ei_usb_audio_undecoded, tvb, offset, length);
}
return length;
}
static void
midi_data_reassemble_init(void)
{
reassembly_table_init(&midi_data_reassembly_table,
&addresses_reassembly_table_functions);
}
static void
midi_data_reassemble_cleanup(void)
{
reassembly_table_destroy(&midi_data_reassembly_table);
}
void
proto_register_usb_audio(void)
{
static hf_register_info hf[] = {
{ &hf_midi_cable_number,
{ "Cable Number", "usbaudio.midi.cable_number", FT_UINT8, BASE_HEX,
NULL, 0xF0, NULL, HFILL }},
{ &hf_midi_code_index,
{ "Code Index", "usbaudio.midi.code_index", FT_UINT8, BASE_HEX,
VALS(code_index_vals), 0x0F, NULL, HFILL }},
{ &hf_midi_event,
{ "MIDI Event", "usbaudio.midi.event", FT_UINT24, BASE_HEX,
NULL, 0, NULL, HFILL }},
{ &hf_ac_if_desc_subtype,
{ "Subtype", "usbaudio.ac_if_subtype", FT_UINT8, BASE_HEX|BASE_EXT_STRING,
&ac_subtype_vals_ext, 0x00, "bDescriptorSubtype", HFILL }},
{ &hf_ac_if_hdr_ver,
{ "Version", "usbaudio.ac_if_hdr.bcdADC",
FT_DOUBLE, BASE_NONE, NULL, 0, "bcdADC", HFILL }},
{ &hf_ac_if_hdr_total_len,
{ "Total length", "usbaudio.ac_if_hdr.wTotalLength",
FT_UINT16, BASE_DEC, NULL, 0x00, "wTotalLength", HFILL }},
{ &hf_ac_if_hdr_bInCollection,
{ "Total number of interfaces", "usbaudio.ac_if_hdr.bInCollection",
FT_UINT8, BASE_DEC, NULL, 0x00, "bInCollection", HFILL }},
{ &hf_ac_if_hdr_if_num,
{ "Interface number", "usbaudio.ac_if_hdr.baInterfaceNr",
FT_UINT8, BASE_DEC, NULL, 0x00, "baInterfaceNr", HFILL }},
{ &hf_ac_if_input_terminalid,
{ "Terminal ID", "usbaudio.ac_if_input.bTerminalID",
FT_UINT8, BASE_DEC, NULL, 0x00, "bTerminalID", HFILL }},
{ &hf_ac_if_input_terminaltype,
{ "Terminal Type", "usbaudio.ac_if_input.wTerminalType", FT_UINT16,
BASE_HEX|BASE_EXT_STRING, &terminal_types_vals_ext, 0x00, "wTerminalType", HFILL }},
{ &hf_ac_if_input_assocterminal,
{ "Assoc Terminal", "usbaudio.ac_if_input.bAssocTerminal",
FT_UINT8, BASE_DEC, NULL, 0x00, "bAssocTerminal", HFILL }},
{ &hf_ac_if_input_nrchannels,
{ "Number Channels", "usbaudio.ac_if_input.bNrChannels",
FT_UINT8, BASE_DEC, NULL, 0x00, "bNrChannels", HFILL }},
{ &hf_ac_if_input_channelconfig,
{ "Channel Config", "usbaudio.ac_if_input.wChannelConfig",
FT_UINT16, BASE_HEX, NULL, 0x00, "wChannelConfig", HFILL }},
{ &hf_ac_if_input_channelnames,
{ "Channel Names", "usbaudio.ac_if_input.iChannelNames",
FT_UINT8, BASE_DEC, NULL, 0x00, "iChannelNames", HFILL }},
{ &hf_ac_if_input_terminal,
{ "Terminal", "usbaudio.ac_if_input.iTerminal",
FT_UINT8, BASE_DEC, NULL, 0x00, "iTerminal", HFILL }},
{ &hf_ac_if_output_terminalid,
{ "Terminal ID", "usbaudio.ac_if_output.bTerminalID",
FT_UINT8, BASE_DEC, NULL, 0x00, "bTerminalID", HFILL }},
{ &hf_ac_if_output_terminaltype,
{ "Terminal Type", "usbaudio.ac_if_output.wTerminalType", FT_UINT16,
BASE_HEX|BASE_EXT_STRING, &terminal_types_vals_ext, 0x00, "wTerminalType", HFILL }},
{ &hf_ac_if_output_assocterminal,
{ "Assoc Terminal", "usbaudio.ac_if_output.bAssocTerminal",
FT_UINT8, BASE_DEC, NULL, 0x00, "bAssocTerminal", HFILL }},
{ &hf_ac_if_output_sourceid,
{ "Source ID", "usbaudio.ac_if_output.bSourceID",
FT_UINT8, BASE_DEC, NULL, 0x00, "bSourceID", HFILL }},
{ &hf_ac_if_output_terminal,
{ "Terminal", "usbaudio.ac_if_output.iTerminal",
FT_UINT8, BASE_DEC, NULL, 0x00, "iTerminal", HFILL }},
{ &hf_ac_if_fu_unitid,
{ "Unit ID", "usbaudio.ac_if_fu.bUnitID",
FT_UINT8, BASE_DEC, NULL, 0x00, "bUnitID", HFILL }},
{ &hf_ac_if_fu_sourceid,
{ "Source ID", "usbaudio.ac_if_fu.bSourceID",
FT_UINT8, BASE_DEC, NULL, 0x00, "bSourceID", HFILL }},
{ &hf_ac_if_fu_controlsize,
{ "Control Size", "usbaudio.ac_if_fu.bControlSize",
FT_UINT8, BASE_DEC, NULL, 0x00, "bControlSize", HFILL }},
{ &hf_ac_if_fu_controls,
{ "Controls", "usbaudio.ac_if_fu.bmaControls",
FT_BYTES, BASE_NONE, NULL, 0x00, "bmaControls", HFILL }},
{ &hf_ac_if_fu_control,
{ "Control", "usbaudio.ac_if_fu.bmaControl",
FT_UINT8, BASE_HEX, NULL, 0x00, "bmaControls", HFILL }},
{ &hf_ac_if_fu_controls_d0,
{ "Mute", "usbaudio.ac_if_fu.bmaControls.d0",
FT_BOOLEAN, 8, NULL, 0x01, NULL, HFILL }},
{ &hf_ac_if_fu_controls_d1,
{ "Volume", "usbaudio.ac_if_fu.bmaControls.d1",
FT_BOOLEAN, 8, NULL, 0x02, NULL, HFILL }},
{ &hf_ac_if_fu_controls_d2,
{ "Bass", "usbaudio.ac_if_fu.bmaControls.d2",
FT_BOOLEAN, 8, NULL, 0x04, NULL, HFILL }},
{ &hf_ac_if_fu_controls_d3,
{ "Mid", "usbaudio.ac_if_fu.bmaControls.d3",
FT_BOOLEAN, 8, NULL, 0x08, NULL, HFILL }},
{ &hf_ac_if_fu_controls_d4,
{ "Treble", "usbaudio.ac_if_fu.bmaControls.d4",
FT_BOOLEAN, 8, NULL, 0x10, NULL, HFILL }},
{ &hf_ac_if_fu_controls_d5,
{ "Graphic Equalizer", "usbaudio.ac_if_fu.bmaControls.d5",
FT_BOOLEAN, 8, NULL, 0x20, NULL, HFILL }},
{ &hf_ac_if_fu_controls_d6,
{ "Automatic Gain", "usbaudio.ac_if_fu.bmaControls.d6",
FT_BOOLEAN, 8, NULL, 0x40, NULL, HFILL }},
{ &hf_ac_if_fu_controls_d7,
{ "Delay", "usbaudio.ac_if_fu.bmaControls.d7",
FT_BOOLEAN, 8, NULL, 0x80, NULL, HFILL }},
{ &hf_ac_if_fu_controls_d8,
{ "Bass Boost", "usbaudio.ac_if_fu.bmaControls.d8",
FT_BOOLEAN, 8, NULL, 0x01, NULL, HFILL }},
{ &hf_ac_if_fu_controls_d9,
{ "Loudness", "usbaudio.ac_if_fu.bmaControls.d9",
FT_BOOLEAN, 8, NULL, 0x02, NULL, HFILL }},
{ &hf_ac_if_fu_controls_rsv,
{ "Reserved", "usbaudio.ac_if_fu.bmaControls.rsv",
FT_UINT8, BASE_HEX, NULL, 0xFC, "Must be zero", HFILL }},
{ &hf_ac_if_fu_ifeature,
{ "Feature", "usbaudio.ac_if_fu.iFeature",
FT_UINT8, BASE_DEC, NULL, 0x00, "iFeature", HFILL }},
{ &hf_as_if_desc_subtype,
{ "Subtype", "usbaudio.as_if_subtype", FT_UINT8, BASE_HEX|BASE_EXT_STRING,
&as_subtype_vals_ext, 0x00, "bDescriptorSubtype", HFILL }},
{ &hf_as_if_gen_term_id,
{ "Terminal ID", "usbaudio.as_if_gen.bTerminalLink",
FT_UINT8, BASE_DEC, NULL, 0x00, "bTerminalLink", HFILL }},
{ &hf_as_if_gen_delay,
{ "Interface delay in frames", "usbaudio.as_if_gen.bDelay",
FT_UINT8, BASE_DEC, NULL, 0x00, "bDelay", HFILL }},
{ &hf_as_if_gen_format,
{ "Format", "usbaudio.as_if_gen.wFormatTag",
FT_UINT16, BASE_HEX, NULL, 0x00, "wFormatTag", HFILL }},
{ &hf_as_if_ft_formattype,
{ "FormatType", "usbaudio.as_if_ft.bFormatType",
FT_UINT8, BASE_DEC, NULL, 0x00, "wFormatType", HFILL }},
{ &hf_as_if_ft_maxbitrate,
{ "Max Bit Rate", "usbaudio.as_if_ft.wMaxBitRate",
FT_UINT16, BASE_DEC, NULL, 0x00, "wMaxBitRate", HFILL }},
{ &hf_as_if_ft_nrchannels,
{ "Number Channels", "usbaudio.as_if_ft.bNrChannels",
FT_UINT8, BASE_DEC, NULL, 0x00, "bNrChannels", HFILL }},
{ &hf_as_if_ft_subframesize,
{ "Subframe Size", "usbaudio.as_if_ft.bSubframeSize",
FT_UINT8, BASE_DEC, NULL, 0x00, "bSubframeSize", HFILL }},
{ &hf_as_if_ft_bitresolution,
{ "Bit Resolution", "usbaudio.as_if_ft.bBitResolution",
FT_UINT8, BASE_DEC, NULL, 0x00, "bBitResolution", HFILL }},
{ &hf_as_if_ft_samplesperframe,
{ "Samples Per Frame", "usbaudio.as_if_ft.wSamplesPerFrame",
FT_UINT16, BASE_DEC, NULL, 0x00, "wSamplesPerFrame", HFILL }},
{ &hf_as_if_ft_samfreqtype,
{ "Samples Frequence Type", "usbaudio.as_if_ft.bSamFreqType",
FT_UINT8, BASE_DEC, NULL, 0x00, "bSamFreqType", HFILL }},
{ &hf_as_if_ft_lowersamfreq,
{ "Lower Samples Frequence", "usbaudio.as_if_ft.tLowerSamFreq",
FT_UINT24, BASE_DEC, NULL, 0x00, "tLowerSamFreq", HFILL }},
{ &hf_as_if_ft_uppersamfreq,
{ "Upper Samples Frequence", "usbaudio.as_if_ft.tUpperSamFreq",
FT_UINT24, BASE_DEC, NULL, 0x00, "tUpperSamFreq", HFILL }},
{ &hf_as_if_ft_samfreq,
{ "Samples Frequence", "usbaudio.as_if_ft.tSamFreq",
FT_UINT24, BASE_DEC, NULL, 0x00, "tSamFreq", HFILL }},
{ &hf_as_ep_desc_subtype,
{ "Subtype", "usbaudio.as_ep_subtype", FT_UINT8,
BASE_HEX, NULL, 0x00, "bDescriptorSubtype", HFILL }},
{ &hf_sysex_msg_fragments,
{ "Message fragments", "usbaudio.sysex.fragments",
FT_NONE, BASE_NONE, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_fragment,
{ "Message fragment", "usbaudio.sysex.fragment",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_fragment_overlap,
{ "Message fragment overlap", "usbaudio.sysex.fragment.overlap",
FT_BOOLEAN, 0, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_fragment_overlap_conflicts,
{ "Message fragment overlapping with conflicting data",
"usbaudio.sysex.fragment.overlap.conflicts",
FT_BOOLEAN, 0, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_fragment_multiple_tails,
{ "Message has multiple tail fragments",
"usbaudio.sysex.fragment.multiple_tails",
FT_BOOLEAN, 0, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_fragment_too_long_fragment,
{ "Message fragment too long", "usbaudio.sysex.fragment.too_long_fragment",
FT_BOOLEAN, 0, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_fragment_error,
{ "Message defragmentation error", "usbaudio.sysex.fragment.error",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_fragment_count,
{ "Message fragment count", "usbaudio.sysex.fragment.count",
FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_reassembled_in,
{ "Reassembled in", "usbaudio.sysex.reassembled.in",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_reassembled_length,
{ "Reassembled length", "usbaudio.sysex.reassembled.length",
FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }},
{ &hf_sysex_msg_reassembled_data,
{ "Reassembled data", "usbaudio.sysex.reassembled.data",
FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }}
};
static gint *usb_audio_subtrees[] = {
&ett_usb_audio,
&ett_usb_audio_desc,
&ett_sysex_msg_fragment,
&ett_sysex_msg_fragments,
&ett_ac_if_fu_controls,
&ett_ac_if_fu_controls0,
&ett_ac_if_fu_controls1
};
static ei_register_info ei[] = {
{ &ei_usb_audio_undecoded, { "usbaudio.undecoded", PI_UNDECODED, PI_WARN, "Not dissected yet (report to wireshark.org)", EXPFILL }},
};
expert_module_t *expert_usb_audio;
proto_usb_audio = proto_register_protocol("USB Audio", "USBAUDIO", "usbaudio");
proto_register_field_array(proto_usb_audio, hf, array_length(hf));
proto_register_subtree_array(usb_audio_subtrees, array_length(usb_audio_subtrees));
expert_usb_audio = expert_register_protocol(proto_usb_audio);
expert_register_field_array(expert_usb_audio, ei, array_length(ei));
register_init_routine(&midi_data_reassemble_init);
register_cleanup_routine(&midi_data_reassemble_cleanup);
register_dissector("usbaudio", dissect_usb_audio_bulk, proto_usb_audio);
}
void
proto_reg_handoff_usb_audio(void)
{
dissector_handle_t usb_audio_bulk_handle, usb_audio_descr_handle;
usb_audio_descr_handle = create_dissector_handle(
dissect_usb_audio_descriptor, proto_usb_audio);
dissector_add_uint("usb.descriptor", IF_CLASS_AUDIO, usb_audio_descr_handle);
usb_audio_bulk_handle = find_dissector("usbaudio");
dissector_add_uint("usb.bulk", IF_CLASS_AUDIO, usb_audio_bulk_handle);
sysex_handle = find_dissector_add_dependency("sysex", proto_usb_audio);
}
/*
* 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-476/c/bad_5108_1 |
crossvul-cpp_data_good_528_1 | #include "vterm_internal.h"
/* vim: set sw=2 : */
#include <stdio.h>
#include <string.h>
#include "rect.h"
#include "utf8.h"
#define UNICODE_SPACE 0x20
#define UNICODE_LINEFEED 0x0a
/* State of the pen at some moment in time, also used in a cell */
typedef struct
{
/* After the bitfield */
VTermColor fg, bg;
unsigned int bold : 1;
unsigned int underline : 2;
unsigned int italic : 1;
unsigned int blink : 1;
unsigned int reverse : 1;
unsigned int strike : 1;
unsigned int font : 4; /* 0 to 9 */
/* Extra state storage that isn't strictly pen-related */
unsigned int protected_cell : 1;
unsigned int dwl : 1; /* on a DECDWL or DECDHL line */
unsigned int dhl : 2; /* on a DECDHL line (1=top 2=bottom) */
} ScreenPen;
/* Internal representation of a screen cell */
typedef struct
{
uint32_t chars[VTERM_MAX_CHARS_PER_CELL];
ScreenPen pen;
} ScreenCell;
static int vterm_screen_set_cell(VTermScreen *screen, VTermPos pos, const VTermScreenCell *cell);
struct VTermScreen
{
VTerm *vt;
VTermState *state;
const VTermScreenCallbacks *callbacks;
void *cbdata;
VTermDamageSize damage_merge;
/* start_row == -1 => no damage */
VTermRect damaged;
VTermRect pending_scrollrect;
int pending_scroll_downward, pending_scroll_rightward;
int rows;
int cols;
int global_reverse;
/* Primary and Altscreen. buffers[1] is lazily allocated as needed */
ScreenCell *buffers[2];
/* buffer will == buffers[0] or buffers[1], depending on altscreen */
ScreenCell *buffer;
/* buffer for a single screen row used in scrollback storage callbacks */
VTermScreenCell *sb_buffer;
ScreenPen pen;
};
static ScreenCell *getcell(const VTermScreen *screen, int row, int col)
{
if(row < 0 || row >= screen->rows)
return NULL;
if(col < 0 || col >= screen->cols)
return NULL;
return screen->buffer + (screen->cols * row) + col;
}
static ScreenCell *realloc_buffer(VTermScreen *screen, ScreenCell *buffer, int new_rows, int new_cols)
{
ScreenCell *new_buffer = vterm_allocator_malloc(screen->vt, sizeof(ScreenCell) * new_rows * new_cols);
int row, col;
for(row = 0; row < new_rows; row++) {
for(col = 0; col < new_cols; col++) {
ScreenCell *new_cell = new_buffer + row*new_cols + col;
if(buffer && row < screen->rows && col < screen->cols)
*new_cell = buffer[row * screen->cols + col];
else {
new_cell->chars[0] = 0;
new_cell->pen = screen->pen;
}
}
}
vterm_allocator_free(screen->vt, buffer);
return new_buffer;
}
static void damagerect(VTermScreen *screen, VTermRect rect)
{
VTermRect emit;
switch(screen->damage_merge) {
case VTERM_DAMAGE_CELL:
/* Always emit damage event */
emit = rect;
break;
case VTERM_DAMAGE_ROW:
/* Emit damage longer than one row. Try to merge with existing damage in
* the same row */
if(rect.end_row > rect.start_row + 1) {
// Bigger than 1 line - flush existing, emit this
vterm_screen_flush_damage(screen);
emit = rect;
}
else if(screen->damaged.start_row == -1) {
// None stored yet
screen->damaged = rect;
return;
}
else if(rect.start_row == screen->damaged.start_row) {
// Merge with the stored line
if(screen->damaged.start_col > rect.start_col)
screen->damaged.start_col = rect.start_col;
if(screen->damaged.end_col < rect.end_col)
screen->damaged.end_col = rect.end_col;
return;
}
else {
// Emit the currently stored line, store a new one
emit = screen->damaged;
screen->damaged = rect;
}
break;
case VTERM_DAMAGE_SCREEN:
case VTERM_DAMAGE_SCROLL:
/* Never emit damage event */
if(screen->damaged.start_row == -1)
screen->damaged = rect;
else {
rect_expand(&screen->damaged, &rect);
}
return;
default:
DEBUG_LOG1("TODO: Maybe merge damage for level %d\n", screen->damage_merge);
return;
}
if(screen->callbacks && screen->callbacks->damage)
(*screen->callbacks->damage)(emit, screen->cbdata);
}
static void damagescreen(VTermScreen *screen)
{
VTermRect rect = {0,0,0,0};
rect.end_row = screen->rows;
rect.end_col = screen->cols;
damagerect(screen, rect);
}
static int putglyph(VTermGlyphInfo *info, VTermPos pos, void *user)
{
int i;
int col;
VTermRect rect;
VTermScreen *screen = user;
ScreenCell *cell = getcell(screen, pos.row, pos.col);
if(!cell)
return 0;
for(i = 0; i < VTERM_MAX_CHARS_PER_CELL && info->chars[i]; i++) {
cell->chars[i] = info->chars[i];
cell->pen = screen->pen;
}
if(i < VTERM_MAX_CHARS_PER_CELL)
cell->chars[i] = 0;
for(col = 1; col < info->width; col++)
getcell(screen, pos.row, pos.col + col)->chars[0] = (uint32_t)-1;
rect.start_row = pos.row;
rect.end_row = pos.row+1;
rect.start_col = pos.col;
rect.end_col = pos.col+info->width;
cell->pen.protected_cell = info->protected_cell;
cell->pen.dwl = info->dwl;
cell->pen.dhl = info->dhl;
damagerect(screen, rect);
return 1;
}
static int moverect_internal(VTermRect dest, VTermRect src, void *user)
{
VTermScreen *screen = user;
if(screen->callbacks && screen->callbacks->sb_pushline &&
dest.start_row == 0 && dest.start_col == 0 && // starts top-left corner
dest.end_col == screen->cols && // full width
screen->buffer == screen->buffers[0]) { // not altscreen
VTermPos pos;
for(pos.row = 0; pos.row < src.start_row; pos.row++) {
for(pos.col = 0; pos.col < screen->cols; pos.col++)
(void)vterm_screen_get_cell(screen, pos, screen->sb_buffer + pos.col);
(screen->callbacks->sb_pushline)(screen->cols, screen->sb_buffer, screen->cbdata);
}
}
{
int cols = src.end_col - src.start_col;
int downward = src.start_row - dest.start_row;
int init_row, test_row, inc_row;
int row;
if(downward < 0) {
init_row = dest.end_row - 1;
test_row = dest.start_row - 1;
inc_row = -1;
}
else {
init_row = dest.start_row;
test_row = dest.end_row;
inc_row = +1;
}
for(row = init_row; row != test_row; row += inc_row)
memmove(getcell(screen, row, dest.start_col),
getcell(screen, row + downward, src.start_col),
cols * sizeof(ScreenCell));
}
return 1;
}
static int moverect_user(VTermRect dest, VTermRect src, void *user)
{
VTermScreen *screen = user;
if(screen->callbacks && screen->callbacks->moverect) {
if(screen->damage_merge != VTERM_DAMAGE_SCROLL)
// Avoid an infinite loop
vterm_screen_flush_damage(screen);
if((*screen->callbacks->moverect)(dest, src, screen->cbdata))
return 1;
}
damagerect(screen, dest);
return 1;
}
static int erase_internal(VTermRect rect, int selective, void *user)
{
VTermScreen *screen = user;
int row, col;
for(row = rect.start_row; row < screen->state->rows && row < rect.end_row; row++) {
const VTermLineInfo *info = vterm_state_get_lineinfo(screen->state, row);
for(col = rect.start_col; col < rect.end_col; col++) {
ScreenCell *cell = getcell(screen, row, col);
if(selective && cell->pen.protected_cell)
continue;
cell->chars[0] = 0;
cell->pen = screen->pen;
cell->pen.dwl = info->doublewidth;
cell->pen.dhl = info->doubleheight;
}
}
return 1;
}
static int erase_user(VTermRect rect, int selective UNUSED, void *user)
{
VTermScreen *screen = user;
damagerect(screen, rect);
return 1;
}
static int erase(VTermRect rect, int selective, void *user)
{
erase_internal(rect, selective, user);
return erase_user(rect, 0, user);
}
static int scrollrect(VTermRect rect, int downward, int rightward, void *user)
{
VTermScreen *screen = user;
if(screen->damage_merge != VTERM_DAMAGE_SCROLL) {
vterm_scroll_rect(rect, downward, rightward,
moverect_internal, erase_internal, screen);
vterm_screen_flush_damage(screen);
vterm_scroll_rect(rect, downward, rightward,
moverect_user, erase_user, screen);
return 1;
}
if(screen->damaged.start_row != -1 &&
!rect_intersects(&rect, &screen->damaged)) {
vterm_screen_flush_damage(screen);
}
if(screen->pending_scrollrect.start_row == -1) {
screen->pending_scrollrect = rect;
screen->pending_scroll_downward = downward;
screen->pending_scroll_rightward = rightward;
}
else if(rect_equal(&screen->pending_scrollrect, &rect) &&
((screen->pending_scroll_downward == 0 && downward == 0) ||
(screen->pending_scroll_rightward == 0 && rightward == 0))) {
screen->pending_scroll_downward += downward;
screen->pending_scroll_rightward += rightward;
}
else {
vterm_screen_flush_damage(screen);
screen->pending_scrollrect = rect;
screen->pending_scroll_downward = downward;
screen->pending_scroll_rightward = rightward;
}
vterm_scroll_rect(rect, downward, rightward,
moverect_internal, erase_internal, screen);
if(screen->damaged.start_row == -1)
return 1;
if(rect_contains(&rect, &screen->damaged)) {
/* Scroll region entirely contains the damage; just move it */
vterm_rect_move(&screen->damaged, -downward, -rightward);
rect_clip(&screen->damaged, &rect);
}
/* There are a number of possible cases here, but lets restrict this to only
* the common case where we might actually gain some performance by
* optimising it. Namely, a vertical scroll that neatly cuts the damage
* region in half.
*/
else if(rect.start_col <= screen->damaged.start_col &&
rect.end_col >= screen->damaged.end_col &&
rightward == 0) {
if(screen->damaged.start_row >= rect.start_row &&
screen->damaged.start_row < rect.end_row) {
screen->damaged.start_row -= downward;
if(screen->damaged.start_row < rect.start_row)
screen->damaged.start_row = rect.start_row;
if(screen->damaged.start_row > rect.end_row)
screen->damaged.start_row = rect.end_row;
}
if(screen->damaged.end_row >= rect.start_row &&
screen->damaged.end_row < rect.end_row) {
screen->damaged.end_row -= downward;
if(screen->damaged.end_row < rect.start_row)
screen->damaged.end_row = rect.start_row;
if(screen->damaged.end_row > rect.end_row)
screen->damaged.end_row = rect.end_row;
}
}
else {
DEBUG_LOG2("TODO: Just flush and redo damaged=" STRFrect " rect=" STRFrect "\n",
ARGSrect(screen->damaged), ARGSrect(rect));
}
return 1;
}
static int movecursor(VTermPos pos, VTermPos oldpos, int visible, void *user)
{
VTermScreen *screen = user;
if(screen->callbacks && screen->callbacks->movecursor)
return (*screen->callbacks->movecursor)(pos, oldpos, visible, screen->cbdata);
return 0;
}
static int setpenattr(VTermAttr attr, VTermValue *val, void *user)
{
VTermScreen *screen = user;
switch(attr) {
case VTERM_ATTR_BOLD:
screen->pen.bold = val->boolean;
return 1;
case VTERM_ATTR_UNDERLINE:
screen->pen.underline = val->number;
return 1;
case VTERM_ATTR_ITALIC:
screen->pen.italic = val->boolean;
return 1;
case VTERM_ATTR_BLINK:
screen->pen.blink = val->boolean;
return 1;
case VTERM_ATTR_REVERSE:
screen->pen.reverse = val->boolean;
return 1;
case VTERM_ATTR_STRIKE:
screen->pen.strike = val->boolean;
return 1;
case VTERM_ATTR_FONT:
screen->pen.font = val->number;
return 1;
case VTERM_ATTR_FOREGROUND:
screen->pen.fg = val->color;
return 1;
case VTERM_ATTR_BACKGROUND:
screen->pen.bg = val->color;
return 1;
case VTERM_N_ATTRS:
return 0;
}
return 0;
}
static int settermprop(VTermProp prop, VTermValue *val, void *user)
{
VTermScreen *screen = user;
switch(prop) {
case VTERM_PROP_ALTSCREEN:
if(val->boolean && !screen->buffers[1])
return 0;
screen->buffer = val->boolean ? screen->buffers[1] : screen->buffers[0];
/* only send a damage event on disable; because during enable there's an
* erase that sends a damage anyway
*/
if(!val->boolean)
damagescreen(screen);
break;
case VTERM_PROP_REVERSE:
screen->global_reverse = val->boolean;
damagescreen(screen);
break;
default:
; /* ignore */
}
if(screen->callbacks && screen->callbacks->settermprop)
return (*screen->callbacks->settermprop)(prop, val, screen->cbdata);
return 1;
}
static int bell(void *user)
{
VTermScreen *screen = user;
if(screen->callbacks && screen->callbacks->bell)
return (*screen->callbacks->bell)(screen->cbdata);
return 0;
}
static int resize(int new_rows, int new_cols, VTermPos *delta, void *user)
{
VTermScreen *screen = user;
int is_altscreen = (screen->buffers[1] && screen->buffer == screen->buffers[1]);
int old_rows = screen->rows;
int old_cols = screen->cols;
int first_blank_row;
if(!is_altscreen && new_rows < old_rows) {
// Fewer rows - determine if we're going to scroll at all, and if so, push
// those lines to scrollback
VTermPos pos = { 0, 0 };
VTermPos cursor = screen->state->pos;
// Find the first blank row after the cursor.
for(pos.row = old_rows - 1; pos.row >= new_rows; pos.row--)
if(!vterm_screen_is_eol(screen, pos) || cursor.row == pos.row)
break;
first_blank_row = pos.row + 1;
if(first_blank_row > new_rows) {
VTermRect rect = {0,0,0,0};
rect.end_row = old_rows;
rect.end_col = old_cols;
scrollrect(rect, first_blank_row - new_rows, 0, user);
vterm_screen_flush_damage(screen);
delta->row -= first_blank_row - new_rows;
}
}
screen->buffers[0] = realloc_buffer(screen, screen->buffers[0], new_rows, new_cols);
if(screen->buffers[1])
screen->buffers[1] = realloc_buffer(screen, screen->buffers[1], new_rows, new_cols);
screen->buffer = is_altscreen ? screen->buffers[1] : screen->buffers[0];
screen->rows = new_rows;
screen->cols = new_cols;
vterm_allocator_free(screen->vt, screen->sb_buffer);
screen->sb_buffer = vterm_allocator_malloc(screen->vt, sizeof(VTermScreenCell) * new_cols);
if(new_cols > old_cols) {
VTermRect rect;
rect.start_row = 0;
rect.end_row = old_rows;
rect.start_col = old_cols;
rect.end_col = new_cols;
damagerect(screen, rect);
}
if(new_rows > old_rows) {
if(!is_altscreen && screen->callbacks && screen->callbacks->sb_popline) {
int rows = new_rows - old_rows;
while(rows) {
VTermRect rect = {0,0,0,0};
VTermPos pos = { 0, 0 };
if(!(screen->callbacks->sb_popline(screen->cols, screen->sb_buffer, screen->cbdata)))
break;
rect.end_row = screen->rows;
rect.end_col = screen->cols;
scrollrect(rect, -1, 0, user);
for(pos.col = 0; pos.col < screen->cols; pos.col += screen->sb_buffer[pos.col].width)
vterm_screen_set_cell(screen, pos, screen->sb_buffer + pos.col);
rect.end_row = 1;
damagerect(screen, rect);
vterm_screen_flush_damage(screen);
rows--;
delta->row++;
}
}
{
VTermRect rect;
rect.start_row = old_rows;
rect.end_row = new_rows;
rect.start_col = 0;
rect.end_col = new_cols;
damagerect(screen, rect);
}
}
if(screen->callbacks && screen->callbacks->resize)
return (*screen->callbacks->resize)(new_rows, new_cols, screen->cbdata);
return 1;
}
static int setlineinfo(int row, const VTermLineInfo *newinfo, const VTermLineInfo *oldinfo, void *user)
{
VTermScreen *screen = user;
int col;
VTermRect rect;
if(newinfo->doublewidth != oldinfo->doublewidth ||
newinfo->doubleheight != oldinfo->doubleheight) {
for(col = 0; col < screen->cols; col++) {
ScreenCell *cell = getcell(screen, row, col);
cell->pen.dwl = newinfo->doublewidth;
cell->pen.dhl = newinfo->doubleheight;
}
rect.start_row = row;
rect.end_row = row + 1;
rect.start_col = 0;
rect.end_col = newinfo->doublewidth ? screen->cols / 2 : screen->cols;
damagerect(screen, rect);
if(newinfo->doublewidth) {
rect.start_col = screen->cols / 2;
rect.end_col = screen->cols;
erase_internal(rect, 0, user);
}
}
return 1;
}
static VTermStateCallbacks state_cbs = {
&putglyph, /* putglyph */
&movecursor, /* movecursor */
&scrollrect, /* scrollrect */
NULL, /* moverect */
&erase, /* erase */
NULL, /* initpen */
&setpenattr, /* setpenattr */
&settermprop, /* settermprop */
&bell, /* bell */
&resize, /* resize */
&setlineinfo /* setlineinfo */
};
/*
* Allocate a new screen and return it.
* Return NULL when out of memory.
*/
static VTermScreen *screen_new(VTerm *vt)
{
VTermState *state = vterm_obtain_state(vt);
VTermScreen *screen;
int rows, cols;
if (state == NULL)
return NULL;
screen = vterm_allocator_malloc(vt, sizeof(VTermScreen));
if (screen == NULL)
return NULL;
vterm_get_size(vt, &rows, &cols);
screen->vt = vt;
screen->state = state;
screen->damage_merge = VTERM_DAMAGE_CELL;
screen->damaged.start_row = -1;
screen->pending_scrollrect.start_row = -1;
screen->rows = rows;
screen->cols = cols;
screen->callbacks = NULL;
screen->cbdata = NULL;
screen->buffers[0] = realloc_buffer(screen, NULL, rows, cols);
screen->buffer = screen->buffers[0];
screen->sb_buffer = vterm_allocator_malloc(screen->vt, sizeof(VTermScreenCell) * cols);
if (screen->buffer == NULL || screen->sb_buffer == NULL)
{
vterm_screen_free(screen);
return NULL;
}
vterm_state_set_callbacks(screen->state, &state_cbs, screen);
return screen;
}
INTERNAL void vterm_screen_free(VTermScreen *screen)
{
vterm_allocator_free(screen->vt, screen->buffers[0]);
vterm_allocator_free(screen->vt, screen->buffers[1]);
vterm_allocator_free(screen->vt, screen->sb_buffer);
vterm_allocator_free(screen->vt, screen);
}
void vterm_screen_reset(VTermScreen *screen, int hard)
{
screen->damaged.start_row = -1;
screen->pending_scrollrect.start_row = -1;
vterm_state_reset(screen->state, hard);
vterm_screen_flush_damage(screen);
}
static size_t _get_chars(const VTermScreen *screen, const int utf8, void *buffer, size_t len, const VTermRect rect)
{
size_t outpos = 0;
int padding = 0;
int row, col;
#define PUT(c) \
if(utf8) { \
size_t thislen = utf8_seqlen(c); \
if(buffer && outpos + thislen <= len) \
outpos += fill_utf8((c), (char *)buffer + outpos); \
else \
outpos += thislen; \
} \
else { \
if(buffer && outpos + 1 <= len) \
((uint32_t*)buffer)[outpos++] = (c); \
else \
outpos++; \
}
for(row = rect.start_row; row < rect.end_row; row++) {
for(col = rect.start_col; col < rect.end_col; col++) {
ScreenCell *cell = getcell(screen, row, col);
int i;
if(cell->chars[0] == 0)
// Erased cell, might need a space
padding++;
else if(cell->chars[0] == (uint32_t)-1)
// Gap behind a double-width char, do nothing
;
else {
while(padding) {
PUT(UNICODE_SPACE);
padding--;
}
for(i = 0; i < VTERM_MAX_CHARS_PER_CELL && cell->chars[i]; i++) {
PUT(cell->chars[i]);
}
}
}
if(row < rect.end_row - 1) {
PUT(UNICODE_LINEFEED);
padding = 0;
}
}
return outpos;
}
size_t vterm_screen_get_chars(const VTermScreen *screen, uint32_t *chars, size_t len, const VTermRect rect)
{
return _get_chars(screen, 0, chars, len, rect);
}
size_t vterm_screen_get_text(const VTermScreen *screen, char *str, size_t len, const VTermRect rect)
{
return _get_chars(screen, 1, str, len, rect);
}
/* Copy internal to external representation of a screen cell */
int vterm_screen_get_cell(const VTermScreen *screen, VTermPos pos, VTermScreenCell *cell)
{
ScreenCell *intcell = getcell(screen, pos.row, pos.col);
int i;
if(!intcell)
return 0;
for(i = 0; ; i++) {
cell->chars[i] = intcell->chars[i];
if(!intcell->chars[i])
break;
}
cell->attrs.bold = intcell->pen.bold;
cell->attrs.underline = intcell->pen.underline;
cell->attrs.italic = intcell->pen.italic;
cell->attrs.blink = intcell->pen.blink;
cell->attrs.reverse = intcell->pen.reverse ^ screen->global_reverse;
cell->attrs.strike = intcell->pen.strike;
cell->attrs.font = intcell->pen.font;
cell->attrs.dwl = intcell->pen.dwl;
cell->attrs.dhl = intcell->pen.dhl;
cell->fg = intcell->pen.fg;
cell->bg = intcell->pen.bg;
if(pos.col < (screen->cols - 1) &&
getcell(screen, pos.row, pos.col + 1)->chars[0] == (uint32_t)-1)
cell->width = 2;
else
cell->width = 1;
return 1;
}
/* Copy external to internal representation of a screen cell */
/* static because it's only used internally for sb_popline during resize */
static int vterm_screen_set_cell(VTermScreen *screen, VTermPos pos, const VTermScreenCell *cell)
{
ScreenCell *intcell = getcell(screen, pos.row, pos.col);
int i;
if(!intcell)
return 0;
for(i = 0; ; i++) {
intcell->chars[i] = cell->chars[i];
if(!cell->chars[i])
break;
}
intcell->pen.bold = cell->attrs.bold;
intcell->pen.underline = cell->attrs.underline;
intcell->pen.italic = cell->attrs.italic;
intcell->pen.blink = cell->attrs.blink;
intcell->pen.reverse = cell->attrs.reverse ^ screen->global_reverse;
intcell->pen.strike = cell->attrs.strike;
intcell->pen.font = cell->attrs.font;
intcell->pen.fg = cell->fg;
intcell->pen.bg = cell->bg;
if(cell->width == 2)
getcell(screen, pos.row, pos.col + 1)->chars[0] = (uint32_t)-1;
return 1;
}
int vterm_screen_is_eol(const VTermScreen *screen, VTermPos pos)
{
/* This cell is EOL if this and every cell to the right is black */
for(; pos.col < screen->cols; pos.col++) {
ScreenCell *cell = getcell(screen, pos.row, pos.col);
if(cell->chars[0] != 0)
return 0;
}
return 1;
}
VTermScreen *vterm_obtain_screen(VTerm *vt)
{
if(!vt->screen)
vt->screen = screen_new(vt);
return vt->screen;
}
void vterm_screen_enable_altscreen(VTermScreen *screen, int altscreen)
{
if(!screen->buffers[1] && altscreen) {
int rows, cols;
vterm_get_size(screen->vt, &rows, &cols);
screen->buffers[1] = realloc_buffer(screen, NULL, rows, cols);
}
}
void vterm_screen_set_callbacks(VTermScreen *screen, const VTermScreenCallbacks *callbacks, void *user)
{
screen->callbacks = callbacks;
screen->cbdata = user;
}
void *vterm_screen_get_cbdata(VTermScreen *screen)
{
return screen->cbdata;
}
void vterm_screen_set_unrecognised_fallbacks(VTermScreen *screen, const VTermParserCallbacks *fallbacks, void *user)
{
vterm_state_set_unrecognised_fallbacks(screen->state, fallbacks, user);
}
void *vterm_screen_get_unrecognised_fbdata(VTermScreen *screen)
{
return vterm_state_get_unrecognised_fbdata(screen->state);
}
void vterm_screen_flush_damage(VTermScreen *screen)
{
if(screen->pending_scrollrect.start_row != -1) {
vterm_scroll_rect(screen->pending_scrollrect, screen->pending_scroll_downward, screen->pending_scroll_rightward,
moverect_user, erase_user, screen);
screen->pending_scrollrect.start_row = -1;
}
if(screen->damaged.start_row != -1) {
if(screen->callbacks && screen->callbacks->damage)
(*screen->callbacks->damage)(screen->damaged, screen->cbdata);
screen->damaged.start_row = -1;
}
}
void vterm_screen_set_damage_merge(VTermScreen *screen, VTermDamageSize size)
{
vterm_screen_flush_damage(screen);
screen->damage_merge = size;
}
static int attrs_differ(VTermAttrMask attrs, ScreenCell *a, ScreenCell *b)
{
if((attrs & VTERM_ATTR_BOLD_MASK) && (a->pen.bold != b->pen.bold))
return 1;
if((attrs & VTERM_ATTR_UNDERLINE_MASK) && (a->pen.underline != b->pen.underline))
return 1;
if((attrs & VTERM_ATTR_ITALIC_MASK) && (a->pen.italic != b->pen.italic))
return 1;
if((attrs & VTERM_ATTR_BLINK_MASK) && (a->pen.blink != b->pen.blink))
return 1;
if((attrs & VTERM_ATTR_REVERSE_MASK) && (a->pen.reverse != b->pen.reverse))
return 1;
if((attrs & VTERM_ATTR_STRIKE_MASK) && (a->pen.strike != b->pen.strike))
return 1;
if((attrs & VTERM_ATTR_FONT_MASK) && (a->pen.font != b->pen.font))
return 1;
if((attrs & VTERM_ATTR_FOREGROUND_MASK) && !vterm_color_equal(a->pen.fg, b->pen.fg))
return 1;
if((attrs & VTERM_ATTR_BACKGROUND_MASK) && !vterm_color_equal(a->pen.bg, b->pen.bg))
return 1;
return 0;
}
int vterm_screen_get_attrs_extent(const VTermScreen *screen, VTermRect *extent, VTermPos pos, VTermAttrMask attrs)
{
int col;
ScreenCell *target = getcell(screen, pos.row, pos.col);
// TODO: bounds check
extent->start_row = pos.row;
extent->end_row = pos.row + 1;
if(extent->start_col < 0)
extent->start_col = 0;
if(extent->end_col < 0)
extent->end_col = screen->cols;
for(col = pos.col - 1; col >= extent->start_col; col--)
if(attrs_differ(attrs, target, getcell(screen, pos.row, col)))
break;
extent->start_col = col + 1;
for(col = pos.col + 1; col < extent->end_col; col++)
if(attrs_differ(attrs, target, getcell(screen, pos.row, col)))
break;
extent->end_col = col - 1;
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_528_1 |
crossvul-cpp_data_bad_528_0 | #include "vterm_internal.h"
#include <stdio.h>
#include <string.h>
#define strneq(a,b,n) (strncmp(a,b,n)==0)
#if defined(DEBUG) && DEBUG > 1
# define DEBUG_GLYPH_COMBINE
#endif
static int on_resize(int rows, int cols, void *user);
/* Some convenient wrappers to make callback functions easier */
static void putglyph(VTermState *state, const uint32_t chars[], int width, VTermPos pos)
{
VTermGlyphInfo info;
info.chars = chars;
info.width = width;
info.protected_cell = state->protected_cell;
info.dwl = state->lineinfo[pos.row].doublewidth;
info.dhl = state->lineinfo[pos.row].doubleheight;
if(state->callbacks && state->callbacks->putglyph)
if((*state->callbacks->putglyph)(&info, pos, state->cbdata))
return;
DEBUG_LOG3("libvterm: Unhandled putglyph U+%04x at (%d,%d)\n", chars[0], pos.col, pos.row);
}
static void updatecursor(VTermState *state, VTermPos *oldpos, int cancel_phantom)
{
if(state->pos.col == oldpos->col && state->pos.row == oldpos->row)
return;
if(cancel_phantom)
state->at_phantom = 0;
if(state->callbacks && state->callbacks->movecursor)
if((*state->callbacks->movecursor)(state->pos, *oldpos, state->mode.cursor_visible, state->cbdata))
return;
}
static void erase(VTermState *state, VTermRect rect, int selective)
{
if(state->callbacks && state->callbacks->erase)
if((*state->callbacks->erase)(rect, selective, state->cbdata))
return;
}
static VTermState *vterm_state_new(VTerm *vt)
{
VTermState *state = vterm_allocator_malloc(vt, sizeof(VTermState));
state->vt = vt;
state->rows = vt->rows;
state->cols = vt->cols;
state->mouse_col = 0;
state->mouse_row = 0;
state->mouse_buttons = 0;
state->mouse_protocol = MOUSE_X10;
state->callbacks = NULL;
state->cbdata = NULL;
vterm_state_newpen(state);
state->bold_is_highbright = 0;
return state;
}
INTERNAL void vterm_state_free(VTermState *state)
{
vterm_allocator_free(state->vt, state->tabstops);
vterm_allocator_free(state->vt, state->lineinfo);
vterm_allocator_free(state->vt, state->combine_chars);
vterm_allocator_free(state->vt, state);
}
static void scroll(VTermState *state, VTermRect rect, int downward, int rightward)
{
int rows;
int cols;
if(!downward && !rightward)
return;
rows = rect.end_row - rect.start_row;
if(downward > rows)
downward = rows;
else if(downward < -rows)
downward = -rows;
cols = rect.end_col - rect.start_col;
if(rightward > cols)
rightward = cols;
else if(rightward < -cols)
rightward = -cols;
// Update lineinfo if full line
if(rect.start_col == 0 && rect.end_col == state->cols && rightward == 0) {
int height = rect.end_row - rect.start_row - abs(downward);
if(downward > 0)
memmove(state->lineinfo + rect.start_row,
state->lineinfo + rect.start_row + downward,
height * sizeof(state->lineinfo[0]));
else
memmove(state->lineinfo + rect.start_row - downward,
state->lineinfo + rect.start_row,
height * sizeof(state->lineinfo[0]));
}
if(state->callbacks && state->callbacks->scrollrect)
if((*state->callbacks->scrollrect)(rect, downward, rightward, state->cbdata))
return;
if(state->callbacks)
vterm_scroll_rect(rect, downward, rightward,
state->callbacks->moverect, state->callbacks->erase, state->cbdata);
}
static void linefeed(VTermState *state)
{
if(state->pos.row == SCROLLREGION_BOTTOM(state) - 1) {
VTermRect rect;
rect.start_row = state->scrollregion_top;
rect.end_row = SCROLLREGION_BOTTOM(state);
rect.start_col = SCROLLREGION_LEFT(state);
rect.end_col = SCROLLREGION_RIGHT(state);
scroll(state, rect, 1, 0);
}
else if(state->pos.row < state->rows-1)
state->pos.row++;
}
static void grow_combine_buffer(VTermState *state)
{
size_t new_size = state->combine_chars_size * 2;
uint32_t *new_chars = vterm_allocator_malloc(state->vt, new_size * sizeof(new_chars[0]));
memcpy(new_chars, state->combine_chars, state->combine_chars_size * sizeof(new_chars[0]));
vterm_allocator_free(state->vt, state->combine_chars);
state->combine_chars = new_chars;
state->combine_chars_size = new_size;
}
static void set_col_tabstop(VTermState *state, int col)
{
unsigned char mask = 1 << (col & 7);
state->tabstops[col >> 3] |= mask;
}
static void clear_col_tabstop(VTermState *state, int col)
{
unsigned char mask = 1 << (col & 7);
state->tabstops[col >> 3] &= ~mask;
}
static int is_col_tabstop(VTermState *state, int col)
{
unsigned char mask = 1 << (col & 7);
return state->tabstops[col >> 3] & mask;
}
static int is_cursor_in_scrollregion(const VTermState *state)
{
if(state->pos.row < state->scrollregion_top ||
state->pos.row >= SCROLLREGION_BOTTOM(state))
return 0;
if(state->pos.col < SCROLLREGION_LEFT(state) ||
state->pos.col >= SCROLLREGION_RIGHT(state))
return 0;
return 1;
}
static void tab(VTermState *state, int count, int direction)
{
while(count > 0) {
if(direction > 0) {
if(state->pos.col >= THISROWWIDTH(state)-1)
return;
state->pos.col++;
}
else if(direction < 0) {
if(state->pos.col < 1)
return;
state->pos.col--;
}
if(is_col_tabstop(state, state->pos.col))
count--;
}
}
#define NO_FORCE 0
#define FORCE 1
#define DWL_OFF 0
#define DWL_ON 1
#define DHL_OFF 0
#define DHL_TOP 1
#define DHL_BOTTOM 2
static void set_lineinfo(VTermState *state, int row, int force, int dwl, int dhl)
{
VTermLineInfo info = state->lineinfo[row];
if(dwl == DWL_OFF)
info.doublewidth = DWL_OFF;
else if(dwl == DWL_ON)
info.doublewidth = DWL_ON;
// else -1 to ignore
if(dhl == DHL_OFF)
info.doubleheight = DHL_OFF;
else if(dhl == DHL_TOP)
info.doubleheight = DHL_TOP;
else if(dhl == DHL_BOTTOM)
info.doubleheight = DHL_BOTTOM;
if((state->callbacks &&
state->callbacks->setlineinfo &&
(*state->callbacks->setlineinfo)(row, &info, state->lineinfo + row, state->cbdata))
|| force)
state->lineinfo[row] = info;
}
static int on_text(const char bytes[], size_t len, void *user)
{
VTermState *state = user;
uint32_t *codepoints;
int npoints = 0;
size_t eaten = 0;
VTermEncodingInstance *encoding;
int i = 0;
VTermPos oldpos = state->pos;
// We'll have at most len codepoints, plus one from a previous incomplete
// sequence.
codepoints = vterm_allocator_malloc(state->vt, (len + 1) * sizeof(uint32_t));
encoding =
state->gsingle_set ? &state->encoding[state->gsingle_set] :
!(bytes[eaten] & 0x80) ? &state->encoding[state->gl_set] :
state->vt->mode.utf8 ? &state->encoding_utf8 :
&state->encoding[state->gr_set];
(*encoding->enc->decode)(encoding->enc, encoding->data,
codepoints, &npoints, state->gsingle_set ? 1 : (int)len,
bytes, &eaten, len);
/* There's a chance an encoding (e.g. UTF-8) hasn't found enough bytes yet
* for even a single codepoint
*/
if(!npoints)
{
vterm_allocator_free(state->vt, codepoints);
return (int)eaten;
}
if(state->gsingle_set && npoints)
state->gsingle_set = 0;
/* This is a combining char. that needs to be merged with the previous
* glyph output */
if(vterm_unicode_is_combining(codepoints[i])) {
/* See if the cursor has moved since */
if(state->pos.row == state->combine_pos.row && state->pos.col == state->combine_pos.col + state->combine_width) {
#ifdef DEBUG_GLYPH_COMBINE
int printpos;
printf("DEBUG: COMBINING SPLIT GLYPH of chars {");
for(printpos = 0; state->combine_chars[printpos]; printpos++)
printf("U+%04x ", state->combine_chars[printpos]);
printf("} + {");
#endif
/* Find where we need to append these combining chars */
int saved_i = 0;
while(state->combine_chars[saved_i])
saved_i++;
/* Add extra ones */
while(i < npoints && vterm_unicode_is_combining(codepoints[i])) {
if(saved_i >= (int)state->combine_chars_size)
grow_combine_buffer(state);
state->combine_chars[saved_i++] = codepoints[i++];
}
if(saved_i >= (int)state->combine_chars_size)
grow_combine_buffer(state);
state->combine_chars[saved_i] = 0;
#ifdef DEBUG_GLYPH_COMBINE
for(; state->combine_chars[printpos]; printpos++)
printf("U+%04x ", state->combine_chars[printpos]);
printf("}\n");
#endif
/* Now render it */
putglyph(state, state->combine_chars, state->combine_width, state->combine_pos);
}
else {
DEBUG_LOG("libvterm: TODO: Skip over split char+combining\n");
}
}
for(; i < npoints; i++) {
// Try to find combining characters following this
int glyph_starts = i;
int glyph_ends;
int width = 0;
uint32_t *chars;
for(glyph_ends = i + 1; glyph_ends < npoints; glyph_ends++)
if(!vterm_unicode_is_combining(codepoints[glyph_ends]))
break;
chars = vterm_allocator_malloc(state->vt, (glyph_ends - glyph_starts + 1) * sizeof(uint32_t));
for( ; i < glyph_ends; i++) {
int this_width;
chars[i - glyph_starts] = codepoints[i];
this_width = vterm_unicode_width(codepoints[i]);
#ifdef DEBUG
if(this_width < 0) {
fprintf(stderr, "Text with negative-width codepoint U+%04x\n", codepoints[i]);
abort();
}
#endif
width += this_width;
}
chars[glyph_ends - glyph_starts] = 0;
i--;
#ifdef DEBUG_GLYPH_COMBINE
int printpos;
printf("DEBUG: COMBINED GLYPH of %d chars {", glyph_ends - glyph_starts);
for(printpos = 0; printpos < glyph_ends - glyph_starts; printpos++)
printf("U+%04x ", chars[printpos]);
printf("}, onscreen width %d\n", width);
#endif
if(state->at_phantom || state->pos.col + width > THISROWWIDTH(state)) {
linefeed(state);
state->pos.col = 0;
state->at_phantom = 0;
}
if(state->mode.insert) {
/* TODO: This will be a little inefficient for large bodies of text, as
* it'll have to 'ICH' effectively before every glyph. We should scan
* ahead and ICH as many times as required
*/
VTermRect rect;
rect.start_row = state->pos.row;
rect.end_row = state->pos.row + 1;
rect.start_col = state->pos.col;
rect.end_col = THISROWWIDTH(state);
scroll(state, rect, 0, -1);
}
putglyph(state, chars, width, state->pos);
if(i == npoints - 1) {
/* End of the buffer. Save the chars in case we have to combine with
* more on the next call */
int save_i;
for(save_i = 0; chars[save_i]; save_i++) {
if(save_i >= (int)state->combine_chars_size)
grow_combine_buffer(state);
state->combine_chars[save_i] = chars[save_i];
}
if(save_i >= (int)state->combine_chars_size)
grow_combine_buffer(state);
state->combine_chars[save_i] = 0;
state->combine_width = width;
state->combine_pos = state->pos;
}
if(state->pos.col + width >= THISROWWIDTH(state)) {
if(state->mode.autowrap)
state->at_phantom = 1;
}
else {
state->pos.col += width;
}
vterm_allocator_free(state->vt, chars);
}
updatecursor(state, &oldpos, 0);
#ifdef DEBUG
if(state->pos.row < 0 || state->pos.row >= state->rows ||
state->pos.col < 0 || state->pos.col >= state->cols) {
fprintf(stderr, "Position out of bounds after text: (%d,%d)\n",
state->pos.row, state->pos.col);
abort();
}
#endif
vterm_allocator_free(state->vt, codepoints);
return (int)eaten;
}
static int on_control(unsigned char control, void *user)
{
VTermState *state = user;
VTermPos oldpos = state->pos;
switch(control) {
case 0x07: // BEL - ECMA-48 8.3.3
if(state->callbacks && state->callbacks->bell)
(*state->callbacks->bell)(state->cbdata);
break;
case 0x08: // BS - ECMA-48 8.3.5
if(state->pos.col > 0)
state->pos.col--;
break;
case 0x09: // HT - ECMA-48 8.3.60
tab(state, 1, +1);
break;
case 0x0a: // LF - ECMA-48 8.3.74
case 0x0b: // VT
case 0x0c: // FF
linefeed(state);
if(state->mode.newline)
state->pos.col = 0;
break;
case 0x0d: // CR - ECMA-48 8.3.15
state->pos.col = 0;
break;
case 0x0e: // LS1 - ECMA-48 8.3.76
state->gl_set = 1;
break;
case 0x0f: // LS0 - ECMA-48 8.3.75
state->gl_set = 0;
break;
case 0x84: // IND - DEPRECATED but implemented for completeness
linefeed(state);
break;
case 0x85: // NEL - ECMA-48 8.3.86
linefeed(state);
state->pos.col = 0;
break;
case 0x88: // HTS - ECMA-48 8.3.62
set_col_tabstop(state, state->pos.col);
break;
case 0x8d: // RI - ECMA-48 8.3.104
if(state->pos.row == state->scrollregion_top) {
VTermRect rect;
rect.start_row = state->scrollregion_top;
rect.end_row = SCROLLREGION_BOTTOM(state);
rect.start_col = SCROLLREGION_LEFT(state);
rect.end_col = SCROLLREGION_RIGHT(state);
scroll(state, rect, -1, 0);
}
else if(state->pos.row > 0)
state->pos.row--;
break;
case 0x8e: // SS2 - ECMA-48 8.3.141
state->gsingle_set = 2;
break;
case 0x8f: // SS3 - ECMA-48 8.3.142
state->gsingle_set = 3;
break;
default:
if(state->fallbacks && state->fallbacks->control)
if((*state->fallbacks->control)(control, state->fbdata))
return 1;
return 0;
}
updatecursor(state, &oldpos, 1);
#ifdef DEBUG
if(state->pos.row < 0 || state->pos.row >= state->rows ||
state->pos.col < 0 || state->pos.col >= state->cols) {
fprintf(stderr, "Position out of bounds after Ctrl %02x: (%d,%d)\n",
control, state->pos.row, state->pos.col);
abort();
}
#endif
return 1;
}
static int settermprop_bool(VTermState *state, VTermProp prop, int v)
{
VTermValue val;
val.boolean = v;
return vterm_state_set_termprop(state, prop, &val);
}
static int settermprop_int(VTermState *state, VTermProp prop, int v)
{
VTermValue val;
val.number = v;
return vterm_state_set_termprop(state, prop, &val);
}
static int settermprop_string(VTermState *state, VTermProp prop, const char *str, size_t len)
{
char *strvalue;
int r;
VTermValue val;
strvalue = vterm_allocator_malloc(state->vt, (len+1) * sizeof(char));
strncpy(strvalue, str, len);
strvalue[len] = 0;
val.string = strvalue;
r = vterm_state_set_termprop(state, prop, &val);
vterm_allocator_free(state->vt, strvalue);
return r;
}
static void savecursor(VTermState *state, int save)
{
if(save) {
state->saved.pos = state->pos;
state->saved.mode.cursor_visible = state->mode.cursor_visible;
state->saved.mode.cursor_blink = state->mode.cursor_blink;
state->saved.mode.cursor_shape = state->mode.cursor_shape;
vterm_state_savepen(state, 1);
}
else {
VTermPos oldpos = state->pos;
state->pos = state->saved.pos;
settermprop_bool(state, VTERM_PROP_CURSORVISIBLE, state->saved.mode.cursor_visible);
settermprop_bool(state, VTERM_PROP_CURSORBLINK, state->saved.mode.cursor_blink);
settermprop_int (state, VTERM_PROP_CURSORSHAPE, state->saved.mode.cursor_shape);
vterm_state_savepen(state, 0);
updatecursor(state, &oldpos, 1);
}
}
static int on_escape(const char *bytes, size_t len, void *user)
{
VTermState *state = user;
/* Easier to decode this from the first byte, even though the final
* byte terminates it
*/
switch(bytes[0]) {
case ' ':
if(len != 2)
return 0;
switch(bytes[1]) {
case 'F': // S7C1T
state->vt->mode.ctrl8bit = 0;
break;
case 'G': // S8C1T
state->vt->mode.ctrl8bit = 1;
break;
default:
return 0;
}
return 2;
case '#':
if(len != 2)
return 0;
switch(bytes[1]) {
case '3': // DECDHL top
if(state->mode.leftrightmargin)
break;
set_lineinfo(state, state->pos.row, NO_FORCE, DWL_ON, DHL_TOP);
break;
case '4': // DECDHL bottom
if(state->mode.leftrightmargin)
break;
set_lineinfo(state, state->pos.row, NO_FORCE, DWL_ON, DHL_BOTTOM);
break;
case '5': // DECSWL
if(state->mode.leftrightmargin)
break;
set_lineinfo(state, state->pos.row, NO_FORCE, DWL_OFF, DHL_OFF);
break;
case '6': // DECDWL
if(state->mode.leftrightmargin)
break;
set_lineinfo(state, state->pos.row, NO_FORCE, DWL_ON, DHL_OFF);
break;
case '8': // DECALN
{
VTermPos pos;
uint32_t E[] = { 'E', 0 };
for(pos.row = 0; pos.row < state->rows; pos.row++)
for(pos.col = 0; pos.col < ROWWIDTH(state, pos.row); pos.col++)
putglyph(state, E, 1, pos);
break;
}
default:
return 0;
}
return 2;
case '(': case ')': case '*': case '+': // SCS
if(len != 2)
return 0;
{
int setnum = bytes[0] - 0x28;
VTermEncoding *newenc = vterm_lookup_encoding(ENC_SINGLE_94, bytes[1]);
if(newenc) {
state->encoding[setnum].enc = newenc;
if(newenc->init)
(*newenc->init)(newenc, state->encoding[setnum].data);
}
}
return 2;
case '7': // DECSC
savecursor(state, 1);
return 1;
case '8': // DECRC
savecursor(state, 0);
return 1;
case '<': // Ignored by VT100. Used in VT52 mode to switch up to VT100
return 1;
case '=': // DECKPAM
state->mode.keypad = 1;
return 1;
case '>': // DECKPNM
state->mode.keypad = 0;
return 1;
case 'c': // RIS - ECMA-48 8.3.105
{
VTermPos oldpos = state->pos;
vterm_state_reset(state, 1);
if(state->callbacks && state->callbacks->movecursor)
(*state->callbacks->movecursor)(state->pos, oldpos, state->mode.cursor_visible, state->cbdata);
return 1;
}
case 'n': // LS2 - ECMA-48 8.3.78
state->gl_set = 2;
return 1;
case 'o': // LS3 - ECMA-48 8.3.80
state->gl_set = 3;
return 1;
case '~': // LS1R - ECMA-48 8.3.77
state->gr_set = 1;
return 1;
case '}': // LS2R - ECMA-48 8.3.79
state->gr_set = 2;
return 1;
case '|': // LS3R - ECMA-48 8.3.81
state->gr_set = 3;
return 1;
default:
return 0;
}
}
static void set_mode(VTermState *state, int num, int val)
{
switch(num) {
case 4: // IRM - ECMA-48 7.2.10
state->mode.insert = val;
break;
case 20: // LNM - ANSI X3.4-1977
state->mode.newline = val;
break;
default:
DEBUG_LOG1("libvterm: Unknown mode %d\n", num);
return;
}
}
static void set_dec_mode(VTermState *state, int num, int val)
{
switch(num) {
case 1:
state->mode.cursor = val;
break;
case 5: // DECSCNM - screen mode
settermprop_bool(state, VTERM_PROP_REVERSE, val);
break;
case 6: // DECOM - origin mode
{
VTermPos oldpos = state->pos;
state->mode.origin = val;
state->pos.row = state->mode.origin ? state->scrollregion_top : 0;
state->pos.col = state->mode.origin ? SCROLLREGION_LEFT(state) : 0;
updatecursor(state, &oldpos, 1);
}
break;
case 7:
state->mode.autowrap = val;
break;
case 12:
settermprop_bool(state, VTERM_PROP_CURSORBLINK, val);
break;
case 25:
settermprop_bool(state, VTERM_PROP_CURSORVISIBLE, val);
break;
case 69: // DECVSSM - vertical split screen mode
// DECLRMM - left/right margin mode
state->mode.leftrightmargin = val;
if(val) {
int row;
// Setting DECVSSM must clear doublewidth/doubleheight state of every line
for(row = 0; row < state->rows; row++)
set_lineinfo(state, row, FORCE, DWL_OFF, DHL_OFF);
}
break;
case 1000:
case 1002:
case 1003:
settermprop_int(state, VTERM_PROP_MOUSE,
!val ? VTERM_PROP_MOUSE_NONE :
(num == 1000) ? VTERM_PROP_MOUSE_CLICK :
(num == 1002) ? VTERM_PROP_MOUSE_DRAG :
VTERM_PROP_MOUSE_MOVE);
break;
case 1004:
state->mode.report_focus = val;
break;
case 1005:
state->mouse_protocol = val ? MOUSE_UTF8 : MOUSE_X10;
break;
case 1006:
state->mouse_protocol = val ? MOUSE_SGR : MOUSE_X10;
break;
case 1015:
state->mouse_protocol = val ? MOUSE_RXVT : MOUSE_X10;
break;
case 1047:
settermprop_bool(state, VTERM_PROP_ALTSCREEN, val);
break;
case 1048:
savecursor(state, val);
break;
case 1049:
settermprop_bool(state, VTERM_PROP_ALTSCREEN, val);
savecursor(state, val);
break;
case 2004:
state->mode.bracketpaste = val;
break;
default:
DEBUG_LOG1("libvterm: Unknown DEC mode %d\n", num);
return;
}
}
static void request_dec_mode(VTermState *state, int num)
{
int reply;
switch(num) {
case 1:
reply = state->mode.cursor;
break;
case 5:
reply = state->mode.screen;
break;
case 6:
reply = state->mode.origin;
break;
case 7:
reply = state->mode.autowrap;
break;
case 12:
reply = state->mode.cursor_blink;
break;
case 25:
reply = state->mode.cursor_visible;
break;
case 69:
reply = state->mode.leftrightmargin;
break;
case 1000:
reply = state->mouse_flags == MOUSE_WANT_CLICK;
break;
case 1002:
reply = state->mouse_flags == (MOUSE_WANT_CLICK|MOUSE_WANT_DRAG);
break;
case 1003:
reply = state->mouse_flags == (MOUSE_WANT_CLICK|MOUSE_WANT_MOVE);
break;
case 1004:
reply = state->mode.report_focus;
break;
case 1005:
reply = state->mouse_protocol == MOUSE_UTF8;
break;
case 1006:
reply = state->mouse_protocol == MOUSE_SGR;
break;
case 1015:
reply = state->mouse_protocol == MOUSE_RXVT;
break;
case 1047:
reply = state->mode.alt_screen;
break;
case 2004:
reply = state->mode.bracketpaste;
break;
default:
vterm_push_output_sprintf_ctrl(state->vt, C1_CSI, "?%d;%d$y", num, 0);
return;
}
vterm_push_output_sprintf_ctrl(state->vt, C1_CSI, "?%d;%d$y", num, reply ? 1 : 2);
}
static int on_csi(const char *leader, const long args[], int argcount, const char *intermed, char command, void *user)
{
VTermState *state = user;
int leader_byte = 0;
int intermed_byte = 0;
VTermPos oldpos = state->pos;
/* Some temporaries for later code */
int count, val;
int row, col;
VTermRect rect;
int selective;
if(leader && leader[0]) {
if(leader[1]) // longer than 1 char
return 0;
switch(leader[0]) {
case '?':
case '>':
leader_byte = leader[0];
break;
default:
return 0;
}
}
if(intermed && intermed[0]) {
if(intermed[1]) // longer than 1 char
return 0;
switch(intermed[0]) {
case ' ':
case '"':
case '$':
case '\'':
intermed_byte = intermed[0];
break;
default:
return 0;
}
}
oldpos = state->pos;
#define LBOUND(v,min) if((v) < (min)) (v) = (min)
#define UBOUND(v,max) if((v) > (max)) (v) = (max)
#define LEADER(l,b) ((l << 8) | b)
#define INTERMED(i,b) ((i << 16) | b)
switch(intermed_byte << 16 | leader_byte << 8 | command) {
case 0x40: // ICH - ECMA-48 8.3.64
count = CSI_ARG_COUNT(args[0]);
if(!is_cursor_in_scrollregion(state))
break;
rect.start_row = state->pos.row;
rect.end_row = state->pos.row + 1;
rect.start_col = state->pos.col;
if(state->mode.leftrightmargin)
rect.end_col = SCROLLREGION_RIGHT(state);
else
rect.end_col = THISROWWIDTH(state);
scroll(state, rect, 0, -count);
break;
case 0x41: // CUU - ECMA-48 8.3.22
count = CSI_ARG_COUNT(args[0]);
state->pos.row -= count;
state->at_phantom = 0;
break;
case 0x42: // CUD - ECMA-48 8.3.19
count = CSI_ARG_COUNT(args[0]);
state->pos.row += count;
state->at_phantom = 0;
break;
case 0x43: // CUF - ECMA-48 8.3.20
count = CSI_ARG_COUNT(args[0]);
state->pos.col += count;
state->at_phantom = 0;
break;
case 0x44: // CUB - ECMA-48 8.3.18
count = CSI_ARG_COUNT(args[0]);
state->pos.col -= count;
state->at_phantom = 0;
break;
case 0x45: // CNL - ECMA-48 8.3.12
count = CSI_ARG_COUNT(args[0]);
state->pos.col = 0;
state->pos.row += count;
state->at_phantom = 0;
break;
case 0x46: // CPL - ECMA-48 8.3.13
count = CSI_ARG_COUNT(args[0]);
state->pos.col = 0;
state->pos.row -= count;
state->at_phantom = 0;
break;
case 0x47: // CHA - ECMA-48 8.3.9
val = CSI_ARG_OR(args[0], 1);
state->pos.col = val-1;
state->at_phantom = 0;
break;
case 0x48: // CUP - ECMA-48 8.3.21
row = CSI_ARG_OR(args[0], 1);
col = argcount < 2 || CSI_ARG_IS_MISSING(args[1]) ? 1 : CSI_ARG(args[1]);
// zero-based
state->pos.row = row-1;
state->pos.col = col-1;
if(state->mode.origin) {
state->pos.row += state->scrollregion_top;
state->pos.col += SCROLLREGION_LEFT(state);
}
state->at_phantom = 0;
break;
case 0x49: // CHT - ECMA-48 8.3.10
count = CSI_ARG_COUNT(args[0]);
tab(state, count, +1);
break;
case 0x4a: // ED - ECMA-48 8.3.39
case LEADER('?', 0x4a): // DECSED - Selective Erase in Display
selective = (leader_byte == '?');
switch(CSI_ARG(args[0])) {
case CSI_ARG_MISSING:
case 0:
rect.start_row = state->pos.row; rect.end_row = state->pos.row + 1;
rect.start_col = state->pos.col; rect.end_col = state->cols;
if(rect.end_col > rect.start_col)
erase(state, rect, selective);
rect.start_row = state->pos.row + 1; rect.end_row = state->rows;
rect.start_col = 0;
for(row = rect.start_row; row < rect.end_row; row++)
set_lineinfo(state, row, FORCE, DWL_OFF, DHL_OFF);
if(rect.end_row > rect.start_row)
erase(state, rect, selective);
break;
case 1:
rect.start_row = 0; rect.end_row = state->pos.row;
rect.start_col = 0; rect.end_col = state->cols;
for(row = rect.start_row; row < rect.end_row; row++)
set_lineinfo(state, row, FORCE, DWL_OFF, DHL_OFF);
if(rect.end_col > rect.start_col)
erase(state, rect, selective);
rect.start_row = state->pos.row; rect.end_row = state->pos.row + 1;
rect.end_col = state->pos.col + 1;
if(rect.end_row > rect.start_row)
erase(state, rect, selective);
break;
case 2:
rect.start_row = 0; rect.end_row = state->rows;
rect.start_col = 0; rect.end_col = state->cols;
for(row = rect.start_row; row < rect.end_row; row++)
set_lineinfo(state, row, FORCE, DWL_OFF, DHL_OFF);
erase(state, rect, selective);
break;
}
break;
case 0x4b: // EL - ECMA-48 8.3.41
case LEADER('?', 0x4b): // DECSEL - Selective Erase in Line
selective = (leader_byte == '?');
rect.start_row = state->pos.row;
rect.end_row = state->pos.row + 1;
switch(CSI_ARG(args[0])) {
case CSI_ARG_MISSING:
case 0:
rect.start_col = state->pos.col; rect.end_col = THISROWWIDTH(state); break;
case 1:
rect.start_col = 0; rect.end_col = state->pos.col + 1; break;
case 2:
rect.start_col = 0; rect.end_col = THISROWWIDTH(state); break;
default:
return 0;
}
if(rect.end_col > rect.start_col)
erase(state, rect, selective);
break;
case 0x4c: // IL - ECMA-48 8.3.67
count = CSI_ARG_COUNT(args[0]);
if(!is_cursor_in_scrollregion(state))
break;
rect.start_row = state->pos.row;
rect.end_row = SCROLLREGION_BOTTOM(state);
rect.start_col = SCROLLREGION_LEFT(state);
rect.end_col = SCROLLREGION_RIGHT(state);
scroll(state, rect, -count, 0);
break;
case 0x4d: // DL - ECMA-48 8.3.32
count = CSI_ARG_COUNT(args[0]);
if(!is_cursor_in_scrollregion(state))
break;
rect.start_row = state->pos.row;
rect.end_row = SCROLLREGION_BOTTOM(state);
rect.start_col = SCROLLREGION_LEFT(state);
rect.end_col = SCROLLREGION_RIGHT(state);
scroll(state, rect, count, 0);
break;
case 0x50: // DCH - ECMA-48 8.3.26
count = CSI_ARG_COUNT(args[0]);
if(!is_cursor_in_scrollregion(state))
break;
rect.start_row = state->pos.row;
rect.end_row = state->pos.row + 1;
rect.start_col = state->pos.col;
if(state->mode.leftrightmargin)
rect.end_col = SCROLLREGION_RIGHT(state);
else
rect.end_col = THISROWWIDTH(state);
scroll(state, rect, 0, count);
break;
case 0x53: // SU - ECMA-48 8.3.147
count = CSI_ARG_COUNT(args[0]);
rect.start_row = state->scrollregion_top;
rect.end_row = SCROLLREGION_BOTTOM(state);
rect.start_col = SCROLLREGION_LEFT(state);
rect.end_col = SCROLLREGION_RIGHT(state);
scroll(state, rect, count, 0);
break;
case 0x54: // SD - ECMA-48 8.3.113
count = CSI_ARG_COUNT(args[0]);
rect.start_row = state->scrollregion_top;
rect.end_row = SCROLLREGION_BOTTOM(state);
rect.start_col = SCROLLREGION_LEFT(state);
rect.end_col = SCROLLREGION_RIGHT(state);
scroll(state, rect, -count, 0);
break;
case 0x58: // ECH - ECMA-48 8.3.38
count = CSI_ARG_COUNT(args[0]);
rect.start_row = state->pos.row;
rect.end_row = state->pos.row + 1;
rect.start_col = state->pos.col;
rect.end_col = state->pos.col + count;
UBOUND(rect.end_col, THISROWWIDTH(state));
erase(state, rect, 0);
break;
case 0x5a: // CBT - ECMA-48 8.3.7
count = CSI_ARG_COUNT(args[0]);
tab(state, count, -1);
break;
case 0x60: // HPA - ECMA-48 8.3.57
col = CSI_ARG_OR(args[0], 1);
state->pos.col = col-1;
state->at_phantom = 0;
break;
case 0x61: // HPR - ECMA-48 8.3.59
count = CSI_ARG_COUNT(args[0]);
state->pos.col += count;
state->at_phantom = 0;
break;
case 0x63: // DA - ECMA-48 8.3.24
val = CSI_ARG_OR(args[0], 0);
if(val == 0)
// DEC VT100 response
vterm_push_output_sprintf_ctrl(state->vt, C1_CSI, "?1;2c");
break;
case LEADER('>', 0x63): // DEC secondary Device Attributes
// This returns xterm version number 100.
vterm_push_output_sprintf_ctrl(state->vt, C1_CSI, ">%d;%d;%dc", 0, 100, 0);
break;
case 0x64: // VPA - ECMA-48 8.3.158
row = CSI_ARG_OR(args[0], 1);
state->pos.row = row-1;
if(state->mode.origin)
state->pos.row += state->scrollregion_top;
state->at_phantom = 0;
break;
case 0x65: // VPR - ECMA-48 8.3.160
count = CSI_ARG_COUNT(args[0]);
state->pos.row += count;
state->at_phantom = 0;
break;
case 0x66: // HVP - ECMA-48 8.3.63
row = CSI_ARG_OR(args[0], 1);
col = argcount < 2 || CSI_ARG_IS_MISSING(args[1]) ? 1 : CSI_ARG(args[1]);
// zero-based
state->pos.row = row-1;
state->pos.col = col-1;
if(state->mode.origin) {
state->pos.row += state->scrollregion_top;
state->pos.col += SCROLLREGION_LEFT(state);
}
state->at_phantom = 0;
break;
case 0x67: // TBC - ECMA-48 8.3.154
val = CSI_ARG_OR(args[0], 0);
switch(val) {
case 0:
clear_col_tabstop(state, state->pos.col);
break;
case 3:
case 5:
for(col = 0; col < state->cols; col++)
clear_col_tabstop(state, col);
break;
case 1:
case 2:
case 4:
break;
/* TODO: 1, 2 and 4 aren't meaningful yet without line tab stops */
default:
return 0;
}
break;
case 0x68: // SM - ECMA-48 8.3.125
if(!CSI_ARG_IS_MISSING(args[0]))
set_mode(state, CSI_ARG(args[0]), 1);
break;
case LEADER('?', 0x68): // DEC private mode set
if(!CSI_ARG_IS_MISSING(args[0]))
set_dec_mode(state, CSI_ARG(args[0]), 1);
break;
case 0x6a: // HPB - ECMA-48 8.3.58
count = CSI_ARG_COUNT(args[0]);
state->pos.col -= count;
state->at_phantom = 0;
break;
case 0x6b: // VPB - ECMA-48 8.3.159
count = CSI_ARG_COUNT(args[0]);
state->pos.row -= count;
state->at_phantom = 0;
break;
case 0x6c: // RM - ECMA-48 8.3.106
if(!CSI_ARG_IS_MISSING(args[0]))
set_mode(state, CSI_ARG(args[0]), 0);
break;
case LEADER('?', 0x6c): // DEC private mode reset
if(!CSI_ARG_IS_MISSING(args[0]))
set_dec_mode(state, CSI_ARG(args[0]), 0);
break;
case 0x6d: // SGR - ECMA-48 8.3.117
vterm_state_setpen(state, args, argcount);
break;
case 0x6e: // DSR - ECMA-48 8.3.35
case LEADER('?', 0x6e): // DECDSR
val = CSI_ARG_OR(args[0], 0);
{
char *qmark = (leader_byte == '?') ? "?" : "";
switch(val) {
case 0: case 1: case 2: case 3: case 4:
// ignore - these are replies
break;
case 5:
vterm_push_output_sprintf_ctrl(state->vt, C1_CSI, "%s0n", qmark);
break;
case 6: // CPR - cursor position report
vterm_push_output_sprintf_ctrl(state->vt, C1_CSI, "%s%d;%dR", qmark, state->pos.row + 1, state->pos.col + 1);
break;
}
}
break;
case LEADER('!', 0x70): // DECSTR - DEC soft terminal reset
vterm_state_reset(state, 0);
break;
case LEADER('?', INTERMED('$', 0x70)):
request_dec_mode(state, CSI_ARG(args[0]));
break;
case INTERMED(' ', 0x71): // DECSCUSR - DEC set cursor shape
val = CSI_ARG_OR(args[0], 1);
switch(val) {
case 0: case 1:
settermprop_bool(state, VTERM_PROP_CURSORBLINK, 1);
settermprop_int (state, VTERM_PROP_CURSORSHAPE, VTERM_PROP_CURSORSHAPE_BLOCK);
break;
case 2:
settermprop_bool(state, VTERM_PROP_CURSORBLINK, 0);
settermprop_int (state, VTERM_PROP_CURSORSHAPE, VTERM_PROP_CURSORSHAPE_BLOCK);
break;
case 3:
settermprop_bool(state, VTERM_PROP_CURSORBLINK, 1);
settermprop_int (state, VTERM_PROP_CURSORSHAPE, VTERM_PROP_CURSORSHAPE_UNDERLINE);
break;
case 4:
settermprop_bool(state, VTERM_PROP_CURSORBLINK, 0);
settermprop_int (state, VTERM_PROP_CURSORSHAPE, VTERM_PROP_CURSORSHAPE_UNDERLINE);
break;
case 5:
settermprop_bool(state, VTERM_PROP_CURSORBLINK, 1);
settermprop_int (state, VTERM_PROP_CURSORSHAPE, VTERM_PROP_CURSORSHAPE_BAR_LEFT);
break;
case 6:
settermprop_bool(state, VTERM_PROP_CURSORBLINK, 0);
settermprop_int (state, VTERM_PROP_CURSORSHAPE, VTERM_PROP_CURSORSHAPE_BAR_LEFT);
break;
}
break;
case INTERMED('"', 0x71): // DECSCA - DEC select character protection attribute
val = CSI_ARG_OR(args[0], 0);
switch(val) {
case 0: case 2:
state->protected_cell = 0;
break;
case 1:
state->protected_cell = 1;
break;
}
break;
case 0x72: // DECSTBM - DEC custom
state->scrollregion_top = CSI_ARG_OR(args[0], 1) - 1;
state->scrollregion_bottom = argcount < 2 || CSI_ARG_IS_MISSING(args[1]) ? -1 : CSI_ARG(args[1]);
LBOUND(state->scrollregion_top, 0);
UBOUND(state->scrollregion_top, state->rows);
LBOUND(state->scrollregion_bottom, -1);
if(state->scrollregion_top == 0 && state->scrollregion_bottom == state->rows)
state->scrollregion_bottom = -1;
else
UBOUND(state->scrollregion_bottom, state->rows);
if(SCROLLREGION_BOTTOM(state) <= state->scrollregion_top) {
// Invalid
state->scrollregion_top = 0;
state->scrollregion_bottom = -1;
}
break;
case 0x73: // DECSLRM - DEC custom
// Always allow setting these margins, just they won't take effect without DECVSSM
state->scrollregion_left = CSI_ARG_OR(args[0], 1) - 1;
state->scrollregion_right = argcount < 2 || CSI_ARG_IS_MISSING(args[1]) ? -1 : CSI_ARG(args[1]);
LBOUND(state->scrollregion_left, 0);
UBOUND(state->scrollregion_left, state->cols);
LBOUND(state->scrollregion_right, -1);
if(state->scrollregion_left == 0 && state->scrollregion_right == state->cols)
state->scrollregion_right = -1;
else
UBOUND(state->scrollregion_right, state->cols);
if(state->scrollregion_right > -1 &&
state->scrollregion_right <= state->scrollregion_left) {
// Invalid
state->scrollregion_left = 0;
state->scrollregion_right = -1;
}
break;
case 0x74:
switch(CSI_ARG(args[0])) {
case 8: /* CSI 8 ; rows ; cols t set size */
if (argcount == 3)
on_resize(CSI_ARG(args[1]), CSI_ARG(args[2]), state);
}
break;
case INTERMED('\'', 0x7D): // DECIC
count = CSI_ARG_COUNT(args[0]);
if(!is_cursor_in_scrollregion(state))
break;
rect.start_row = state->scrollregion_top;
rect.end_row = SCROLLREGION_BOTTOM(state);
rect.start_col = state->pos.col;
rect.end_col = SCROLLREGION_RIGHT(state);
scroll(state, rect, 0, -count);
break;
case INTERMED('\'', 0x7E): // DECDC
count = CSI_ARG_COUNT(args[0]);
if(!is_cursor_in_scrollregion(state))
break;
rect.start_row = state->scrollregion_top;
rect.end_row = SCROLLREGION_BOTTOM(state);
rect.start_col = state->pos.col;
rect.end_col = SCROLLREGION_RIGHT(state);
scroll(state, rect, 0, count);
break;
default:
if(state->fallbacks && state->fallbacks->csi)
if((*state->fallbacks->csi)(leader, args, argcount, intermed, command, state->fbdata))
return 1;
return 0;
}
if(state->mode.origin) {
LBOUND(state->pos.row, state->scrollregion_top);
UBOUND(state->pos.row, SCROLLREGION_BOTTOM(state)-1);
LBOUND(state->pos.col, SCROLLREGION_LEFT(state));
UBOUND(state->pos.col, SCROLLREGION_RIGHT(state)-1);
}
else {
LBOUND(state->pos.row, 0);
UBOUND(state->pos.row, state->rows-1);
LBOUND(state->pos.col, 0);
UBOUND(state->pos.col, THISROWWIDTH(state)-1);
}
updatecursor(state, &oldpos, 1);
#ifdef DEBUG
if(state->pos.row < 0 || state->pos.row >= state->rows ||
state->pos.col < 0 || state->pos.col >= state->cols) {
fprintf(stderr, "Position out of bounds after CSI %c: (%d,%d)\n",
command, state->pos.row, state->pos.col);
abort();
}
if(SCROLLREGION_BOTTOM(state) <= state->scrollregion_top) {
fprintf(stderr, "Scroll region height out of bounds after CSI %c: %d <= %d\n",
command, SCROLLREGION_BOTTOM(state), state->scrollregion_top);
abort();
}
if(SCROLLREGION_RIGHT(state) <= SCROLLREGION_LEFT(state)) {
fprintf(stderr, "Scroll region width out of bounds after CSI %c: %d <= %d\n",
command, SCROLLREGION_RIGHT(state), SCROLLREGION_LEFT(state));
abort();
}
#endif
return 1;
}
static int on_osc(const char *command, size_t cmdlen, void *user)
{
VTermState *state = user;
if(cmdlen < 2)
return 0;
if(strneq(command, "0;", 2)) {
settermprop_string(state, VTERM_PROP_ICONNAME, command + 2, cmdlen - 2);
settermprop_string(state, VTERM_PROP_TITLE, command + 2, cmdlen - 2);
return 1;
}
else if(strneq(command, "1;", 2)) {
settermprop_string(state, VTERM_PROP_ICONNAME, command + 2, cmdlen - 2);
return 1;
}
else if(strneq(command, "2;", 2)) {
settermprop_string(state, VTERM_PROP_TITLE, command + 2, cmdlen - 2);
return 1;
}
else if(strneq(command, "10;", 3)) {
/* request foreground color: <Esc>]10;?<0x07> */
int red = state->default_fg.red;
int blue = state->default_fg.blue;
int green = state->default_fg.green;
vterm_push_output_sprintf_ctrl(state->vt, C1_OSC, "10;rgb:%02x%02x/%02x%02x/%02x%02x\x07", red, red, green, green, blue, blue);
return 1;
}
else if(strneq(command, "11;", 3)) {
/* request background color: <Esc>]11;?<0x07> */
int red = state->default_bg.red;
int blue = state->default_bg.blue;
int green = state->default_bg.green;
vterm_push_output_sprintf_ctrl(state->vt, C1_OSC, "11;rgb:%02x%02x/%02x%02x/%02x%02x\x07", red, red, green, green, blue, blue);
return 1;
}
else if(strneq(command, "12;", 3)) {
settermprop_string(state, VTERM_PROP_CURSORCOLOR, command + 3, cmdlen - 3);
return 1;
}
else if(state->fallbacks && state->fallbacks->osc)
if((*state->fallbacks->osc)(command, cmdlen, state->fbdata))
return 1;
return 0;
}
static void request_status_string(VTermState *state, const char *command, size_t cmdlen)
{
if(cmdlen == 1)
switch(command[0]) {
case 'm': // Query SGR
{
long args[20];
int argc = vterm_state_getpen(state, args, sizeof(args)/sizeof(args[0]));
int argi;
vterm_push_output_sprintf_ctrl(state->vt, C1_DCS, "1$r");
for(argi = 0; argi < argc; argi++)
vterm_push_output_sprintf(state->vt,
argi == argc - 1 ? "%d" :
CSI_ARG_HAS_MORE(args[argi]) ? "%d:" :
"%d;",
CSI_ARG(args[argi]));
vterm_push_output_sprintf(state->vt, "m");
vterm_push_output_sprintf_ctrl(state->vt, C1_ST, "");
}
return;
case 'r': // Query DECSTBM
vterm_push_output_sprintf_dcs(state->vt, "1$r%d;%dr", state->scrollregion_top+1, SCROLLREGION_BOTTOM(state));
return;
case 's': // Query DECSLRM
vterm_push_output_sprintf_dcs(state->vt, "1$r%d;%ds", SCROLLREGION_LEFT(state)+1, SCROLLREGION_RIGHT(state));
return;
}
if(cmdlen == 2) {
if(strneq(command, " q", 2)) {
int reply;
switch(state->mode.cursor_shape) {
case VTERM_PROP_CURSORSHAPE_BLOCK: reply = 2; break;
case VTERM_PROP_CURSORSHAPE_UNDERLINE: reply = 4; break;
default: /* VTERM_PROP_CURSORSHAPE_BAR_LEFT */ reply = 6; break;
}
if(state->mode.cursor_blink)
reply--;
vterm_push_output_sprintf_dcs(state->vt, "1$r%d q", reply);
return;
}
else if(strneq(command, "\"q", 2)) {
vterm_push_output_sprintf_dcs(state->vt, "1$r%d\"q", state->protected_cell ? 1 : 2);
return;
}
}
vterm_push_output_sprintf_dcs(state->vt, "0$r%.s", (int)cmdlen, command);
}
static int on_dcs(const char *command, size_t cmdlen, void *user)
{
VTermState *state = user;
if(cmdlen >= 2 && strneq(command, "$q", 2)) {
request_status_string(state, command+2, cmdlen-2);
return 1;
}
else if(state->fallbacks && state->fallbacks->dcs)
if((*state->fallbacks->dcs)(command, cmdlen, state->fbdata))
return 1;
return 0;
}
static int on_resize(int rows, int cols, void *user)
{
VTermState *state = user;
VTermPos oldpos = state->pos;
VTermPos delta = { 0, 0 };
if(cols != state->cols) {
unsigned char *newtabstops = vterm_allocator_malloc(state->vt, (cols + 7) / 8);
/* TODO: This can all be done much more efficiently bytewise */
int col;
for(col = 0; col < state->cols && col < cols; col++) {
unsigned char mask = 1 << (col & 7);
if(state->tabstops[col >> 3] & mask)
newtabstops[col >> 3] |= mask;
else
newtabstops[col >> 3] &= ~mask;
}
for( ; col < cols; col++) {
unsigned char mask = 1 << (col & 7);
if(col % 8 == 0)
newtabstops[col >> 3] |= mask;
else
newtabstops[col >> 3] &= ~mask;
}
vterm_allocator_free(state->vt, state->tabstops);
state->tabstops = newtabstops;
}
if(rows != state->rows) {
VTermLineInfo *newlineinfo = vterm_allocator_malloc(state->vt, rows * sizeof(VTermLineInfo));
int row;
for(row = 0; row < state->rows && row < rows; row++) {
newlineinfo[row] = state->lineinfo[row];
}
for( ; row < rows; row++) {
newlineinfo[row].doublewidth = 0;
newlineinfo[row].doubleheight = 0;
}
vterm_allocator_free(state->vt, state->lineinfo);
state->lineinfo = newlineinfo;
}
state->rows = rows;
state->cols = cols;
if(state->scrollregion_bottom > -1)
UBOUND(state->scrollregion_bottom, state->rows);
if(state->scrollregion_right > -1)
UBOUND(state->scrollregion_right, state->cols);
if(state->callbacks && state->callbacks->resize)
(*state->callbacks->resize)(rows, cols, &delta, state->cbdata);
if(state->at_phantom && state->pos.col < cols-1) {
state->at_phantom = 0;
state->pos.col++;
}
state->pos.row += delta.row;
state->pos.col += delta.col;
if(state->pos.row >= rows)
state->pos.row = rows - 1;
if(state->pos.col >= cols)
state->pos.col = cols - 1;
updatecursor(state, &oldpos, 1);
return 1;
}
static const VTermParserCallbacks parser_callbacks = {
on_text, /* text */
on_control, /* control */
on_escape, /* escape */
on_csi, /* csi */
on_osc, /* osc */
on_dcs, /* dcs */
on_resize /* resize */
};
VTermState *vterm_obtain_state(VTerm *vt)
{
VTermState *state;
if(vt->state)
return vt->state;
state = vterm_state_new(vt);
vt->state = state;
state->combine_chars_size = 16;
state->combine_chars = vterm_allocator_malloc(state->vt, state->combine_chars_size * sizeof(state->combine_chars[0]));
state->tabstops = vterm_allocator_malloc(state->vt, (state->cols + 7) / 8);
state->lineinfo = vterm_allocator_malloc(state->vt, state->rows * sizeof(VTermLineInfo));
state->encoding_utf8.enc = vterm_lookup_encoding(ENC_UTF8, 'u');
if(*state->encoding_utf8.enc->init != NULL)
(*state->encoding_utf8.enc->init)(state->encoding_utf8.enc, state->encoding_utf8.data);
vterm_parser_set_callbacks(vt, &parser_callbacks, state);
return state;
}
void vterm_state_reset(VTermState *state, int hard)
{
VTermEncoding *default_enc;
state->scrollregion_top = 0;
state->scrollregion_bottom = -1;
state->scrollregion_left = 0;
state->scrollregion_right = -1;
state->mode.keypad = 0;
state->mode.cursor = 0;
state->mode.autowrap = 1;
state->mode.insert = 0;
state->mode.newline = 0;
state->mode.alt_screen = 0;
state->mode.origin = 0;
state->mode.leftrightmargin = 0;
state->mode.bracketpaste = 0;
state->mode.report_focus = 0;
state->vt->mode.ctrl8bit = 0;
{
int col;
for(col = 0; col < state->cols; col++)
if(col % 8 == 0)
set_col_tabstop(state, col);
else
clear_col_tabstop(state, col);
}
{
int row;
for(row = 0; row < state->rows; row++)
set_lineinfo(state, row, FORCE, DWL_OFF, DHL_OFF);
}
if(state->callbacks && state->callbacks->initpen)
(*state->callbacks->initpen)(state->cbdata);
vterm_state_resetpen(state);
default_enc = state->vt->mode.utf8 ?
vterm_lookup_encoding(ENC_UTF8, 'u') :
vterm_lookup_encoding(ENC_SINGLE_94, 'B');
{
int i;
for(i = 0; i < 4; i++) {
state->encoding[i].enc = default_enc;
if(default_enc->init)
(*default_enc->init)(default_enc, state->encoding[i].data);
}
}
state->gl_set = 0;
state->gr_set = 1;
state->gsingle_set = 0;
state->protected_cell = 0;
// Initialise the props
settermprop_bool(state, VTERM_PROP_CURSORVISIBLE, 1);
settermprop_bool(state, VTERM_PROP_CURSORBLINK, 1);
settermprop_int (state, VTERM_PROP_CURSORSHAPE, VTERM_PROP_CURSORSHAPE_BLOCK);
if(hard) {
VTermRect rect = { 0, 0, 0, 0 };
state->pos.row = 0;
state->pos.col = 0;
state->at_phantom = 0;
rect.end_row = state->rows;
rect.end_col = state->cols;
erase(state, rect, 0);
}
}
void vterm_state_get_cursorpos(const VTermState *state, VTermPos *cursorpos)
{
*cursorpos = state->pos;
}
void vterm_state_get_mousestate(const VTermState *state, VTermMouseState *mousestate)
{
mousestate->pos.col = state->mouse_col;
mousestate->pos.row = state->mouse_row;
mousestate->buttons = state->mouse_buttons;
mousestate->flags = state->mouse_flags;
}
void vterm_state_set_callbacks(VTermState *state, const VTermStateCallbacks *callbacks, void *user)
{
if(callbacks) {
state->callbacks = callbacks;
state->cbdata = user;
if(state->callbacks && state->callbacks->initpen)
(*state->callbacks->initpen)(state->cbdata);
}
else {
state->callbacks = NULL;
state->cbdata = NULL;
}
}
void *vterm_state_get_cbdata(VTermState *state)
{
return state->cbdata;
}
void vterm_state_set_unrecognised_fallbacks(VTermState *state, const VTermParserCallbacks *fallbacks, void *user)
{
if(fallbacks) {
state->fallbacks = fallbacks;
state->fbdata = user;
}
else {
state->fallbacks = NULL;
state->fbdata = NULL;
}
}
void *vterm_state_get_unrecognised_fbdata(VTermState *state)
{
return state->fbdata;
}
int vterm_state_set_termprop(VTermState *state, VTermProp prop, VTermValue *val)
{
/* Only store the new value of the property if usercode said it was happy.
* This is especially important for altscreen switching */
if(state->callbacks && state->callbacks->settermprop)
if(!(*state->callbacks->settermprop)(prop, val, state->cbdata))
return 0;
switch(prop) {
case VTERM_PROP_TITLE:
case VTERM_PROP_ICONNAME:
case VTERM_PROP_CURSORCOLOR:
// we don't store these, just transparently pass through
return 1;
case VTERM_PROP_CURSORVISIBLE:
state->mode.cursor_visible = val->boolean;
return 1;
case VTERM_PROP_CURSORBLINK:
state->mode.cursor_blink = val->boolean;
return 1;
case VTERM_PROP_CURSORSHAPE:
state->mode.cursor_shape = val->number;
return 1;
case VTERM_PROP_REVERSE:
state->mode.screen = val->boolean;
return 1;
case VTERM_PROP_ALTSCREEN:
state->mode.alt_screen = val->boolean;
if(state->mode.alt_screen) {
VTermRect rect = {0, 0, 0, 0};
rect.end_row = state->rows;
rect.end_col = state->cols;
erase(state, rect, 0);
}
return 1;
case VTERM_PROP_MOUSE:
state->mouse_flags = 0;
if(val->number)
state->mouse_flags |= MOUSE_WANT_CLICK;
if(val->number == VTERM_PROP_MOUSE_DRAG)
state->mouse_flags |= MOUSE_WANT_DRAG;
if(val->number == VTERM_PROP_MOUSE_MOVE)
state->mouse_flags |= MOUSE_WANT_MOVE;
return 1;
case VTERM_N_PROPS:
return 0;
}
return 0;
}
void vterm_state_focus_in(VTermState *state)
{
if(state->mode.report_focus)
vterm_push_output_sprintf_ctrl(state->vt, C1_CSI, "I");
}
void vterm_state_focus_out(VTermState *state)
{
if(state->mode.report_focus)
vterm_push_output_sprintf_ctrl(state->vt, C1_CSI, "O");
}
const VTermLineInfo *vterm_state_get_lineinfo(const VTermState *state, int row)
{
return state->lineinfo + row;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_528_0 |
crossvul-cpp_data_bad_1062_0 | // SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 2013 - 2018 Intel Corporation. */
#include <linux/types.h>
#include <linux/module.h>
#include <net/ipv6.h>
#include <net/ip.h>
#include <net/tcp.h>
#include <linux/if_macvlan.h>
#include <linux/prefetch.h>
#include "fm10k.h"
#define DRV_VERSION "0.26.1-k"
#define DRV_SUMMARY "Intel(R) Ethernet Switch Host Interface Driver"
const char fm10k_driver_version[] = DRV_VERSION;
char fm10k_driver_name[] = "fm10k";
static const char fm10k_driver_string[] = DRV_SUMMARY;
static const char fm10k_copyright[] =
"Copyright(c) 2013 - 2018 Intel Corporation.";
MODULE_AUTHOR("Intel Corporation, <linux.nics@intel.com>");
MODULE_DESCRIPTION(DRV_SUMMARY);
MODULE_LICENSE("GPL v2");
MODULE_VERSION(DRV_VERSION);
/* single workqueue for entire fm10k driver */
struct workqueue_struct *fm10k_workqueue;
/**
* fm10k_init_module - Driver Registration Routine
*
* fm10k_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
**/
static int __init fm10k_init_module(void)
{
pr_info("%s - version %s\n", fm10k_driver_string, fm10k_driver_version);
pr_info("%s\n", fm10k_copyright);
/* create driver workqueue */
fm10k_workqueue = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0,
fm10k_driver_name);
fm10k_dbg_init();
return fm10k_register_pci_driver();
}
module_init(fm10k_init_module);
/**
* fm10k_exit_module - Driver Exit Cleanup Routine
*
* fm10k_exit_module is called just before the driver is removed
* from memory.
**/
static void __exit fm10k_exit_module(void)
{
fm10k_unregister_pci_driver();
fm10k_dbg_exit();
/* destroy driver workqueue */
destroy_workqueue(fm10k_workqueue);
}
module_exit(fm10k_exit_module);
static bool fm10k_alloc_mapped_page(struct fm10k_ring *rx_ring,
struct fm10k_rx_buffer *bi)
{
struct page *page = bi->page;
dma_addr_t dma;
/* Only page will be NULL if buffer was consumed */
if (likely(page))
return true;
/* alloc new page for storage */
page = dev_alloc_page();
if (unlikely(!page)) {
rx_ring->rx_stats.alloc_failed++;
return false;
}
/* map page for use */
dma = dma_map_page(rx_ring->dev, page, 0, PAGE_SIZE, DMA_FROM_DEVICE);
/* if mapping failed free memory back to system since
* there isn't much point in holding memory we can't use
*/
if (dma_mapping_error(rx_ring->dev, dma)) {
__free_page(page);
rx_ring->rx_stats.alloc_failed++;
return false;
}
bi->dma = dma;
bi->page = page;
bi->page_offset = 0;
return true;
}
/**
* fm10k_alloc_rx_buffers - Replace used receive buffers
* @rx_ring: ring to place buffers on
* @cleaned_count: number of buffers to replace
**/
void fm10k_alloc_rx_buffers(struct fm10k_ring *rx_ring, u16 cleaned_count)
{
union fm10k_rx_desc *rx_desc;
struct fm10k_rx_buffer *bi;
u16 i = rx_ring->next_to_use;
/* nothing to do */
if (!cleaned_count)
return;
rx_desc = FM10K_RX_DESC(rx_ring, i);
bi = &rx_ring->rx_buffer[i];
i -= rx_ring->count;
do {
if (!fm10k_alloc_mapped_page(rx_ring, bi))
break;
/* Refresh the desc even if buffer_addrs didn't change
* because each write-back erases this info.
*/
rx_desc->q.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset);
rx_desc++;
bi++;
i++;
if (unlikely(!i)) {
rx_desc = FM10K_RX_DESC(rx_ring, 0);
bi = rx_ring->rx_buffer;
i -= rx_ring->count;
}
/* clear the status bits for the next_to_use descriptor */
rx_desc->d.staterr = 0;
cleaned_count--;
} while (cleaned_count);
i += rx_ring->count;
if (rx_ring->next_to_use != i) {
/* record the next descriptor to use */
rx_ring->next_to_use = i;
/* update next to alloc since we have filled the ring */
rx_ring->next_to_alloc = i;
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64).
*/
wmb();
/* notify hardware of new descriptors */
writel(i, rx_ring->tail);
}
}
/**
* fm10k_reuse_rx_page - page flip buffer and store it back on the ring
* @rx_ring: rx descriptor ring to store buffers on
* @old_buff: donor buffer to have page reused
*
* Synchronizes page for reuse by the interface
**/
static void fm10k_reuse_rx_page(struct fm10k_ring *rx_ring,
struct fm10k_rx_buffer *old_buff)
{
struct fm10k_rx_buffer *new_buff;
u16 nta = rx_ring->next_to_alloc;
new_buff = &rx_ring->rx_buffer[nta];
/* update, and store next to alloc */
nta++;
rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0;
/* transfer page from old buffer to new buffer */
*new_buff = *old_buff;
/* sync the buffer for use by the device */
dma_sync_single_range_for_device(rx_ring->dev, old_buff->dma,
old_buff->page_offset,
FM10K_RX_BUFSZ,
DMA_FROM_DEVICE);
}
static inline bool fm10k_page_is_reserved(struct page *page)
{
return (page_to_nid(page) != numa_mem_id()) || page_is_pfmemalloc(page);
}
static bool fm10k_can_reuse_rx_page(struct fm10k_rx_buffer *rx_buffer,
struct page *page,
unsigned int __maybe_unused truesize)
{
/* avoid re-using remote pages */
if (unlikely(fm10k_page_is_reserved(page)))
return false;
#if (PAGE_SIZE < 8192)
/* if we are only owner of page we can reuse it */
if (unlikely(page_count(page) != 1))
return false;
/* flip page offset to other buffer */
rx_buffer->page_offset ^= FM10K_RX_BUFSZ;
#else
/* move offset up to the next cache line */
rx_buffer->page_offset += truesize;
if (rx_buffer->page_offset > (PAGE_SIZE - FM10K_RX_BUFSZ))
return false;
#endif
/* Even if we own the page, we are not allowed to use atomic_set()
* This would break get_page_unless_zero() users.
*/
page_ref_inc(page);
return true;
}
/**
* fm10k_add_rx_frag - Add contents of Rx buffer to sk_buff
* @rx_buffer: buffer containing page to add
* @size: packet size from rx_desc
* @rx_desc: descriptor containing length of buffer written by hardware
* @skb: sk_buff to place the data into
*
* This function will add the data contained in rx_buffer->page to the skb.
* This is done either through a direct copy if the data in the buffer is
* less than the skb header size, otherwise it will just attach the page as
* a frag to the skb.
*
* The function will then update the page offset if necessary and return
* true if the buffer can be reused by the interface.
**/
static bool fm10k_add_rx_frag(struct fm10k_rx_buffer *rx_buffer,
unsigned int size,
union fm10k_rx_desc *rx_desc,
struct sk_buff *skb)
{
struct page *page = rx_buffer->page;
unsigned char *va = page_address(page) + rx_buffer->page_offset;
#if (PAGE_SIZE < 8192)
unsigned int truesize = FM10K_RX_BUFSZ;
#else
unsigned int truesize = ALIGN(size, 512);
#endif
unsigned int pull_len;
if (unlikely(skb_is_nonlinear(skb)))
goto add_tail_frag;
if (likely(size <= FM10K_RX_HDR_LEN)) {
memcpy(__skb_put(skb, size), va, ALIGN(size, sizeof(long)));
/* page is not reserved, we can reuse buffer as-is */
if (likely(!fm10k_page_is_reserved(page)))
return true;
/* this page cannot be reused so discard it */
__free_page(page);
return false;
}
/* we need the header to contain the greater of either ETH_HLEN or
* 60 bytes if the skb->len is less than 60 for skb_pad.
*/
pull_len = eth_get_headlen(va, FM10K_RX_HDR_LEN);
/* align pull length to size of long to optimize memcpy performance */
memcpy(__skb_put(skb, pull_len), va, ALIGN(pull_len, sizeof(long)));
/* update all of the pointers */
va += pull_len;
size -= pull_len;
add_tail_frag:
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page,
(unsigned long)va & ~PAGE_MASK, size, truesize);
return fm10k_can_reuse_rx_page(rx_buffer, page, truesize);
}
static struct sk_buff *fm10k_fetch_rx_buffer(struct fm10k_ring *rx_ring,
union fm10k_rx_desc *rx_desc,
struct sk_buff *skb)
{
unsigned int size = le16_to_cpu(rx_desc->w.length);
struct fm10k_rx_buffer *rx_buffer;
struct page *page;
rx_buffer = &rx_ring->rx_buffer[rx_ring->next_to_clean];
page = rx_buffer->page;
prefetchw(page);
if (likely(!skb)) {
void *page_addr = page_address(page) +
rx_buffer->page_offset;
/* prefetch first cache line of first page */
prefetch(page_addr);
#if L1_CACHE_BYTES < 128
prefetch(page_addr + L1_CACHE_BYTES);
#endif
/* allocate a skb to store the frags */
skb = napi_alloc_skb(&rx_ring->q_vector->napi,
FM10K_RX_HDR_LEN);
if (unlikely(!skb)) {
rx_ring->rx_stats.alloc_failed++;
return NULL;
}
/* we will be copying header into skb->data in
* pskb_may_pull so it is in our interest to prefetch
* it now to avoid a possible cache miss
*/
prefetchw(skb->data);
}
/* we are reusing so sync this buffer for CPU use */
dma_sync_single_range_for_cpu(rx_ring->dev,
rx_buffer->dma,
rx_buffer->page_offset,
size,
DMA_FROM_DEVICE);
/* pull page into skb */
if (fm10k_add_rx_frag(rx_buffer, size, rx_desc, skb)) {
/* hand second half of page back to the ring */
fm10k_reuse_rx_page(rx_ring, rx_buffer);
} else {
/* we are not reusing the buffer so unmap it */
dma_unmap_page(rx_ring->dev, rx_buffer->dma,
PAGE_SIZE, DMA_FROM_DEVICE);
}
/* clear contents of rx_buffer */
rx_buffer->page = NULL;
return skb;
}
static inline void fm10k_rx_checksum(struct fm10k_ring *ring,
union fm10k_rx_desc *rx_desc,
struct sk_buff *skb)
{
skb_checksum_none_assert(skb);
/* Rx checksum disabled via ethtool */
if (!(ring->netdev->features & NETIF_F_RXCSUM))
return;
/* TCP/UDP checksum error bit is set */
if (fm10k_test_staterr(rx_desc,
FM10K_RXD_STATUS_L4E |
FM10K_RXD_STATUS_L4E2 |
FM10K_RXD_STATUS_IPE |
FM10K_RXD_STATUS_IPE2)) {
ring->rx_stats.csum_err++;
return;
}
/* It must be a TCP or UDP packet with a valid checksum */
if (fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4CS2))
skb->encapsulation = true;
else if (!fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4CS))
return;
skb->ip_summed = CHECKSUM_UNNECESSARY;
ring->rx_stats.csum_good++;
}
#define FM10K_RSS_L4_TYPES_MASK \
(BIT(FM10K_RSSTYPE_IPV4_TCP) | \
BIT(FM10K_RSSTYPE_IPV4_UDP) | \
BIT(FM10K_RSSTYPE_IPV6_TCP) | \
BIT(FM10K_RSSTYPE_IPV6_UDP))
static inline void fm10k_rx_hash(struct fm10k_ring *ring,
union fm10k_rx_desc *rx_desc,
struct sk_buff *skb)
{
u16 rss_type;
if (!(ring->netdev->features & NETIF_F_RXHASH))
return;
rss_type = le16_to_cpu(rx_desc->w.pkt_info) & FM10K_RXD_RSSTYPE_MASK;
if (!rss_type)
return;
skb_set_hash(skb, le32_to_cpu(rx_desc->d.rss),
(BIT(rss_type) & FM10K_RSS_L4_TYPES_MASK) ?
PKT_HASH_TYPE_L4 : PKT_HASH_TYPE_L3);
}
static void fm10k_type_trans(struct fm10k_ring *rx_ring,
union fm10k_rx_desc __maybe_unused *rx_desc,
struct sk_buff *skb)
{
struct net_device *dev = rx_ring->netdev;
struct fm10k_l2_accel *l2_accel = rcu_dereference_bh(rx_ring->l2_accel);
/* check to see if DGLORT belongs to a MACVLAN */
if (l2_accel) {
u16 idx = le16_to_cpu(FM10K_CB(skb)->fi.w.dglort) - 1;
idx -= l2_accel->dglort;
if (idx < l2_accel->size && l2_accel->macvlan[idx])
dev = l2_accel->macvlan[idx];
else
l2_accel = NULL;
}
/* Record Rx queue, or update macvlan statistics */
if (!l2_accel)
skb_record_rx_queue(skb, rx_ring->queue_index);
else
macvlan_count_rx(netdev_priv(dev), skb->len + ETH_HLEN, true,
false);
skb->protocol = eth_type_trans(skb, dev);
}
/**
* fm10k_process_skb_fields - Populate skb header fields from Rx descriptor
* @rx_ring: rx descriptor ring packet is being transacted on
* @rx_desc: pointer to the EOP Rx descriptor
* @skb: pointer to current skb being populated
*
* This function checks the ring, descriptor, and packet information in
* order to populate the hash, checksum, VLAN, timestamp, protocol, and
* other fields within the skb.
**/
static unsigned int fm10k_process_skb_fields(struct fm10k_ring *rx_ring,
union fm10k_rx_desc *rx_desc,
struct sk_buff *skb)
{
unsigned int len = skb->len;
fm10k_rx_hash(rx_ring, rx_desc, skb);
fm10k_rx_checksum(rx_ring, rx_desc, skb);
FM10K_CB(skb)->tstamp = rx_desc->q.timestamp;
FM10K_CB(skb)->fi.w.vlan = rx_desc->w.vlan;
FM10K_CB(skb)->fi.d.glort = rx_desc->d.glort;
if (rx_desc->w.vlan) {
u16 vid = le16_to_cpu(rx_desc->w.vlan);
if ((vid & VLAN_VID_MASK) != rx_ring->vid)
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid);
else if (vid & VLAN_PRIO_MASK)
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q),
vid & VLAN_PRIO_MASK);
}
fm10k_type_trans(rx_ring, rx_desc, skb);
return len;
}
/**
* fm10k_is_non_eop - process handling of non-EOP buffers
* @rx_ring: Rx ring being processed
* @rx_desc: Rx descriptor for current buffer
*
* This function updates next to clean. If the buffer is an EOP buffer
* this function exits returning false, otherwise it will place the
* sk_buff in the next buffer to be chained and return true indicating
* that this is in fact a non-EOP buffer.
**/
static bool fm10k_is_non_eop(struct fm10k_ring *rx_ring,
union fm10k_rx_desc *rx_desc)
{
u32 ntc = rx_ring->next_to_clean + 1;
/* fetch, update, and store next to clean */
ntc = (ntc < rx_ring->count) ? ntc : 0;
rx_ring->next_to_clean = ntc;
prefetch(FM10K_RX_DESC(rx_ring, ntc));
if (likely(fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_EOP)))
return false;
return true;
}
/**
* fm10k_cleanup_headers - Correct corrupted or empty headers
* @rx_ring: rx descriptor ring packet is being transacted on
* @rx_desc: pointer to the EOP Rx descriptor
* @skb: pointer to current skb being fixed
*
* Address the case where we are pulling data in on pages only
* and as such no data is present in the skb header.
*
* In addition if skb is not at least 60 bytes we need to pad it so that
* it is large enough to qualify as a valid Ethernet frame.
*
* Returns true if an error was encountered and skb was freed.
**/
static bool fm10k_cleanup_headers(struct fm10k_ring *rx_ring,
union fm10k_rx_desc *rx_desc,
struct sk_buff *skb)
{
if (unlikely((fm10k_test_staterr(rx_desc,
FM10K_RXD_STATUS_RXE)))) {
#define FM10K_TEST_RXD_BIT(rxd, bit) \
((rxd)->w.csum_err & cpu_to_le16(bit))
if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_SWITCH_ERROR))
rx_ring->rx_stats.switch_errors++;
if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_NO_DESCRIPTOR))
rx_ring->rx_stats.drops++;
if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_PP_ERROR))
rx_ring->rx_stats.pp_errors++;
if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_SWITCH_READY))
rx_ring->rx_stats.link_errors++;
if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_TOO_BIG))
rx_ring->rx_stats.length_errors++;
dev_kfree_skb_any(skb);
rx_ring->rx_stats.errors++;
return true;
}
/* if eth_skb_pad returns an error the skb was freed */
if (eth_skb_pad(skb))
return true;
return false;
}
/**
* fm10k_receive_skb - helper function to handle rx indications
* @q_vector: structure containing interrupt and ring information
* @skb: packet to send up
**/
static void fm10k_receive_skb(struct fm10k_q_vector *q_vector,
struct sk_buff *skb)
{
napi_gro_receive(&q_vector->napi, skb);
}
static int fm10k_clean_rx_irq(struct fm10k_q_vector *q_vector,
struct fm10k_ring *rx_ring,
int budget)
{
struct sk_buff *skb = rx_ring->skb;
unsigned int total_bytes = 0, total_packets = 0;
u16 cleaned_count = fm10k_desc_unused(rx_ring);
while (likely(total_packets < budget)) {
union fm10k_rx_desc *rx_desc;
/* return some buffers to hardware, one at a time is too slow */
if (cleaned_count >= FM10K_RX_BUFFER_WRITE) {
fm10k_alloc_rx_buffers(rx_ring, cleaned_count);
cleaned_count = 0;
}
rx_desc = FM10K_RX_DESC(rx_ring, rx_ring->next_to_clean);
if (!rx_desc->d.staterr)
break;
/* This memory barrier is needed to keep us from reading
* any other fields out of the rx_desc until we know the
* descriptor has been written back
*/
dma_rmb();
/* retrieve a buffer from the ring */
skb = fm10k_fetch_rx_buffer(rx_ring, rx_desc, skb);
/* exit if we failed to retrieve a buffer */
if (!skb)
break;
cleaned_count++;
/* fetch next buffer in frame if non-eop */
if (fm10k_is_non_eop(rx_ring, rx_desc))
continue;
/* verify the packet layout is correct */
if (fm10k_cleanup_headers(rx_ring, rx_desc, skb)) {
skb = NULL;
continue;
}
/* populate checksum, timestamp, VLAN, and protocol */
total_bytes += fm10k_process_skb_fields(rx_ring, rx_desc, skb);
fm10k_receive_skb(q_vector, skb);
/* reset skb pointer */
skb = NULL;
/* update budget accounting */
total_packets++;
}
/* place incomplete frames back on ring for completion */
rx_ring->skb = skb;
u64_stats_update_begin(&rx_ring->syncp);
rx_ring->stats.packets += total_packets;
rx_ring->stats.bytes += total_bytes;
u64_stats_update_end(&rx_ring->syncp);
q_vector->rx.total_packets += total_packets;
q_vector->rx.total_bytes += total_bytes;
return total_packets;
}
#define VXLAN_HLEN (sizeof(struct udphdr) + 8)
static struct ethhdr *fm10k_port_is_vxlan(struct sk_buff *skb)
{
struct fm10k_intfc *interface = netdev_priv(skb->dev);
struct fm10k_udp_port *vxlan_port;
/* we can only offload a vxlan if we recognize it as such */
vxlan_port = list_first_entry_or_null(&interface->vxlan_port,
struct fm10k_udp_port, list);
if (!vxlan_port)
return NULL;
if (vxlan_port->port != udp_hdr(skb)->dest)
return NULL;
/* return offset of udp_hdr plus 8 bytes for VXLAN header */
return (struct ethhdr *)(skb_transport_header(skb) + VXLAN_HLEN);
}
#define FM10K_NVGRE_RESERVED0_FLAGS htons(0x9FFF)
#define NVGRE_TNI htons(0x2000)
struct fm10k_nvgre_hdr {
__be16 flags;
__be16 proto;
__be32 tni;
};
static struct ethhdr *fm10k_gre_is_nvgre(struct sk_buff *skb)
{
struct fm10k_nvgre_hdr *nvgre_hdr;
int hlen = ip_hdrlen(skb);
/* currently only IPv4 is supported due to hlen above */
if (vlan_get_protocol(skb) != htons(ETH_P_IP))
return NULL;
/* our transport header should be NVGRE */
nvgre_hdr = (struct fm10k_nvgre_hdr *)(skb_network_header(skb) + hlen);
/* verify all reserved flags are 0 */
if (nvgre_hdr->flags & FM10K_NVGRE_RESERVED0_FLAGS)
return NULL;
/* report start of ethernet header */
if (nvgre_hdr->flags & NVGRE_TNI)
return (struct ethhdr *)(nvgre_hdr + 1);
return (struct ethhdr *)(&nvgre_hdr->tni);
}
__be16 fm10k_tx_encap_offload(struct sk_buff *skb)
{
u8 l4_hdr = 0, inner_l4_hdr = 0, inner_l4_hlen;
struct ethhdr *eth_hdr;
if (skb->inner_protocol_type != ENCAP_TYPE_ETHER ||
skb->inner_protocol != htons(ETH_P_TEB))
return 0;
switch (vlan_get_protocol(skb)) {
case htons(ETH_P_IP):
l4_hdr = ip_hdr(skb)->protocol;
break;
case htons(ETH_P_IPV6):
l4_hdr = ipv6_hdr(skb)->nexthdr;
break;
default:
return 0;
}
switch (l4_hdr) {
case IPPROTO_UDP:
eth_hdr = fm10k_port_is_vxlan(skb);
break;
case IPPROTO_GRE:
eth_hdr = fm10k_gre_is_nvgre(skb);
break;
default:
return 0;
}
if (!eth_hdr)
return 0;
switch (eth_hdr->h_proto) {
case htons(ETH_P_IP):
inner_l4_hdr = inner_ip_hdr(skb)->protocol;
break;
case htons(ETH_P_IPV6):
inner_l4_hdr = inner_ipv6_hdr(skb)->nexthdr;
break;
default:
return 0;
}
switch (inner_l4_hdr) {
case IPPROTO_TCP:
inner_l4_hlen = inner_tcp_hdrlen(skb);
break;
case IPPROTO_UDP:
inner_l4_hlen = 8;
break;
default:
return 0;
}
/* The hardware allows tunnel offloads only if the combined inner and
* outer header is 184 bytes or less
*/
if (skb_inner_transport_header(skb) + inner_l4_hlen -
skb_mac_header(skb) > FM10K_TUNNEL_HEADER_LENGTH)
return 0;
return eth_hdr->h_proto;
}
static int fm10k_tso(struct fm10k_ring *tx_ring,
struct fm10k_tx_buffer *first)
{
struct sk_buff *skb = first->skb;
struct fm10k_tx_desc *tx_desc;
unsigned char *th;
u8 hdrlen;
if (skb->ip_summed != CHECKSUM_PARTIAL)
return 0;
if (!skb_is_gso(skb))
return 0;
/* compute header lengths */
if (skb->encapsulation) {
if (!fm10k_tx_encap_offload(skb))
goto err_vxlan;
th = skb_inner_transport_header(skb);
} else {
th = skb_transport_header(skb);
}
/* compute offset from SOF to transport header and add header len */
hdrlen = (th - skb->data) + (((struct tcphdr *)th)->doff << 2);
first->tx_flags |= FM10K_TX_FLAGS_CSUM;
/* update gso size and bytecount with header size */
first->gso_segs = skb_shinfo(skb)->gso_segs;
first->bytecount += (first->gso_segs - 1) * hdrlen;
/* populate Tx descriptor header size and mss */
tx_desc = FM10K_TX_DESC(tx_ring, tx_ring->next_to_use);
tx_desc->hdrlen = hdrlen;
tx_desc->mss = cpu_to_le16(skb_shinfo(skb)->gso_size);
return 1;
err_vxlan:
tx_ring->netdev->features &= ~NETIF_F_GSO_UDP_TUNNEL;
if (net_ratelimit())
netdev_err(tx_ring->netdev,
"TSO requested for unsupported tunnel, disabling offload\n");
return -1;
}
static void fm10k_tx_csum(struct fm10k_ring *tx_ring,
struct fm10k_tx_buffer *first)
{
struct sk_buff *skb = first->skb;
struct fm10k_tx_desc *tx_desc;
union {
struct iphdr *ipv4;
struct ipv6hdr *ipv6;
u8 *raw;
} network_hdr;
u8 *transport_hdr;
__be16 frag_off;
__be16 protocol;
u8 l4_hdr = 0;
if (skb->ip_summed != CHECKSUM_PARTIAL)
goto no_csum;
if (skb->encapsulation) {
protocol = fm10k_tx_encap_offload(skb);
if (!protocol) {
if (skb_checksum_help(skb)) {
dev_warn(tx_ring->dev,
"failed to offload encap csum!\n");
tx_ring->tx_stats.csum_err++;
}
goto no_csum;
}
network_hdr.raw = skb_inner_network_header(skb);
transport_hdr = skb_inner_transport_header(skb);
} else {
protocol = vlan_get_protocol(skb);
network_hdr.raw = skb_network_header(skb);
transport_hdr = skb_transport_header(skb);
}
switch (protocol) {
case htons(ETH_P_IP):
l4_hdr = network_hdr.ipv4->protocol;
break;
case htons(ETH_P_IPV6):
l4_hdr = network_hdr.ipv6->nexthdr;
if (likely((transport_hdr - network_hdr.raw) ==
sizeof(struct ipv6hdr)))
break;
ipv6_skip_exthdr(skb, network_hdr.raw - skb->data +
sizeof(struct ipv6hdr),
&l4_hdr, &frag_off);
if (unlikely(frag_off))
l4_hdr = NEXTHDR_FRAGMENT;
break;
default:
break;
}
switch (l4_hdr) {
case IPPROTO_TCP:
case IPPROTO_UDP:
break;
case IPPROTO_GRE:
if (skb->encapsulation)
break;
/* fall through */
default:
if (unlikely(net_ratelimit())) {
dev_warn(tx_ring->dev,
"partial checksum, version=%d l4 proto=%x\n",
protocol, l4_hdr);
}
skb_checksum_help(skb);
tx_ring->tx_stats.csum_err++;
goto no_csum;
}
/* update TX checksum flag */
first->tx_flags |= FM10K_TX_FLAGS_CSUM;
tx_ring->tx_stats.csum_good++;
no_csum:
/* populate Tx descriptor header size and mss */
tx_desc = FM10K_TX_DESC(tx_ring, tx_ring->next_to_use);
tx_desc->hdrlen = 0;
tx_desc->mss = 0;
}
#define FM10K_SET_FLAG(_input, _flag, _result) \
((_flag <= _result) ? \
((u32)(_input & _flag) * (_result / _flag)) : \
((u32)(_input & _flag) / (_flag / _result)))
static u8 fm10k_tx_desc_flags(struct sk_buff *skb, u32 tx_flags)
{
/* set type for advanced descriptor with frame checksum insertion */
u32 desc_flags = 0;
/* set checksum offload bits */
desc_flags |= FM10K_SET_FLAG(tx_flags, FM10K_TX_FLAGS_CSUM,
FM10K_TXD_FLAG_CSUM);
return desc_flags;
}
static bool fm10k_tx_desc_push(struct fm10k_ring *tx_ring,
struct fm10k_tx_desc *tx_desc, u16 i,
dma_addr_t dma, unsigned int size, u8 desc_flags)
{
/* set RS and INT for last frame in a cache line */
if ((++i & (FM10K_TXD_WB_FIFO_SIZE - 1)) == 0)
desc_flags |= FM10K_TXD_FLAG_RS | FM10K_TXD_FLAG_INT;
/* record values to descriptor */
tx_desc->buffer_addr = cpu_to_le64(dma);
tx_desc->flags = desc_flags;
tx_desc->buflen = cpu_to_le16(size);
/* return true if we just wrapped the ring */
return i == tx_ring->count;
}
static int __fm10k_maybe_stop_tx(struct fm10k_ring *tx_ring, u16 size)
{
netif_stop_subqueue(tx_ring->netdev, tx_ring->queue_index);
/* Memory barrier before checking head and tail */
smp_mb();
/* Check again in a case another CPU has just made room available */
if (likely(fm10k_desc_unused(tx_ring) < size))
return -EBUSY;
/* A reprieve! - use start_queue because it doesn't call schedule */
netif_start_subqueue(tx_ring->netdev, tx_ring->queue_index);
++tx_ring->tx_stats.restart_queue;
return 0;
}
static inline int fm10k_maybe_stop_tx(struct fm10k_ring *tx_ring, u16 size)
{
if (likely(fm10k_desc_unused(tx_ring) >= size))
return 0;
return __fm10k_maybe_stop_tx(tx_ring, size);
}
static void fm10k_tx_map(struct fm10k_ring *tx_ring,
struct fm10k_tx_buffer *first)
{
struct sk_buff *skb = first->skb;
struct fm10k_tx_buffer *tx_buffer;
struct fm10k_tx_desc *tx_desc;
struct skb_frag_struct *frag;
unsigned char *data;
dma_addr_t dma;
unsigned int data_len, size;
u32 tx_flags = first->tx_flags;
u16 i = tx_ring->next_to_use;
u8 flags = fm10k_tx_desc_flags(skb, tx_flags);
tx_desc = FM10K_TX_DESC(tx_ring, i);
/* add HW VLAN tag */
if (skb_vlan_tag_present(skb))
tx_desc->vlan = cpu_to_le16(skb_vlan_tag_get(skb));
else
tx_desc->vlan = 0;
size = skb_headlen(skb);
data = skb->data;
dma = dma_map_single(tx_ring->dev, data, size, DMA_TO_DEVICE);
data_len = skb->data_len;
tx_buffer = first;
for (frag = &skb_shinfo(skb)->frags[0];; frag++) {
if (dma_mapping_error(tx_ring->dev, dma))
goto dma_error;
/* record length, and DMA address */
dma_unmap_len_set(tx_buffer, len, size);
dma_unmap_addr_set(tx_buffer, dma, dma);
while (unlikely(size > FM10K_MAX_DATA_PER_TXD)) {
if (fm10k_tx_desc_push(tx_ring, tx_desc++, i++, dma,
FM10K_MAX_DATA_PER_TXD, flags)) {
tx_desc = FM10K_TX_DESC(tx_ring, 0);
i = 0;
}
dma += FM10K_MAX_DATA_PER_TXD;
size -= FM10K_MAX_DATA_PER_TXD;
}
if (likely(!data_len))
break;
if (fm10k_tx_desc_push(tx_ring, tx_desc++, i++,
dma, size, flags)) {
tx_desc = FM10K_TX_DESC(tx_ring, 0);
i = 0;
}
size = skb_frag_size(frag);
data_len -= size;
dma = skb_frag_dma_map(tx_ring->dev, frag, 0, size,
DMA_TO_DEVICE);
tx_buffer = &tx_ring->tx_buffer[i];
}
/* write last descriptor with LAST bit set */
flags |= FM10K_TXD_FLAG_LAST;
if (fm10k_tx_desc_push(tx_ring, tx_desc, i++, dma, size, flags))
i = 0;
/* record bytecount for BQL */
netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount);
/* record SW timestamp if HW timestamp is not available */
skb_tx_timestamp(first->skb);
/* Force memory writes to complete before letting h/w know there
* are new descriptors to fetch. (Only applicable for weak-ordered
* memory model archs, such as IA-64).
*
* We also need this memory barrier to make certain all of the
* status bits have been updated before next_to_watch is written.
*/
wmb();
/* set next_to_watch value indicating a packet is present */
first->next_to_watch = tx_desc;
tx_ring->next_to_use = i;
/* Make sure there is space in the ring for the next send. */
fm10k_maybe_stop_tx(tx_ring, DESC_NEEDED);
/* notify HW of packet */
if (netif_xmit_stopped(txring_txq(tx_ring)) || !skb->xmit_more) {
writel(i, tx_ring->tail);
/* we need this if more than one processor can write to our tail
* at a time, it synchronizes IO on IA64/Altix systems
*/
mmiowb();
}
return;
dma_error:
dev_err(tx_ring->dev, "TX DMA map failed\n");
/* clear dma mappings for failed tx_buffer map */
for (;;) {
tx_buffer = &tx_ring->tx_buffer[i];
fm10k_unmap_and_free_tx_resource(tx_ring, tx_buffer);
if (tx_buffer == first)
break;
if (i == 0)
i = tx_ring->count;
i--;
}
tx_ring->next_to_use = i;
}
netdev_tx_t fm10k_xmit_frame_ring(struct sk_buff *skb,
struct fm10k_ring *tx_ring)
{
u16 count = TXD_USE_COUNT(skb_headlen(skb));
struct fm10k_tx_buffer *first;
unsigned short f;
u32 tx_flags = 0;
int tso;
/* need: 1 descriptor per page * PAGE_SIZE/FM10K_MAX_DATA_PER_TXD,
* + 1 desc for skb_headlen/FM10K_MAX_DATA_PER_TXD,
* + 2 desc gap to keep tail from touching head
* otherwise try next time
*/
for (f = 0; f < skb_shinfo(skb)->nr_frags; f++)
count += TXD_USE_COUNT(skb_shinfo(skb)->frags[f].size);
if (fm10k_maybe_stop_tx(tx_ring, count + 3)) {
tx_ring->tx_stats.tx_busy++;
return NETDEV_TX_BUSY;
}
/* record the location of the first descriptor for this packet */
first = &tx_ring->tx_buffer[tx_ring->next_to_use];
first->skb = skb;
first->bytecount = max_t(unsigned int, skb->len, ETH_ZLEN);
first->gso_segs = 1;
/* record initial flags and protocol */
first->tx_flags = tx_flags;
tso = fm10k_tso(tx_ring, first);
if (tso < 0)
goto out_drop;
else if (!tso)
fm10k_tx_csum(tx_ring, first);
fm10k_tx_map(tx_ring, first);
return NETDEV_TX_OK;
out_drop:
dev_kfree_skb_any(first->skb);
first->skb = NULL;
return NETDEV_TX_OK;
}
static u64 fm10k_get_tx_completed(struct fm10k_ring *ring)
{
return ring->stats.packets;
}
/**
* fm10k_get_tx_pending - how many Tx descriptors not processed
* @ring: the ring structure
* @in_sw: is tx_pending being checked in SW or in HW?
*/
u64 fm10k_get_tx_pending(struct fm10k_ring *ring, bool in_sw)
{
struct fm10k_intfc *interface = ring->q_vector->interface;
struct fm10k_hw *hw = &interface->hw;
u32 head, tail;
if (likely(in_sw)) {
head = ring->next_to_clean;
tail = ring->next_to_use;
} else {
head = fm10k_read_reg(hw, FM10K_TDH(ring->reg_idx));
tail = fm10k_read_reg(hw, FM10K_TDT(ring->reg_idx));
}
return ((head <= tail) ? tail : tail + ring->count) - head;
}
bool fm10k_check_tx_hang(struct fm10k_ring *tx_ring)
{
u32 tx_done = fm10k_get_tx_completed(tx_ring);
u32 tx_done_old = tx_ring->tx_stats.tx_done_old;
u32 tx_pending = fm10k_get_tx_pending(tx_ring, true);
clear_check_for_tx_hang(tx_ring);
/* Check for a hung queue, but be thorough. This verifies
* that a transmit has been completed since the previous
* check AND there is at least one packet pending. By
* requiring this to fail twice we avoid races with
* clearing the ARMED bit and conditions where we
* run the check_tx_hang logic with a transmit completion
* pending but without time to complete it yet.
*/
if (!tx_pending || (tx_done_old != tx_done)) {
/* update completed stats and continue */
tx_ring->tx_stats.tx_done_old = tx_done;
/* reset the countdown */
clear_bit(__FM10K_HANG_CHECK_ARMED, tx_ring->state);
return false;
}
/* make sure it is true for two checks in a row */
return test_and_set_bit(__FM10K_HANG_CHECK_ARMED, tx_ring->state);
}
/**
* fm10k_tx_timeout_reset - initiate reset due to Tx timeout
* @interface: driver private struct
**/
void fm10k_tx_timeout_reset(struct fm10k_intfc *interface)
{
/* Do the reset outside of interrupt context */
if (!test_bit(__FM10K_DOWN, interface->state)) {
interface->tx_timeout_count++;
set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags);
fm10k_service_event_schedule(interface);
}
}
/**
* fm10k_clean_tx_irq - Reclaim resources after transmit completes
* @q_vector: structure containing interrupt and ring information
* @tx_ring: tx ring to clean
* @napi_budget: Used to determine if we are in netpoll
**/
static bool fm10k_clean_tx_irq(struct fm10k_q_vector *q_vector,
struct fm10k_ring *tx_ring, int napi_budget)
{
struct fm10k_intfc *interface = q_vector->interface;
struct fm10k_tx_buffer *tx_buffer;
struct fm10k_tx_desc *tx_desc;
unsigned int total_bytes = 0, total_packets = 0;
unsigned int budget = q_vector->tx.work_limit;
unsigned int i = tx_ring->next_to_clean;
if (test_bit(__FM10K_DOWN, interface->state))
return true;
tx_buffer = &tx_ring->tx_buffer[i];
tx_desc = FM10K_TX_DESC(tx_ring, i);
i -= tx_ring->count;
do {
struct fm10k_tx_desc *eop_desc = tx_buffer->next_to_watch;
/* if next_to_watch is not set then there is no work pending */
if (!eop_desc)
break;
/* prevent any other reads prior to eop_desc */
smp_rmb();
/* if DD is not set pending work has not been completed */
if (!(eop_desc->flags & FM10K_TXD_FLAG_DONE))
break;
/* clear next_to_watch to prevent false hangs */
tx_buffer->next_to_watch = NULL;
/* update the statistics for this packet */
total_bytes += tx_buffer->bytecount;
total_packets += tx_buffer->gso_segs;
/* free the skb */
napi_consume_skb(tx_buffer->skb, napi_budget);
/* unmap skb header data */
dma_unmap_single(tx_ring->dev,
dma_unmap_addr(tx_buffer, dma),
dma_unmap_len(tx_buffer, len),
DMA_TO_DEVICE);
/* clear tx_buffer data */
tx_buffer->skb = NULL;
dma_unmap_len_set(tx_buffer, len, 0);
/* unmap remaining buffers */
while (tx_desc != eop_desc) {
tx_buffer++;
tx_desc++;
i++;
if (unlikely(!i)) {
i -= tx_ring->count;
tx_buffer = tx_ring->tx_buffer;
tx_desc = FM10K_TX_DESC(tx_ring, 0);
}
/* unmap any remaining paged data */
if (dma_unmap_len(tx_buffer, len)) {
dma_unmap_page(tx_ring->dev,
dma_unmap_addr(tx_buffer, dma),
dma_unmap_len(tx_buffer, len),
DMA_TO_DEVICE);
dma_unmap_len_set(tx_buffer, len, 0);
}
}
/* move us one more past the eop_desc for start of next pkt */
tx_buffer++;
tx_desc++;
i++;
if (unlikely(!i)) {
i -= tx_ring->count;
tx_buffer = tx_ring->tx_buffer;
tx_desc = FM10K_TX_DESC(tx_ring, 0);
}
/* issue prefetch for next Tx descriptor */
prefetch(tx_desc);
/* update budget accounting */
budget--;
} while (likely(budget));
i += tx_ring->count;
tx_ring->next_to_clean = i;
u64_stats_update_begin(&tx_ring->syncp);
tx_ring->stats.bytes += total_bytes;
tx_ring->stats.packets += total_packets;
u64_stats_update_end(&tx_ring->syncp);
q_vector->tx.total_bytes += total_bytes;
q_vector->tx.total_packets += total_packets;
if (check_for_tx_hang(tx_ring) && fm10k_check_tx_hang(tx_ring)) {
/* schedule immediate reset if we believe we hung */
struct fm10k_hw *hw = &interface->hw;
netif_err(interface, drv, tx_ring->netdev,
"Detected Tx Unit Hang\n"
" Tx Queue <%d>\n"
" TDH, TDT <%x>, <%x>\n"
" next_to_use <%x>\n"
" next_to_clean <%x>\n",
tx_ring->queue_index,
fm10k_read_reg(hw, FM10K_TDH(tx_ring->reg_idx)),
fm10k_read_reg(hw, FM10K_TDT(tx_ring->reg_idx)),
tx_ring->next_to_use, i);
netif_stop_subqueue(tx_ring->netdev,
tx_ring->queue_index);
netif_info(interface, probe, tx_ring->netdev,
"tx hang %d detected on queue %d, resetting interface\n",
interface->tx_timeout_count + 1,
tx_ring->queue_index);
fm10k_tx_timeout_reset(interface);
/* the netdev is about to reset, no point in enabling stuff */
return true;
}
/* notify netdev of completed buffers */
netdev_tx_completed_queue(txring_txq(tx_ring),
total_packets, total_bytes);
#define TX_WAKE_THRESHOLD min_t(u16, FM10K_MIN_TXD - 1, DESC_NEEDED * 2)
if (unlikely(total_packets && netif_carrier_ok(tx_ring->netdev) &&
(fm10k_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD))) {
/* Make sure that anybody stopping the queue after this
* sees the new next_to_clean.
*/
smp_mb();
if (__netif_subqueue_stopped(tx_ring->netdev,
tx_ring->queue_index) &&
!test_bit(__FM10K_DOWN, interface->state)) {
netif_wake_subqueue(tx_ring->netdev,
tx_ring->queue_index);
++tx_ring->tx_stats.restart_queue;
}
}
return !!budget;
}
/**
* fm10k_update_itr - update the dynamic ITR value based on packet size
*
* Stores a new ITR value based on strictly on packet size. The
* divisors and thresholds used by this function were determined based
* on theoretical maximum wire speed and testing data, in order to
* minimize response time while increasing bulk throughput.
*
* @ring_container: Container for rings to have ITR updated
**/
static void fm10k_update_itr(struct fm10k_ring_container *ring_container)
{
unsigned int avg_wire_size, packets, itr_round;
/* Only update ITR if we are using adaptive setting */
if (!ITR_IS_ADAPTIVE(ring_container->itr))
goto clear_counts;
packets = ring_container->total_packets;
if (!packets)
goto clear_counts;
avg_wire_size = ring_container->total_bytes / packets;
/* The following is a crude approximation of:
* wmem_default / (size + overhead) = desired_pkts_per_int
* rate / bits_per_byte / (size + ethernet overhead) = pkt_rate
* (desired_pkt_rate / pkt_rate) * usecs_per_sec = ITR value
*
* Assuming wmem_default is 212992 and overhead is 640 bytes per
* packet, (256 skb, 64 headroom, 320 shared info), we can reduce the
* formula down to
*
* (34 * (size + 24)) / (size + 640) = ITR
*
* We first do some math on the packet size and then finally bitshift
* by 8 after rounding up. We also have to account for PCIe link speed
* difference as ITR scales based on this.
*/
if (avg_wire_size <= 360) {
/* Start at 250K ints/sec and gradually drop to 77K ints/sec */
avg_wire_size *= 8;
avg_wire_size += 376;
} else if (avg_wire_size <= 1152) {
/* 77K ints/sec to 45K ints/sec */
avg_wire_size *= 3;
avg_wire_size += 2176;
} else if (avg_wire_size <= 1920) {
/* 45K ints/sec to 38K ints/sec */
avg_wire_size += 4480;
} else {
/* plateau at a limit of 38K ints/sec */
avg_wire_size = 6656;
}
/* Perform final bitshift for division after rounding up to ensure
* that the calculation will never get below a 1. The bit shift
* accounts for changes in the ITR due to PCIe link speed.
*/
itr_round = READ_ONCE(ring_container->itr_scale) + 8;
avg_wire_size += BIT(itr_round) - 1;
avg_wire_size >>= itr_round;
/* write back value and retain adaptive flag */
ring_container->itr = avg_wire_size | FM10K_ITR_ADAPTIVE;
clear_counts:
ring_container->total_bytes = 0;
ring_container->total_packets = 0;
}
static void fm10k_qv_enable(struct fm10k_q_vector *q_vector)
{
/* Enable auto-mask and clear the current mask */
u32 itr = FM10K_ITR_ENABLE;
/* Update Tx ITR */
fm10k_update_itr(&q_vector->tx);
/* Update Rx ITR */
fm10k_update_itr(&q_vector->rx);
/* Store Tx itr in timer slot 0 */
itr |= (q_vector->tx.itr & FM10K_ITR_MAX);
/* Shift Rx itr to timer slot 1 */
itr |= (q_vector->rx.itr & FM10K_ITR_MAX) << FM10K_ITR_INTERVAL1_SHIFT;
/* Write the final value to the ITR register */
writel(itr, q_vector->itr);
}
static int fm10k_poll(struct napi_struct *napi, int budget)
{
struct fm10k_q_vector *q_vector =
container_of(napi, struct fm10k_q_vector, napi);
struct fm10k_ring *ring;
int per_ring_budget, work_done = 0;
bool clean_complete = true;
fm10k_for_each_ring(ring, q_vector->tx) {
if (!fm10k_clean_tx_irq(q_vector, ring, budget))
clean_complete = false;
}
/* Handle case where we are called by netpoll with a budget of 0 */
if (budget <= 0)
return budget;
/* attempt to distribute budget to each queue fairly, but don't
* allow the budget to go below 1 because we'll exit polling
*/
if (q_vector->rx.count > 1)
per_ring_budget = max(budget / q_vector->rx.count, 1);
else
per_ring_budget = budget;
fm10k_for_each_ring(ring, q_vector->rx) {
int work = fm10k_clean_rx_irq(q_vector, ring, per_ring_budget);
work_done += work;
if (work >= per_ring_budget)
clean_complete = false;
}
/* If all work not completed, return budget and keep polling */
if (!clean_complete)
return budget;
/* Exit the polling mode, but don't re-enable interrupts if stack might
* poll us due to busy-polling
*/
if (likely(napi_complete_done(napi, work_done)))
fm10k_qv_enable(q_vector);
return min(work_done, budget - 1);
}
/**
* fm10k_set_qos_queues: Allocate queues for a QOS-enabled device
* @interface: board private structure to initialize
*
* When QoS (Quality of Service) is enabled, allocate queues for
* each traffic class. If multiqueue isn't available,then abort QoS
* initialization.
*
* This function handles all combinations of Qos and RSS.
*
**/
static bool fm10k_set_qos_queues(struct fm10k_intfc *interface)
{
struct net_device *dev = interface->netdev;
struct fm10k_ring_feature *f;
int rss_i, i;
int pcs;
/* Map queue offset and counts onto allocated tx queues */
pcs = netdev_get_num_tc(dev);
if (pcs <= 1)
return false;
/* set QoS mask and indices */
f = &interface->ring_feature[RING_F_QOS];
f->indices = pcs;
f->mask = BIT(fls(pcs - 1)) - 1;
/* determine the upper limit for our current DCB mode */
rss_i = interface->hw.mac.max_queues / pcs;
rss_i = BIT(fls(rss_i) - 1);
/* set RSS mask and indices */
f = &interface->ring_feature[RING_F_RSS];
rss_i = min_t(u16, rss_i, f->limit);
f->indices = rss_i;
f->mask = BIT(fls(rss_i - 1)) - 1;
/* configure pause class to queue mapping */
for (i = 0; i < pcs; i++)
netdev_set_tc_queue(dev, i, rss_i, rss_i * i);
interface->num_rx_queues = rss_i * pcs;
interface->num_tx_queues = rss_i * pcs;
return true;
}
/**
* fm10k_set_rss_queues: Allocate queues for RSS
* @interface: board private structure to initialize
*
* This is our "base" multiqueue mode. RSS (Receive Side Scaling) will try
* to allocate one Rx queue per CPU, and if available, one Tx queue per CPU.
*
**/
static bool fm10k_set_rss_queues(struct fm10k_intfc *interface)
{
struct fm10k_ring_feature *f;
u16 rss_i;
f = &interface->ring_feature[RING_F_RSS];
rss_i = min_t(u16, interface->hw.mac.max_queues, f->limit);
/* record indices and power of 2 mask for RSS */
f->indices = rss_i;
f->mask = BIT(fls(rss_i - 1)) - 1;
interface->num_rx_queues = rss_i;
interface->num_tx_queues = rss_i;
return true;
}
/**
* fm10k_set_num_queues: Allocate queues for device, feature dependent
* @interface: board private structure to initialize
*
* This is the top level queue allocation routine. The order here is very
* important, starting with the "most" number of features turned on at once,
* and ending with the smallest set of features. This way large combinations
* can be allocated if they're turned on, and smaller combinations are the
* fallthrough conditions.
*
**/
static void fm10k_set_num_queues(struct fm10k_intfc *interface)
{
/* Attempt to setup QoS and RSS first */
if (fm10k_set_qos_queues(interface))
return;
/* If we don't have QoS, just fallback to only RSS. */
fm10k_set_rss_queues(interface);
}
/**
* fm10k_reset_num_queues - Reset the number of queues to zero
* @interface: board private structure
*
* This function should be called whenever we need to reset the number of
* queues after an error condition.
*/
static void fm10k_reset_num_queues(struct fm10k_intfc *interface)
{
interface->num_tx_queues = 0;
interface->num_rx_queues = 0;
interface->num_q_vectors = 0;
}
/**
* fm10k_alloc_q_vector - Allocate memory for a single interrupt vector
* @interface: board private structure to initialize
* @v_count: q_vectors allocated on interface, used for ring interleaving
* @v_idx: index of vector in interface struct
* @txr_count: total number of Tx rings to allocate
* @txr_idx: index of first Tx ring to allocate
* @rxr_count: total number of Rx rings to allocate
* @rxr_idx: index of first Rx ring to allocate
*
* We allocate one q_vector. If allocation fails we return -ENOMEM.
**/
static int fm10k_alloc_q_vector(struct fm10k_intfc *interface,
unsigned int v_count, unsigned int v_idx,
unsigned int txr_count, unsigned int txr_idx,
unsigned int rxr_count, unsigned int rxr_idx)
{
struct fm10k_q_vector *q_vector;
struct fm10k_ring *ring;
int ring_count;
ring_count = txr_count + rxr_count;
/* allocate q_vector and rings */
q_vector = kzalloc(struct_size(q_vector, ring, ring_count), GFP_KERNEL);
if (!q_vector)
return -ENOMEM;
/* initialize NAPI */
netif_napi_add(interface->netdev, &q_vector->napi,
fm10k_poll, NAPI_POLL_WEIGHT);
/* tie q_vector and interface together */
interface->q_vector[v_idx] = q_vector;
q_vector->interface = interface;
q_vector->v_idx = v_idx;
/* initialize pointer to rings */
ring = q_vector->ring;
/* save Tx ring container info */
q_vector->tx.ring = ring;
q_vector->tx.work_limit = FM10K_DEFAULT_TX_WORK;
q_vector->tx.itr = interface->tx_itr;
q_vector->tx.itr_scale = interface->hw.mac.itr_scale;
q_vector->tx.count = txr_count;
while (txr_count) {
/* assign generic ring traits */
ring->dev = &interface->pdev->dev;
ring->netdev = interface->netdev;
/* configure backlink on ring */
ring->q_vector = q_vector;
/* apply Tx specific ring traits */
ring->count = interface->tx_ring_count;
ring->queue_index = txr_idx;
/* assign ring to interface */
interface->tx_ring[txr_idx] = ring;
/* update count and index */
txr_count--;
txr_idx += v_count;
/* push pointer to next ring */
ring++;
}
/* save Rx ring container info */
q_vector->rx.ring = ring;
q_vector->rx.itr = interface->rx_itr;
q_vector->rx.itr_scale = interface->hw.mac.itr_scale;
q_vector->rx.count = rxr_count;
while (rxr_count) {
/* assign generic ring traits */
ring->dev = &interface->pdev->dev;
ring->netdev = interface->netdev;
rcu_assign_pointer(ring->l2_accel, interface->l2_accel);
/* configure backlink on ring */
ring->q_vector = q_vector;
/* apply Rx specific ring traits */
ring->count = interface->rx_ring_count;
ring->queue_index = rxr_idx;
/* assign ring to interface */
interface->rx_ring[rxr_idx] = ring;
/* update count and index */
rxr_count--;
rxr_idx += v_count;
/* push pointer to next ring */
ring++;
}
fm10k_dbg_q_vector_init(q_vector);
return 0;
}
/**
* fm10k_free_q_vector - Free memory allocated for specific interrupt vector
* @interface: board private structure to initialize
* @v_idx: Index of vector to be freed
*
* This function frees the memory allocated to the q_vector. In addition if
* NAPI is enabled it will delete any references to the NAPI struct prior
* to freeing the q_vector.
**/
static void fm10k_free_q_vector(struct fm10k_intfc *interface, int v_idx)
{
struct fm10k_q_vector *q_vector = interface->q_vector[v_idx];
struct fm10k_ring *ring;
fm10k_dbg_q_vector_exit(q_vector);
fm10k_for_each_ring(ring, q_vector->tx)
interface->tx_ring[ring->queue_index] = NULL;
fm10k_for_each_ring(ring, q_vector->rx)
interface->rx_ring[ring->queue_index] = NULL;
interface->q_vector[v_idx] = NULL;
netif_napi_del(&q_vector->napi);
kfree_rcu(q_vector, rcu);
}
/**
* fm10k_alloc_q_vectors - Allocate memory for interrupt vectors
* @interface: board private structure to initialize
*
* We allocate one q_vector per queue interrupt. If allocation fails we
* return -ENOMEM.
**/
static int fm10k_alloc_q_vectors(struct fm10k_intfc *interface)
{
unsigned int q_vectors = interface->num_q_vectors;
unsigned int rxr_remaining = interface->num_rx_queues;
unsigned int txr_remaining = interface->num_tx_queues;
unsigned int rxr_idx = 0, txr_idx = 0, v_idx = 0;
int err;
if (q_vectors >= (rxr_remaining + txr_remaining)) {
for (; rxr_remaining; v_idx++) {
err = fm10k_alloc_q_vector(interface, q_vectors, v_idx,
0, 0, 1, rxr_idx);
if (err)
goto err_out;
/* update counts and index */
rxr_remaining--;
rxr_idx++;
}
}
for (; v_idx < q_vectors; v_idx++) {
int rqpv = DIV_ROUND_UP(rxr_remaining, q_vectors - v_idx);
int tqpv = DIV_ROUND_UP(txr_remaining, q_vectors - v_idx);
err = fm10k_alloc_q_vector(interface, q_vectors, v_idx,
tqpv, txr_idx,
rqpv, rxr_idx);
if (err)
goto err_out;
/* update counts and index */
rxr_remaining -= rqpv;
txr_remaining -= tqpv;
rxr_idx++;
txr_idx++;
}
return 0;
err_out:
fm10k_reset_num_queues(interface);
while (v_idx--)
fm10k_free_q_vector(interface, v_idx);
return -ENOMEM;
}
/**
* fm10k_free_q_vectors - Free memory allocated for interrupt vectors
* @interface: board private structure to initialize
*
* This function frees the memory allocated to the q_vectors. In addition if
* NAPI is enabled it will delete any references to the NAPI struct prior
* to freeing the q_vector.
**/
static void fm10k_free_q_vectors(struct fm10k_intfc *interface)
{
int v_idx = interface->num_q_vectors;
fm10k_reset_num_queues(interface);
while (v_idx--)
fm10k_free_q_vector(interface, v_idx);
}
/**
* f10k_reset_msix_capability - reset MSI-X capability
* @interface: board private structure to initialize
*
* Reset the MSI-X capability back to its starting state
**/
static void fm10k_reset_msix_capability(struct fm10k_intfc *interface)
{
pci_disable_msix(interface->pdev);
kfree(interface->msix_entries);
interface->msix_entries = NULL;
}
/**
* f10k_init_msix_capability - configure MSI-X capability
* @interface: board private structure to initialize
*
* Attempt to configure the interrupts using the best available
* capabilities of the hardware and the kernel.
**/
static int fm10k_init_msix_capability(struct fm10k_intfc *interface)
{
struct fm10k_hw *hw = &interface->hw;
int v_budget, vector;
/* It's easy to be greedy for MSI-X vectors, but it really
* doesn't do us much good if we have a lot more vectors
* than CPU's. So let's be conservative and only ask for
* (roughly) the same number of vectors as there are CPU's.
* the default is to use pairs of vectors
*/
v_budget = max(interface->num_rx_queues, interface->num_tx_queues);
v_budget = min_t(u16, v_budget, num_online_cpus());
/* account for vectors not related to queues */
v_budget += NON_Q_VECTORS(hw);
/* At the same time, hardware can only support a maximum of
* hw.mac->max_msix_vectors vectors. With features
* such as RSS and VMDq, we can easily surpass the number of Rx and Tx
* descriptor queues supported by our device. Thus, we cap it off in
* those rare cases where the cpu count also exceeds our vector limit.
*/
v_budget = min_t(int, v_budget, hw->mac.max_msix_vectors);
/* A failure in MSI-X entry allocation is fatal. */
interface->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
GFP_KERNEL);
if (!interface->msix_entries)
return -ENOMEM;
/* populate entry values */
for (vector = 0; vector < v_budget; vector++)
interface->msix_entries[vector].entry = vector;
/* Attempt to enable MSI-X with requested value */
v_budget = pci_enable_msix_range(interface->pdev,
interface->msix_entries,
MIN_MSIX_COUNT(hw),
v_budget);
if (v_budget < 0) {
kfree(interface->msix_entries);
interface->msix_entries = NULL;
return v_budget;
}
/* record the number of queues available for q_vectors */
interface->num_q_vectors = v_budget - NON_Q_VECTORS(hw);
return 0;
}
/**
* fm10k_cache_ring_qos - Descriptor ring to register mapping for QoS
* @interface: Interface structure continaining rings and devices
*
* Cache the descriptor ring offsets for Qos
**/
static bool fm10k_cache_ring_qos(struct fm10k_intfc *interface)
{
struct net_device *dev = interface->netdev;
int pc, offset, rss_i, i, q_idx;
u16 pc_stride = interface->ring_feature[RING_F_QOS].mask + 1;
u8 num_pcs = netdev_get_num_tc(dev);
if (num_pcs <= 1)
return false;
rss_i = interface->ring_feature[RING_F_RSS].indices;
for (pc = 0, offset = 0; pc < num_pcs; pc++, offset += rss_i) {
q_idx = pc;
for (i = 0; i < rss_i; i++) {
interface->tx_ring[offset + i]->reg_idx = q_idx;
interface->tx_ring[offset + i]->qos_pc = pc;
interface->rx_ring[offset + i]->reg_idx = q_idx;
interface->rx_ring[offset + i]->qos_pc = pc;
q_idx += pc_stride;
}
}
return true;
}
/**
* fm10k_cache_ring_rss - Descriptor ring to register mapping for RSS
* @interface: Interface structure continaining rings and devices
*
* Cache the descriptor ring offsets for RSS
**/
static void fm10k_cache_ring_rss(struct fm10k_intfc *interface)
{
int i;
for (i = 0; i < interface->num_rx_queues; i++)
interface->rx_ring[i]->reg_idx = i;
for (i = 0; i < interface->num_tx_queues; i++)
interface->tx_ring[i]->reg_idx = i;
}
/**
* fm10k_assign_rings - Map rings to network devices
* @interface: Interface structure containing rings and devices
*
* This function is meant to go though and configure both the network
* devices so that they contain rings, and configure the rings so that
* they function with their network devices.
**/
static void fm10k_assign_rings(struct fm10k_intfc *interface)
{
if (fm10k_cache_ring_qos(interface))
return;
fm10k_cache_ring_rss(interface);
}
static void fm10k_init_reta(struct fm10k_intfc *interface)
{
u16 i, rss_i = interface->ring_feature[RING_F_RSS].indices;
u32 reta;
/* If the Rx flow indirection table has been configured manually, we
* need to maintain it when possible.
*/
if (netif_is_rxfh_configured(interface->netdev)) {
for (i = FM10K_RETA_SIZE; i--;) {
reta = interface->reta[i];
if ((((reta << 24) >> 24) < rss_i) &&
(((reta << 16) >> 24) < rss_i) &&
(((reta << 8) >> 24) < rss_i) &&
(((reta) >> 24) < rss_i))
continue;
/* this should never happen */
dev_err(&interface->pdev->dev,
"RSS indirection table assigned flows out of queue bounds. Reconfiguring.\n");
goto repopulate_reta;
}
/* do nothing if all of the elements are in bounds */
return;
}
repopulate_reta:
fm10k_write_reta(interface, NULL);
}
/**
* fm10k_init_queueing_scheme - Determine proper queueing scheme
* @interface: board private structure to initialize
*
* We determine which queueing scheme to use based on...
* - Hardware queue count (num_*_queues)
* - defined by miscellaneous hardware support/features (RSS, etc.)
**/
int fm10k_init_queueing_scheme(struct fm10k_intfc *interface)
{
int err;
/* Number of supported queues */
fm10k_set_num_queues(interface);
/* Configure MSI-X capability */
err = fm10k_init_msix_capability(interface);
if (err) {
dev_err(&interface->pdev->dev,
"Unable to initialize MSI-X capability\n");
goto err_init_msix;
}
/* Allocate memory for queues */
err = fm10k_alloc_q_vectors(interface);
if (err) {
dev_err(&interface->pdev->dev,
"Unable to allocate queue vectors\n");
goto err_alloc_q_vectors;
}
/* Map rings to devices, and map devices to physical queues */
fm10k_assign_rings(interface);
/* Initialize RSS redirection table */
fm10k_init_reta(interface);
return 0;
err_alloc_q_vectors:
fm10k_reset_msix_capability(interface);
err_init_msix:
fm10k_reset_num_queues(interface);
return err;
}
/**
* fm10k_clear_queueing_scheme - Clear the current queueing scheme settings
* @interface: board private structure to clear queueing scheme on
*
* We go through and clear queueing specific resources and reset the structure
* to pre-load conditions
**/
void fm10k_clear_queueing_scheme(struct fm10k_intfc *interface)
{
fm10k_free_q_vectors(interface);
fm10k_reset_msix_capability(interface);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_1062_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.